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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1560864d4a28ccef989baa434f8ec17312b1981d | 10f6ae12f5af6a0a550bbd902633c591ff1040e2 | /src/lib/liba/exa.cpp | 24d0413d4cbf34ac601b6b4887b974a36ad44d26 | [
"BSD-2-Clause"
] | permissive | headupinclouds/hunter_sandbox | 2b5c92663aa2fac96c7a4ed00162b468bf0e70ec | a97fd587d9922ba2a68c74a96da4b30cdfe5a5b5 | refs/heads/master | 2021-01-17T09:04:21.652048 | 2016-05-21T14:53:44 | 2016-05-21T14:53:44 | 37,385,592 | 1 | 2 | null | 2016-05-21T14:51:19 | 2015-06-13T19:49:16 | CMake | UTF-8 | C++ | false | false | 66 | cpp | exa.cpp | #include "liba/exa.hpp"
int funca(int x, int y) { return x + y; }
|
9b7ec15a706d90f41c77320663ce44eb602334a5 | ca0c17e84d2082db1097628393c4373696a425d3 | /src/optimization/glpk_optimizer_implementation.cpp | f46d729d944589b9ada48187d2c98b2c74370027 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | GridOPTICS/GridPACK | cc7475c427133987ef0e6ce1a050f83593a8d0dc | 8ba94936b204a3c0fbcdc97a10c8eebc1cc25609 | refs/heads/develop | 2023-09-03T13:24:53.364094 | 2023-08-28T16:19:20 | 2023-08-28T16:19:20 | 22,120,575 | 42 | 16 | null | 2023-09-05T14:55:21 | 2014-07-22T21:01:57 | C++ | UTF-8 | C++ | false | false | 3,405 | cpp | glpk_optimizer_implementation.cpp | // -------------------------------------------------------------
// file: glpk_optimizer_implementation.cpp
// -------------------------------------------------------------
// -------------------------------------------------------------
// Battelle Memorial Institute
// Pacific Northwest Laboratory
// -------------------------------------------------------------
// -------------------------------------------------------------
// Created September 16, 2015 by William A. Perkins
// Last Change: 2016-12-08 14:59:33 d3g096
// -------------------------------------------------------------
#include <algorithm>
#include <fstream>
#include <glpk.h>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include "glpk_optimizer_implementation.hpp"
namespace gridpack {
namespace optimization {
// -------------------------------------------------------------
// class GLPKOptimizerImplementation
// -------------------------------------------------------------
// -------------------------------------------------------------
// GLPKOptimizerImplementation:: constructors / destructor
// -------------------------------------------------------------
GLPKOptimizerImplementation::GLPKOptimizerImplementation(const parallel::Communicator& comm)
: LPFileOptimizerImplementation(comm)
{
}
GLPKOptimizerImplementation::~GLPKOptimizerImplementation(void)
{
}
// -------------------------------------------------------------
// GLPKOptimizerImplementation::p_solve
// -------------------------------------------------------------
void
GLPKOptimizerImplementation::p_solve(const p_optimizeMethod& m)
{
parallel::Communicator comm(this->communicator());
int nproc(comm.size());
int me(comm.rank());
std::ofstream tmp;
LPFileOptimizerImplementation::p_solve(m);
if (p_runMaybe) {
int ierr;
glp_prob *lp = glp_create_prob();
std::cout << p_outputName << std::endl;
ierr = glp_read_lp(lp, NULL, p_outputName.c_str());
if (ierr != 0) {
std::string msg =
boost::str(boost::format("GLPK LP parse failure, code = %d") % ierr);
glp_delete_prob(lp);
throw gridpack::Exception(msg);
}
ierr = glp_simplex(lp, NULL);
if (ierr != 0) {
std::string msg =
boost::str(boost::format("GLPK optimizer failure, code = %d") % ierr);
glp_delete_prob(lp);
throw gridpack::Exception(msg);
}
comm.barrier();
for (int p = 0; p < nproc; ++p) {
if (p == me) {
std::cout << "Optimimal variable values (process " << me << "):" << std::endl;
int varnum(glp_get_num_cols(lp));
for (int idx = 1; idx <= varnum; ++idx) {
std::string gname(glp_get_col_name(lp, idx));
VariablePtr v(p_allVariables[gname]);
std::string vname(v->name());
std::cout << gname << " " << vname << " "
<< glp_get_col_prim(lp, idx) << " "
<< glp_get_col_dual(lp, idx) << " "
<< std::endl;
SetVariableInitial vset(glp_get_col_prim(lp, idx));
v->accept(vset);
}
VariableTable vtab(std::cout);
BOOST_FOREACH(VarMap::value_type& i, p_allVariables) {
i.second->accept(vtab);
}
}
comm.barrier();
}
glp_delete_prob(lp);
}
}
} // namespace optimization
} // namespace gridpack
|
6ddbd8e4251ccaec19197ac68c7cb995ceacf0ff | 4a727d0b9de7492f4ef1a53e37340bff2ad7d21d | /10142.cpp | acf1c725a8e1d869209caf4b699089042dd8c950 | [] | no_license | iamedu/uva | e9f08704b6983f9aa0fe83a0bba2d104242d760c | ef56371229f657c981063d120664e7e4a5b05210 | refs/heads/master | 2021-01-23T08:39:13.592552 | 2012-11-19T14:59:19 | 2012-11-19T14:59:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,700 | cpp | 10142.cpp | #include <iostream>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <algorithm>
#include <utility>
using namespace std;
class Ballot {
public:
list<int> votes;
int get_vote() { return votes.front(); }
void delete_vote() { votes.pop_front(); }
void push_vote(int index) { votes.push_back(index); }
};
int main() {
int cases;
cin >> cases;
cin.ignore(100, '\n');
cin.ignore(100, '\n');
while(cases--) {
int candidates;
int min_votes = 0;
cin >> candidates;
cin.ignore(100, '\n');
vector<string> names(candidates + 1);
vector<int> votes(candidates + 1);
list<Ballot *> ballots;
fill(votes.begin(), votes.end(), 0);
for(int i = 1; i <= candidates; i++) {
char name[256];
cin.getline(name, 256);
names[i] = name;
}
while(cin.peek() != '\n' && !cin.eof()) {
min_votes++;
Ballot *b = new Ballot();
for(int i = 0; i < candidates; i++) {
int tmp;
cin >> tmp;
b->push_vote(tmp);
}
cin.ignore(100, '\n');
ballots.push_back(b);
votes[b->get_vote()]++;
}
cin.ignore(100, '\n');
min_votes /= 2;
while(true) {
vector<int> mins;
vector<int> deleted;
int min = 1001;
bool found = false;
//check if have same votes
bool same_votes = true;
int vote_count = 0;
for(vector<int>::iterator it = votes.begin() + 1; it != votes.end(); it++) {
int pos = it - votes.begin();
if(*it > min_votes) {
cout << names[pos] << endl;
found = true;
same_votes = false;
break;
}
if(*it > 0) {
if(vote_count == 0) vote_count = *it;
if(*it != vote_count) same_votes = false;
}
if(*it == 0 && !binary_search(deleted.begin(), deleted.end(), pos)) {
deleted.push_back(pos);
}
if(*it > 0 && *it < min) {
mins.clear();
mins.push_back(pos);
min = *it;
} else if(*it == min) {
mins.push_back(pos);
}
}
if(same_votes) {
for(vector<int>::iterator it = votes.begin() + 1; it != votes.end(); it++) {
int pos = it - votes.begin();
if(*it > 0) cout << names[pos] << endl;
}
break;
}
if(found) break;
else {
for(vector<int>::iterator it = mins.begin(); it != mins.end(); it++) {
votes[*it] = 0;
deleted.push_back(*it);
}
sort(deleted.begin(), deleted.end());
for(list<Ballot *>::iterator it = ballots.begin(); it != ballots.end(); it++) {
Ballot *b = *it;
if(binary_search(deleted.begin(), deleted.end(), b->get_vote())) {
while(binary_search(deleted.begin(), deleted.end(), b->get_vote())) {
b->delete_vote();
}
votes[b->get_vote()]++;
}
}
}
}
if(cases > 0) cout << endl;
}
return 0;
}
|
21489418353da875c78492f9d10044c4d2932414 | f36cab2b1ad98a84fef194d8176919b3d03f7f8a | /ModelViewer/ViewerFoundation/Meshes/NuoMeshBounds.h | eaf557c07e8a4d9c4bf2d262a3abd3dc9cfe10d0 | [
"BSD-3-Clause"
] | permissive | middlefeng/NuoModelViewer | 74b82d417ee2454f3b7113a82bf66d2bcb9b6bc1 | eb0996b4a8c5559da3d279dc356dc3a27bde5acd | refs/heads/master | 2023-07-25T20:05:46.599373 | 2023-07-25T04:42:25 | 2023-07-25T04:42:25 | 67,608,101 | 314 | 44 | MIT | 2020-01-24T19:28:22 | 2016-09-07T13:17:01 | C++ | UTF-8 | C++ | false | false | 311 | h | NuoMeshBounds.h | //
// NuoMeshBounds.h
// ModelViewer
//
// Created by Dong on 1/25/18.
// Copyright © 2018 middleware. All rights reserved.
//
#ifndef __MESH_BOUNDS_H__
#define __MESH_BOUNDS_H__
#include "NuoBounds.h"
class NuoMeshBounds
{
public:
NuoBounds boundingBox;
NuoSphere boundingSphere;
};
#endif
|
ad2561020fca8615d9dbef6f31a6109825cc1112 | ab39958758a7d637d52783a3e6f28a1fc94fee48 | /cplusplus-SchoolBook/7.6/7.6.cpp | e2ef0539e2e9e86bb9d7f33cf4cd56809882f321 | [] | no_license | YouChowMein/C-plus-plus | 4089fb8a8a8dd3b188a24dd81e9cfdec130096d1 | 0a637c54513758f9f164a9f9ca0d163e12c8356b | refs/heads/master | 2020-03-10T22:00:59.055085 | 2018-05-16T16:17:50 | 2018-05-16T16:17:50 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 992 | cpp | 7.6.cpp | #include<iostream>
using namespace std;
int main(void)
{
const int M = 5, N = 4;
int i, j, score[M][N], //score存放成绩
sum[M] = { 0 }; //sum存放每人的总分
float ave[N] = { 0 }; //存放每门课的平均分
for (int i = 0; i < M; i++)
{
cout << "输入第" << i + 1 << "名学生的成绩:" << endl;
for (int j = 0; j < N; j++)
{
cin >> score[i][j]; //输入一个成绩
sum[i] += score[i][j]; //累加到对应个人的总分数组元素中
ave[j] += score[i][j]; //累加到对应课程的平均分数组元素中
}
}
for (j = 0; j < N; j++) ave[j] /= M; //计算每门课程的平均分
cout << "\t政治\t数学\t英语\tC++\t总分\n";
for (i = 0; i < M; i++) //输出成绩与结果
{
for (j = 0; j < N; j++) cout << '\t' << score[i][j];
cout << '\t' << sum[i] << endl;
}
cout << "均分:";
for (j = 0; j < N; j++) cout << '\t' << ave[j];
system("pause");
return 0;
}
|
db2884a92b3f824aa835a54ca26472262c552463 | 716d13a37ad5b13615e90947c467ac1b829d0334 | /trace_server/utils/history.h | 435f18f5cc297424838b0096a728d13f6c0ff58a | [
"MIT"
] | permissive | mojmir-svoboda/DbgToolkit | 0a2302647975d66ad4d6f5a610c5f3fd014b5d19 | 590887987d0856032be906068a3103b6ce31d21c | refs/heads/master | 2021-01-17T02:58:26.706748 | 2017-11-15T13:32:13 | 2017-11-15T13:32:13 | 19,892,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,798 | h | history.h | #pragma once
#include <vector>
#include <memory>
#include <boost/call_traits.hpp>
#include <functional>
#include <algorithm>
#include "hash.h"
template <typename KeyT>
struct ItemInfo
{
unsigned m_ref_count;
unsigned m_hash;
KeyT m_key;
ItemInfo () : m_ref_count(0), m_hash(0) { }
ItemInfo (typename boost::call_traits<KeyT>::param_type key)
: m_ref_count(0), m_hash(static_cast<unsigned>(hash<KeyT>()(key))), m_key(key) { }
friend bool operator< (ItemInfo const & lhs, ItemInfo const & rhs)
{
return rhs.m_ref_count < lhs.m_ref_count; // @NOTE: reverse order rhs < lhs
}
friend bool operator== (ItemInfo const & lhs, ItemInfo const & rhs)
{
return lhs.m_key == rhs.m_key;
}
template <class ArchiveT>
void serialize (ArchiveT & ar, unsigned const version)
{
ar & boost::serialization::make_nvp("ref_count", m_ref_count);
ar & boost::serialization::make_nvp("hash", m_hash);
ar & boost::serialization::make_nvp("key", m_key);
}
};
template <typename KeyT>
struct History
{
unsigned m_key_limit;
int m_current_item;
typedef KeyT key_t;
typedef std::vector<ItemInfo<key_t> > dict_t;
typedef typename dict_t::iterator it_t;
typedef typename dict_t::const_iterator const_it_t;
dict_t m_dict;
History (unsigned item_limit)
: m_key_limit(item_limit)
, m_current_item(-1)
{
m_dict.reserve(m_key_limit);
}
void sort () { std::sort(m_dict.begin(), m_dict.end()); }
void insert (typename boost::call_traits<KeyT>::param_type key)
{
unsigned const key_hash = static_cast<unsigned>(hash<KeyT>()(key));
for (size_t i = 0, ie = m_dict.size(); i < ie; ++i)
{
if (m_dict[i].m_hash == key_hash && m_dict[i].m_key == key)
{
++m_dict[i].m_ref_count;
return;
}
}
sort();
// item not found, replace another
if (m_dict.size() >= m_key_limit)
m_dict.pop_back();
m_dict.push_back(ItemInfo<KeyT>(key));
}
void insert_no_refcount (typename boost::call_traits<KeyT>::param_type key)
{
if (!find(key))
m_dict.push_back(ItemInfo<KeyT>(key));
}
bool find (typename boost::call_traits<KeyT>::param_type key)
{
unsigned const key_hash = static_cast<unsigned>(hash<KeyT>()(key));
for (size_t i = 0, ie = m_dict.size(); i < ie; ++i)
if (m_dict[i].m_hash == key_hash && m_dict[i].m_key == key)
return true;
return false;
}
void remove (typename boost::call_traits<KeyT>::param_type key)
{
m_dict.erase(std::remove(m_dict.begin(), m_dict.end(), key), m_dict.end());
}
template <class ArchiveT>
void serialize (ArchiveT & ar, unsigned const version)
{
ar & boost::serialization::make_nvp("dict", m_dict);
ar & boost::serialization::make_nvp("current_item", m_current_item);
}
size_t size () const { return m_dict.size(); }
KeyT const & operator[] (size_t i) const { return m_dict[i].m_key; }
};
|
f0c497eef5dade909a44972c34b3423940a845b7 | 882aecfb6a4ce598fb2dde075fe5be466b9ec515 | /include/programmer.h | 4624ace90f194c77dda4a8eea4fb1be346086674 | [
"MIT"
] | permissive | pololu/pololu-usb-avr-programmer-v2 | 5aa48049389d893d3759f895df01f464f243fbb8 | c6dfe014718511459ec4e4d75599c2baf748af80 | refs/heads/master | 2023-06-23T23:22:27.975110 | 2023-06-20T15:57:35 | 2023-06-20T15:57:35 | 53,175,299 | 16 | 4 | NOASSERTION | 2023-06-20T15:58:15 | 2016-03-05T00:55:53 | C++ | UTF-8 | C++ | false | false | 6,304 | h | programmer.h | // Copyright (C) Pololu Corporation. See www.pololu.com for details.
/** Main header file for the C++ library libpavrpgm.
*
* This library supports communciating with the Pololu USB AVR Programmer v2.
*
* This is only intended to be used as a static library by the other projects in
* this repository. The interface described in this header is considered to be
* an internal implementation detail, and it may change at any time.
*/
#pragma once
#include <libusbp.hpp>
#include <vector>
#include <string>
#include <cstdint>
#include "pavr2_protocol.h"
#include "programmer_frequency_tables.h"
/** The maximum firmware major version supported by this program. If we make a
* breaking change in the firmware, we can use this to be sure that old software
* will not try to talk to new firmware and mess something up. */
#define PAVR2_FIRMWARE_VERSION_MAJOR_MAX 1
struct ProgrammerSettings;
struct ProgrammerVariables;
class Programmer
{
public:
Programmer() = delete;
// Gets the name (string with a number of kHz) of the maximum ISP frequency.
// This is only used by the programmer if SCK_DURATION is 0.
static std::string getMaxFrequencyName(uint32_t ispFastestPeriod);
// Sets the maximum frequency by its name. The name must exactly match
// one of the allowed values.
static void setMaxFrequency(ProgrammerSettings &, std::string maxFrequencyName);
// Gets the name (string with a number of kHz) of the frequency actually
// being used by the programmer, which depends on two parameters:
// SCK_DURATION and ISP_FASTEST_PERIOD.
static std::string getFrequencyName(uint32_t sckDuration, uint32_t ispFastestPeriod);
// Sets the actual frequency being used by the programmer by its name. The
// name must exactly match one of the allowed values. This function always
// sets SCK_DURATION, and it only sets ISP_FASTEST_PERIOD if necessary.
static void setFrequency(ProgrammerSettings &, std::string frequencyName);
static std::string convertProgrammingErrorToShortString(uint8_t programmingError);
// This long string does not stand alone (e.g. it could be empty if there was
// no error or an unknown error). It should also be displayed below the
// output of convertProgrammingErrorToShortString.
static std::string convertProgrammingErrorToLongString(uint8_t programmingError);
static std::string convertDeviceResetToString(uint8_t deviceReset);
static std::string convertRegulatorModeToString(uint8_t regulatorMode);
static std::string convertRegulatorLevelToString(uint8_t regulatorLevel);
static std::string convertLineFunctionToString(uint8_t lineFunction);
};
class ProgrammerInstance
{
public:
ProgrammerInstance();
explicit ProgrammerInstance(
libusbp::device, libusbp::generic_interface, uint16_t product_id,
std::string serialNumber, uint16_t firmwareVersion);
std::string getName() const;
// An operating system-specific identifier for this device.
std::string getOsId() const;
std::string getSerialNumber() const;
uint16_t getFirmwareVersion() const;
// Returns a string like "1.03", not including any firmware modification codes.
// See ProgrammerHandle::getFirmwareVersionString().
std::string getFirmwareVersionString() const;
uint8_t getFirmwareVersionMajor() const;
uint8_t getFirmwareVersionMinor() const;
std::string getProgrammingPortName() const;
std::string getTtlPortName() const;
/** Same as getProgrammingPortName but it returns "(unknown)" instead of
* throwing exceptions from the USB library. */
std::string tryGetProgrammingPortName() const;
/** Same as getTtlPortName but it returns "(unknown)" instead of throwing
* exceptions from the USB library. */
std::string tryGetTtlPortName() const;
operator bool() const;
libusbp::device usbDevice;
libusbp::generic_interface usbInterface;
private:
uint16_t productId;
std::string serialNumber;
uint16_t firmwareVersion;
};
std::vector<ProgrammerInstance> programmerGetList();
// [all-settings]
struct ProgrammerSettings
{
uint32_t sckDuration = 0;
uint32_t ispFastestPeriod = 0;
uint8_t regulatorMode = 0;
bool vccOutputEnabled = 0;
uint8_t vccOutputIndicator = 0;
uint8_t lineAFunction = 0;
uint8_t lineBFunction = 0;
uint32_t vccVddMaxRange = 0; // units: mV
uint32_t vcc3v3Min = 0; // units: mV
uint32_t vcc3v3Max = 0; // units: mV
uint32_t vcc5vMin = 0; // units: mV
uint32_t vcc5vMax = 0; // units: mV
uint32_t hardwareVersion = 0;
uint32_t softwareVersionMajor = 0;
uint32_t softwareVersionMinor = 0;
};
struct ProgrammerVariables
{
uint8_t lastDeviceReset = 0;
bool hasResultsFromLastProgramming = 0;
uint8_t programmingError = 0;
uint16_t targetVccMeasuredMinMv = 0;
uint16_t targetVccMeasuredMaxMv = 0;
uint16_t programmerVddMeasuredMinMv = 0;
uint16_t programmerVddMeasuredMaxMv = 0;
uint16_t targetVccMv = 0;
uint16_t programmerVddMv = 0;
uint8_t regulatorLevel = 0;
bool inProgrammingMode = 0;
};
struct ProgrammerDigitalReadings
{
uint8_t portA;
uint8_t portB;
uint8_t portC;
};
class ProgrammerHandle
{
public:
ProgrammerHandle();
explicit ProgrammerHandle(ProgrammerInstance);
void close();
const ProgrammerInstance & getInstance() const;
operator bool() const
{
return handle;
}
// Returns the firmware version string, including any modification
// codes (e.g. "1.07nc").
std::string getFirmwareVersionString();
ProgrammerSettings getSettings();
void validateSettings(const ProgrammerSettings &);
void applySettings(const ProgrammerSettings &);
void restoreDefaults();
ProgrammerVariables getVariables();
ProgrammerDigitalReadings digitalRead();
private:
uint8_t getRawSetting(uint8_t id);
void setRawSetting(uint8_t id, uint8_t value);
uint8_t getRawVariable(uint8_t id);
std::string cachedFirmwareVersion;
libusbp::generic_handle handle;
ProgrammerInstance instance;
};
// Returns true if a Pololu USB AVR Programmer (pgm03a) is connected
// to the computer.
bool pgm03aPresent();
extern const char * pgm03aMessage;
|
bdf3177425bd7fc4ca08eecc39bb42220485ec86 | 935a7ffba3674ebb3ac26005b5297393b7c46dd0 | /TP3/exo3.cc | 0a892b05a8e47113c4875ae6cb666f92eddebfc6 | [] | no_license | karshann/language-avanc-e | 1277acce9b57e5b55273d352e2d8fdfa0135fc59 | b375a1f3fdb4d7534a6f269b2240c0f4bf4c1dd4 | refs/heads/master | 2020-04-01T23:32:50.232382 | 2018-10-26T09:15:58 | 2018-10-26T09:15:58 | 153,763,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,480 | cc | exo3.cc |
class Node{
friend class
// Variable membre
private ::
int integer;
Node *nextNode;
//Methodes
public:
//Constructeur
Node(int i=0)
{
integer=i;
nextNode=NULL;
}
~Node();
{
//Ce destruvteur fonctionne recursivement ( avalanche de destruction ).
// La destruction entraine la destruction du noeud suivant etc .
if(nextNode)delete nextNode;
}
int GetInt() {return integer;}
Node =GetNextNode(){return nextNode;}
};
class CList
{
protected:
Node *head;
int length;
public :
CList()
{
head=NULL;
length=0;
}
//Si on veut un destructeur virtuel , il faut laisser sa definition pour les classes derivées
//Dans cet exemple , on laisse le soin de la destruction à la classe de base car
//cette destrution est la meme pour les piles et les files.
~CListe()
{
delete head;
head=NULL;
length=0;
}
friend ostream& operator <<(ostream&, CList&);
virtual CList & operator <(int)=0;
CList & operator >(int &i)
{
if(!head)
{
cout<<" la pile est vide \n";
return *this;
}
//retire la tete de la pile et mettre sa valeur dans la variable passée en argument
i=head->integer;
Node *tmp=head;
head=head->nextNode;
tmp->nextNode=NULL; // Pour eviter l'effacement recursif
delete tmp;
return *this;
}
};
ostream& operator <<(ostream &out,CList& clist)
{
Node *curNode=CList.head;
for(int i=0;i<list.length;i++)
{
out<<curNode->GetInt()<<" ";
curNode=curNide->GetNextNode();
}
return out;
}
class CPile : public CList
{
public:
CPile():CList(){}
virtual CList & operator <(int i)
{
Node *newNode=new Node[i];
newNode->nextNode=head;
head=newNode;
length++;
return *this;
}
}
class CFile : public CList
{
public :
CFile():CList(){}
//Empile un entier a la fin de la file
virtual CList & operator <(int i )
{
Node *newNode=new Node(i)
if(!head)
head=newNode;
else
{
Node *n=head;
while(n->nextNode)
n=n->nextNode;
n->nextNode=newNode;
}
length++;
return *this;
}
};
void main(){
CPile pile;
CFile file;
CList* ptList = &file;
* ptList < 0 < 1; //empiler deux valeurs dans la file
cout << * ptList;
int i;
* ptList > i; //récupérer une valeur de la file dans i
cout << * ptList << " i=" << i;
ptList = &pile;
* ptList < 0 < 1; //empiler deux valeurs dans la pile
cout << *ptPile;
* ptList > i; //récupérer une valeur de la pile dans i
cout << * ptList << " i=" << i;
}
|
24c4c0334e435d533234997a00f0936a4e88398a | f03cc2d3b830f6a616af40815815020ead38b992 | /FairyEngine/Source/F3DEngine/F3DJPGCodec.h | a85a5daa64a4372a9771db4c250bd47beed7a940 | [] | no_license | yish0000/Fairy3D | 18d88d13e2a3a3e466d65db7aea06a8b111118ba | 6b84c6cb6c58a383e53a6a7f64676667c159c76b | refs/heads/master | 2021-07-01T16:37:14.887464 | 2020-11-08T14:52:01 | 2020-11-08T14:52:01 | 12,029,469 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,248 | h | F3DJPGCodec.h | /*
* ------------------------------------------------------------------------
* Name: F3DJPGCodec.h
* Desc: 本文件为引擎定义了一个JPEG图像解码器。
* Author: Yish
* Date: 2010/11/16
* ----------------------------------------------------------------------
* CopyRight (C) YishSoft. 2010 All right Observed.
* ------------------------------------------------------------------------
*/
#ifndef __F3D_JPGCODEC_H__
#define __F3D_JPGCODEC_H__
//// HEADERS OF THIS FILE /////////////////////////////////////////////////
#include "F3DImageCodec.h"
///////////////////////////////////////////////////////////////////////////
/** JPEG图像解码器
*/
class FAIRY_API F3DJPGCodec : public F3DImageCodec
{
#ifdef USE_IJL_LIB
private:
F_DLIB_HANDLE m_hDll; // Intel JPEG 动态库句柄
#endif
public:
F3DJPGCodec(void);
~F3DJPGCodec(void);
// 从本地磁盘中加载图像
F3DImage* Load( const char* filename );
// 保存图像的Mipmap到文件
void SaveMipmap( const char* filename,F3DImage* image,size_t level );
};
//////////////////////////////////////////////////////////////////////////
#endif //#ifndef __F3D_JPGCODEC_H__ |
39442d77e09352849106a884796b81def4db7bd7 | 880ba6f0ad1090d5c1d837d0e76d1d767ebe20d8 | /source/second.cpp | e92f451558126df619180a2618da2044fcd077a8 | [] | no_license | jetma/adso | 7657e02978c0afdc35c66a67771841ddbed69f17 | 56fd41696a542cc9a80da60a6ffe06ebfb2e67f3 | refs/heads/master | 2020-06-18T12:32:10.407939 | 2019-03-03T08:49:52 | 2019-03-03T08:49:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 226 | cpp | second.cpp | #include "second.h"
#include "adsotime.h"
#include "text.h"
Second::Second(Text *t, Text *a, Text *b): Time(t, a, b) { myclass += ":Second";};
Second::Second(Text *t): Time(t) { myclass += ":Second";};
Second::~Second() {}
|
24de2f06a839c1679222d5cd93a6dcc73e1b8044 | 28125dc1d0090d864c3414472b0794d3939ff728 | /The Miracle and the Sleeper1.cpp | 49e3afef7c974497ea6b29d938498f8d98dda4a3 | [] | no_license | Wadshah/c-codeforces | d4baeac02ef26ef8ccf4e3add92ecd4094ace582 | 8ea16f66e64910a2076d48aea7b2e9c7892bd55e | refs/heads/main | 2023-08-03T16:22:12.213406 | 2021-09-18T09:00:39 | 2021-09-18T09:00:39 | 407,808,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | cpp | The Miracle and the Sleeper1.cpp | #include<bits/stdc++.h>
#include<iostream>
using namespace std;
#define ll long long int
#define inf 1e18
#define mod 1000000007
const int N=1e5+5;
void file_i_o(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("inputf.in", "r", stdin);
freopen("output.in", "w", stdout);
#endif
}
int main(int argc ,char const *argv[]){
clock_t begin =clock();
file_i_o();
ll t;
cin>>t;
while(t--){
ll a,b,r,i,k,t;
cin>>a>>b;
if(a==b)
cout<<"0";
else{
if(a>(b/2))
cout<<b%(a);
if(a<=b/2){
r=b/2;
k=b%r;
t=b%(r+1);
cout<<max(k,t);
}
}
cout<<endl;
}
#ifndef ONLINE_JUDGE
clock_t end =clock();
cout<<"\n\nExecuted In: "<<double(end - begin) / CLOCKS_PER_SEC*1000<<" ms";
#endif
return 0;
}
|
61c3d226c6b2877c7f5b8322d76ab0cf701fa258 | cc36bf3a46b06af454e42f88865aa2b16caefc2c | /UI_Textures/SignalLayerWidget.hpp | b6f63204b3f5742bc47d49643b7c4aaf7f6736ae | [] | no_license | artcampo/2012_3D_Procedural_Object_Editor | 058548468514da39d1434b024bcf42e17f1e0af4 | ddb75c727bfb12f1d39786dd72928dc35539c860 | refs/heads/master | 2021-01-12T04:27:28.204089 | 2016-12-29T13:57:45 | 2016-12-29T13:57:45 | 77,615,572 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,840 | hpp | SignalLayerWidget.hpp | #ifndef SIGNALLAYOUT_HPP
#define SIGNALLAYOUT_HPP
#include <QPushButton>
#include <QLabel>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QHBoxLayout>
#include <QRadioButton>
#include <QMessageBox>
#include <QFrame>
#include <QGridLayout>
#include <QDir>
#include <QCoreApplication>
#include <QComboBox>
#include <QSlider>
#include <QSharedPointer>
#include <QApplication>
#include <QCheckBox>
#include <sstream>
#include <string>
#include <iostream>
#include "UI_Textures/QD3DWidgetTexture.hpp"
#include "UI_Textures/MinorWidgets/SingleColourWidget.h"
#include "UI_Textures/MinorWidgets/SignalNameButton.hpp"
class ProcShader;
class ProfilerDp;
class SplineNWidget;
class SignalLayerWidget : public QFrame
{
Q_OBJECT
public:
SignalLayerWidget::~SignalLayerWidget();
SignalLayerWidget(QWidget *parent,
Layer* aLayer,
bool aIsLastLayer,
bool aIsAlone,
std::string& aLayerOpName,
ProcShader* aProcShader,
int aChannelId,
QD3DWidgetTexture *aFinalMaterial,
QD3DWidgetTexture *aCurrentSignLay,
ProfilerDp* aProfiler);
int getOpToCompositeId();
string getLayerName();
void loadSignalVariables();
void loadCompositeOperationVariables();
float compositeLayerBlendFactor();
void profileShaderCompile();
void profileRedrawFinal( std::string& tempName, ProfilerDp* prof );
// Qt mouse
public:
void mousePressEvent (QMouseEvent *event);
void mouseMoveEvent (QMouseEvent *event);
void mouseReleaseEvent ( QMouseEvent * event );
void dropEvent(QDropEvent *de);
void dragMoveEvent(QDragMoveEvent *de);
void dragEnterEvent(QDragEnterEvent *event);
void setDragging( bool aValue );
private:
QPoint mDragStartPosition;
bool mDragging;
// copy of pointers to main objects
private:
bool mIsLastLayer;
bool mIsAlone;
int mChannelId;
ProcShader* mProcShader;
QD3DWidgetTexture *mFinalMaterial;
QD3DWidgetTexture *mCurrentSignLay;
// widgets
private:
//QVBoxLayout* mLayout;
QVBoxLayout* mMainLayout;
QGridLayout* mSignalLayout;
QHBoxLayout* mCompOpLayout;
// layer layout
QHBoxLayout* mLayerSignalSuperLayout;
QVBoxLayout* mLayerSignalButtonsLayout;
QPushButton* mDeleteLayerButtton;
QPushButton* mReinitSignalButtton;
QComboBox* mChooseSignal;
QComboBox* mChooseSignalType;
// signal layout
QLabel* mLayerLabel;
QLabel* mInputParamsLabel;
QComboBox* mChooseInputParams;
QCheckBox* mWeightLabel;
QSlider* mChooseWeightX;
QSlider* mChooseWeightY;
QSlider* mChooseWeightZ;
QSpinBox* mOctSpin;
QDoubleSpinBox* mOctMultSpin;
SplineNWidget* m2GradientPicker;
// Signal: warp
QComboBox* mChooseSignalWarp;
QDoubleSpinBox* mWarpLengthSpin;
QCheckBox* mWarpCheckBox;
string mWarpSignalName;
// Signal: lines
QCheckBox* mFreq1Label;
QCheckBox* mPhaseLabel;
QLabel* mThresholdLabel;
bool mFreq1SliderSingleValue;
QSlider* mFreq1SliderX;
QSlider* mFreq1SliderY;
QSlider* mFreq1SliderZ;
bool mPhaseSliderSingleValue;
QSlider* mPhaseSliderX;
QSlider* mPhaseSliderY;
QSlider* mPhaseSliderZ;
//QDoubleSpinBox* mFreq2Spin;
QDoubleSpinBox* mThresholdSpin;
// composed op layout
QComboBox* mChooseOperation;
QSlider* mOpBlendFactorSlider;
// SIGNAL: khan-1
QDoubleSpinBox* mFreq1floatSpin;
QDoubleSpinBox* mFreq2floatSpin;
private:
int mIndexOfLayerSignal;
bool mInhibitSignalChangedSlot;
bool mNewLayerOpModeSet;
private:
std::string mNameLayer; //Main Layer-Signal
std::string mSignal; //its signal
int mSignalType;
std::string mCompositeLayerOpName; //its composite operation
int mCompositeLayerOpId;
float mCompositeLayerOpBlend;
// SIGNAL: General
int mColorId;
std::vector<D3DXCOLOR> mColor;
int mInputParams;
D3DXVECTOR3 mNoiseW;
int mNoiseNoct;
float mNoiseMoct;
// SIGNAL: noise
//TODO: remove
float mTurbulence;
QSlider* mTurbulenceSlider;
// SIGNAL: Lines / Strips
D3DXVECTOR3 mFreq1;
D3DXVECTOR3 mPhase;
float mThreshold;
D3DXVECTOR3 mComposedFreq1;
// SIGNAL: khan-1
float mFreq1float;
float mFreq2float;
//PROFILING
private:
ProfilerDp* mProfiler; //just pointer
std::wstring makeShaderFilePath ( std::string& aActualSignal );
public:
void redrawSignalPreview();
void redrawFinal();
private:
void loadWidgetsSignalGeneral();
void loadWidgetsSignalNoise();
void loadWidgetsSignalNoiseSin();
void loadWidgetsSignalStrips();
void loadWidgetsSignalLines();
void loadWidgetsSignalKhan1();
D3DXVECTOR3 getDifferentValue( float v1, float v2, float v3 );
private slots:
void signalChanged();
void signalOpChanged( int aOpId );
void signalOpBlendChanged();
void signalTypeChanged();
void signalToBeDeleted();
void signalToBeReinitialized();
void changeSignalOfLayer( const QString& aSelectedSignal );
void changeWarpSignalOfLayer(const QString& aSelectedWarpSignal );
signals:
void forceReloadLayersAndSignals();
void forceReloadSignals();
void setDragSource( const std::string, const bool );
void setDragDestination( const std::string, const bool );
void forceDeleteListLayerAndSignal();
};
#endif // SIGNALLAYOUT_HPP
|
599671ac9da79e26d760fc5cb0c52126a1651757 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/mutt/gumtree/mutt_repos_function_1337_mutt-1.7.2.cpp | c8a9cf07c527c17620cd8e237d8ebc19edb7027e | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 175 | cpp | mutt_repos_function_1337_mutt-1.7.2.cpp | void menu_last_entry (MUTTMENU *menu)
{
if (menu->max)
{
menu->current = menu->max - 1;
menu->redraw = REDRAW_MOTION;
}
else
mutt_error _("No entries.");
} |
dfb636fca574536d6814bcd849b179233f469dbe | 8267336ce840fadfd64ab9b5753cbedef391159c | /C++/Blackjack (C++)/Blackjack.cpp | 0f936132fc93245d3eb35dd1456bbd843dcf838d | [] | no_license | beaugoldberg/Programming-C | 7b6a634997289f5edc3b6be37263f18d49db0729 | 8a040a076512ba571594242ee1dbd25d66dd76da | refs/heads/main | 2023-01-21T16:16:18.898025 | 2020-11-13T05:14:00 | 2020-11-13T05:14:00 | 312,479,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,668 | cpp | Blackjack.cpp | #include <iostream>
#include <string>
#include <vector>
#include "Blackjack.h"
using namespace std;
void Blackjack::displayIntro()
{
cout << "********************************" << endl;
cout << "** Welcome to Blackjack! **" << endl;
cout << "********************************" << endl;
cout << "** Winnings **" << endl;
cout << "** -------------------------- **" << endl;
cout << "** Push - 0:0 **" << endl;
cout << "** High Count - 1:1 **" << endl;
cout << "** Natural Blackjack - 3:2 **" << endl;
cout << "********************************" << endl;
}
void Blackjack::displayPlayerHand(Blackjack game)
{
cout << "*****************************" << endl;
cout << " Player hand " << endl;
cout << "*****************************" << endl;
game.printHand(0);
cout << "Your hand total: " << game.updateHandtoPrint() << endl;
}
void Blackjack::displayBustOutro(Blackjack game)
{
cout << endl;
cout << "*****************************" << endl;
cout << "** Bust **" << endl;
cout << "*****************************" << endl;
cout << "Losing hand: " << endl;
game.printHand(0);
cout << "Your hand total: " << game.updateHandValue(0) << endl << endl;
}
void Blackjack::displayDealerBlackjack(Blackjack game)
{
cout << "*****************************" << endl;
cout << "** Winning Dealer Hand **" << endl;
cout << "*****************************" << endl;
for (int i = 0; i < game.dealerDeck.size(); i++) {
game.dealerDeck.at(i).printCard();
}
cout << endl;
}
void Blackjack::displayOutro(int difference)
{
if (difference > 0) { cout << "You won $" << difference << ". Congratulations!" << endl; }
else if (difference < 0) { cout << "You lost $" << difference << ". Better luck next time!" << endl; }
else { cout << "You broke even. Come play again soon to see if you can win!" << endl; }
}
int Blackjack::updateHandValue(int choice)
{
int handValue = 0;
int ace;
int acepath;
int bigAce = 0;
int smallAce = 0;
Card current;
vector<Card> deck;
if (choice == 0) { deck = userHand; }
else if (choice == 1) { deck = dealerDeck; }
for (int i = 0; i < deck.size(); i++)
{
current = deck.at(i);
if (current.getName() == "Ace") {
ace = 1;
acepath = 0;
}
int hypo = handValue + 11;
if (handValue <= 21 && hypo <= 21 && ace == 1 && acepath == 0) {
handValue += 11;
acepath = 1;
bigAce += 1;
}
else if (handValue <= 21 && hypo >= 21 && ace == 1 && acepath == 0) {
handValue += 1;
acepath = 1;
smallAce += 1;
}
else {
handValue += current.getValue();
}
if (handValue > 21 && bigAce == 1) {
handValue -= 10;
bigAce -= 1;
}
}
return handValue;
}
string Blackjack::updateHandtoPrint()
{
int handValue = 0;
int smallValue = 0;
int ace;
int acepath;
int bigAce = 0;
int smallAce = 0;
string biggerValue;
string lesserValue;
Card current;
for (int i = 0; i < userHand.size(); i++)
{
current = userHand.at(i);
if (current.getName() == "Ace") {
ace = 1;
acepath = 0;
}
int hypo = handValue + 11;
if (handValue <= 21 && hypo <= 21 && ace == 1 && acepath == 0) {
handValue += 11;
acepath = 1;
bigAce += 1;
}
else if (handValue <= 21 && hypo >= 21 && ace == 1 && acepath == 0) {
handValue += 1;
acepath = 1;
smallAce += 1;
}
else {
handValue += current.getValue();
}
if (handValue > 21 && bigAce == 1) {
handValue -= 10;
bigAce -= 1;
}
}
if (bigAce == 1 && handValue != 21) {
smallValue = handValue - 10;
lesserValue = to_string(smallValue);
biggerValue = to_string(handValue);
return biggerValue + " or " + lesserValue;
}
else {
biggerValue = to_string(handValue);
return biggerValue;
}
}
void Blackjack::printHand(int choice)
{
vector<Card> deck;
Card currentCard;
if (choice == 0) { deck = userHand; }
else if (choice == 1 || choice == 2) { deck = dealerDeck; }
if (choice == 0 || choice == 1) {
for (int i = 0; i < deck.size(); i++) {
currentCard = deck.at(i);
currentCard.printCard();
}
}
else if (choice == 2) {
Card firstCard = dealerDeck.at(0);
firstCard.printCard();
if (firstCard.getName() == "Ace") {
string ifAce = "1 or 11";
cout << "Dealer hand value: " << ifAce << endl;
}
else {
int value = firstCard.getValue();
cout << "Dealer hand value: " << value << endl;
}
}
}
void Blackjack::addUserHand(Card card)
{
userHand.push_back(card);
}
void Blackjack::addDealerHand(Card card)
{
dealerDeck.push_back(card);
}
void Blackjack::clearHands()
{
userHand.clear();
dealerDeck.clear();
}
int Blackjack::checkNaturalBlackjack(int choice)
{
vector<Card> deck;
if (choice == 0) { deck = userHand; }
else if (choice == 1) { deck = dealerDeck; }
int ace;
int acepath;
int bigAce = 0;
int smallAce = 0;
int handValue = 0;
int naturalBlackjack;
for (int i = 0; i < deck.size(); i++)
{
Card current = deck.at(i);
if (current.getName() == "Ace") {
acepath = 0;
ace = 1;
}
int hypo = handValue + 11;
if (handValue <= 21 && hypo <= 21 && ace == 1 && acepath == 0) {
handValue += 11;
acepath = 1;
bigAce += 1;
}
else if (handValue <= 21 && hypo >= 21 && ace == 1 && acepath == 0) {
handValue += 1;
smallAce += 1;
acepath = 1;
}
else {
handValue += current.getValue();
}
if (handValue == 21 && bigAce == 1) {
naturalBlackjack = 1;
}
else { naturalBlackjack = 0; }
}
return naturalBlackjack;
}
|
5ab7f5eca27117d40a98b33b0098bdbe70df2ed2 | 0251f2c2d4a144d0b746b57724c092a317676b88 | /3CoeurSystemOld/src/Common/Common/DialogueLoop/UseEvent.cpp | c880475d89e4867bce324aa9b86f102448811e3a | [] | no_license | Careeza/3CoeurSystem | 28fdeed4202601b10d14d74f48d6fa6c469d3c3b | dbef22b90b7e476c94495cee6442d084dcff617a | refs/heads/master | 2020-07-20T12:33:07.004980 | 2020-04-04T18:08:02 | 2020-04-04T18:08:02 | 206,639,977 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 538 | cpp | UseEvent.cpp | #include "common.h"
int dialogueUseButton(t_keyManagement mouse, std::shared_ptr<CS_Element> button)
{
t_buttonValue buttonValue;
buttonValue = CS_KeyControl::useButton(mouse, button);
if (buttonValue == trueButton)
return (0);
else if (buttonValue == falseButton)
return (1);
else
return (-1);
}
int dialogueUseEvent(t_action action, std::shared_ptr<CS_Element> button)
{
if (action.escape == KeyPress)
return (1);
return (dialogueUseButton(action.att, button));
}
|
dd1e285988a040e20a61adff199fa1d523bc762f | 4fcc010579218a20d2ff59bcb9f2c688a354c05b | /MeKaSlug/Weapon_Bomb.h | 2218cc848aa6c4075027a17088cb629b54079bb0 | [] | no_license | hki2345/MetalSlug | ef6bdc646800d2f14e242cd7370e44cb6d18145c | ecf3c220e78452288abab5e5b4eee86d93b27343 | refs/heads/master | 2020-03-30T03:30:22.479081 | 2019-04-01T10:40:11 | 2019-04-01T10:40:11 | 150,691,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 595 | h | Weapon_Bomb.h | #pragma once
#include "One_Weapon.h"
class Animator;
class Weapon_Bomb : public One_Weapon
{
private:
Animator* p_Render;
Dirf m_Power_pos_Dir;
Dirf m_Rending_Dir;
int m_i_JumpCount;
float m_v_EriPower;
public:
void Init() override {};
void Init(Positionf _Pos, Dirf _Pos_Dir, Dirf _Power_Pos_Dir);
void Activate();
void DebugUpdate() override;
void Update() override ;
private:
void Init_Render() override;
void Init_Collision() override;
void Update_Fire() override ;
void Update_Render();
void Update_BottomLine() override;
public:
Weapon_Bomb();
~Weapon_Bomb();
};
|
46746c0892ccbedb009187b992690c2f5965b9e9 | d269d416e1be1b0c0dcb3e61f6a0a8d25a5a3394 | /ExtractSurface.cpp | 22f6c8b68dc8f0892c3a130255f5fc31e09ceb5f | [
"MIT"
] | permissive | lineCode/gui-3 | 18d092f6fe4a16db0bb434af1edd54572eea6101 | f81c00e995396d5682e0cdecf6cd71d59c3c0773 | refs/heads/master | 2021-05-30T07:38:07.378763 | 2015-06-25T20:17:07 | 2015-06-25T20:17:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | cpp | ExtractSurface.cpp | #include <imageprocessing/ImageStackVolumeAdaptor.h>
#include "MarchingCubes.h"
#include "ExtractSurface.h"
ExtractSurface::ExtractSurface() {
registerInput(_stack, "stack");
registerOutput(_surface, "surface");
}
void
ExtractSurface::updateOutputs() {
// wrap the input stack into a volume adaptor
ImageStackVolumeAdaptor volume(*_stack);
// create a marching cubes instance
MarchingCubes<ImageStackVolumeAdaptor> marchingCubes;
_surface = marchingCubes.generateSurface(
volume,
MarchingCubes<ImageStackVolumeAdaptor>::AcceptAbove(0.5),
10.0,
10.0,
10.0);
}
|
fc56307bec8c297a4d205df9302928d3da56f883 | d7b7d1afd941e3eaa86c2fd9de85a86c50e182d3 | /include/Axigluon.hh | 00f2e8ea12bf3b7e3079537dd3797d208af723a0 | [] | no_license | crovelli/AxigluonAnalysisTools | f5755d474ea92b581359bf40c216a9541c343a1d | e5ca3bd66e6f76fa189ac780e5b5da932611d972 | refs/heads/master | 2020-05-30T04:29:39.805342 | 2013-06-30T14:48:35 | 2013-06-30T14:48:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,222 | hh | Axigluon.hh | /// The Higgs class is an auxiliary class which contains basic
/// functionality useful for any analysis of Vecbos+jets events.
/// It derives from AxigluonBase.
#ifndef Axigluon_h
#define Axigluon_h
#include "AxigluonAnalysisTools/include/AxigluonBase.h"
#include "HiggsAnalysisTools/include/JetCorrectionUncertainty.h"
#include "EgammaAnalysisTools/include/CutBasedEleIDSelector.hh"
// ROOT includes
#include <TLorentzVector.h>
#include <TVector3.h>
// std includes
#include <string>
#include <vector>
#include <map>
class Axigluon : public AxigluonBase{
public:
typedef std::pair<unsigned int,unsigned int> aLSSegment;
typedef std::vector< std::pair<unsigned int,unsigned int> > LSSegments;
typedef unsigned int aRun;
typedef std::map< aRun, LSSegments > runsLSSegmentsMap;
typedef std::pair < aRun, LSSegments > aRunsLSSegmentsMapElement;
/// Class Constructor
Axigluon(TTree *tree=0);
/// Class Destructor
virtual ~Axigluon();
/// Fill RunLSMap according to json file
void fillRunLSMap();
/// Set Good Run LS
void setJsonGoodRunList(const std::string& jsonFilePath);
/// check if Run/LS is a good one
bool isGoodRunLS();
/// reload TriggerMask if necessary (data file is changed). Should be called for each event inside the event loop
bool reloadTriggerMask(bool newVersion=false);
/// set the list of required trigger to produce the bitmask
void setRequiredTriggers(const std::vector<std::string>& reqTriggers);
/// check if the event passed HLT. To be called per event
bool hasPassedHLT();
/// get the required HLT path given the current run
std::string getHLTPathForRun(int runN, std::string fullname);
//get the value of the requested bits
std::vector<int> getHLTOutput();
/// Get pt given x/y coordinates
float GetPt(float px, float py) { return TMath::Sqrt(px*px + py*py); }
// useful electron functions
/// sigma ieta ieta of the seed cluster (ecal-driven/tracker-driven)
float SigmaiEiE(int electron);
/// sigma iphi iphi of the seed cluster (ecal-driven/tracker-driven)
float SigmaiPiP(int electron);
// get the PFjet ID
bool isPFJetID(float eta, float nHFrac, float nEmFrac, int nConst, float chHFrac, float chMult, float chEmFrac, int WP);
//! Chris kinematic variables
double CalcMTR(TLorentzVector ja, TLorentzVector jb, TVector3 met);
double CalcMRstar(TLorentzVector ja, TLorentzVector jb);
double CalcGammaMRstar(TLorentzVector ja, TLorentzVector jb);
std::vector<int> sortElectronsByPt(std::vector<int> electrnons);
std::vector<int> sortMuonsByPt(std::vector<int> muons);
TLorentzVector GetJESCorrected(TLorentzVector p4jet, const char *ScaleDirection);
//! comput the PF MET with charged PFcandidates = -ptL1 -ptL2 - sum_i(ptChPFcand_i)
TVector3 pfChargedMet(TVector3 lep1, TVector3 lep2);
TVector3 corrSaclayMet(TVector3 lep1, TVector3 lep2);
// the lepton fakeable object definition
bool isEleDenomFake(int theEle, bool *isDenomEleID, bool *isDenomEleIso, CutBasedEleIDSelector *thisCutBasedID);
bool isMuonDenomFake(int theMuon, bool *isDenomMuonID, bool *isDenomMuonIso);
//! returns the output of the custom muon ID
void isMuonID(int muonIndex, bool *muonIdOutput);
//! returns the output of the custom cut electron ID with WPXX
void isEleID(int eleIndex, bool *eleIdOutput, bool *isolOutput, bool *convRejOutput, CutBasedEleIDSelector *thisCutBasedID);
//! returns the output of the custom cut electron ID with WPXX && deominator selection
void isEleIDAndDenom(int eleIndex, bool *eleIdOutput, bool *isolOutput, bool *convRejOutput, CutBasedEleIDSelector *thisCutBasedID);
enum jetIdWP { none=0, loose=1, medium=2, tight=3 };
private:
///goodRUN/LS list
runsLSSegmentsMap goodRunLS;
std::string jsonFile;
std::string lastFile;
std::vector<std::string> requiredTriggers;
JetCorrectionUncertainty *jecUnc_calo;
JetCorrectionUncertainty *jecUnc_PF;
protected:
//! the list of required triggers
std::vector<int> m_requiredTriggers;
/// calculate transverse mass
/// definitions in http://indico.cern.ch/getFile.py/access?contribId=4&resId=0&materialId=slides&confId=104213
float mT3(TLorentzVector pl1, TLorentzVector pl2, TVector3 met);
};
#endif
|
b0b0968d5ea23cd7ad50bbac605ce17fd5aa6de1 | 97899b7708901605f214ba80147bbe2629ec7ffa | /蓝桥-七届-省赛-四平方和.cpp | 2737bd810ef8b5cb3986d201fb5a62cddc8d9fb9 | [] | no_license | srcrs/code | dcfe5f852b6696ca994d3e8bcfdc637fb3ca2a10 | 3c3aa4cfcaa1234dd3ad89e4f294b5d409c5ceb7 | refs/heads/master | 2021-07-14T08:22:17.828622 | 2020-10-16T14:37:35 | 2020-10-16T14:37:35 | 215,021,759 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 650 | cpp | 蓝桥-七届-省赛-四平方和.cpp | #include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
int dir[5000005]={0};
int n;
void init(){
fill(dir,dir+n,0);
for(int i=0;i*i<=n;i++){
for(int j=0;j*j<=n;j++){
if(i*i+j*j<=n){
dir[i*i+j*j]=1;
}
}
}
}
int main()
{
cin >> n;
init();
bool flag=false;
for(int i=0;i*i<=n;i++){
for(int j=0;j*j<=n;j++){
if(dir[n-i*i-j*j]){
for(int k=0;k*k<=n;k++){
int d = (int)sqrt(n-(i*i+j*j+k*k));
if(d*d==(n-(i*i+j*j+k*k))){
cout << i << " " << j << " " << k << " " << d;
flag=true;
break;
}
}
}
if(flag){
break;
}
}
if(flag){
break;
}
}
return 0;
}
|
556d8da70e7e2141c360d09118b4252bd1495bfa | 2b1b30f417721bd5f38f014113e736ff3793a5d5 | /firmware/lib/Controller/src/Fin.cpp | 9fe42f0a5b4917cf540d34a1fe1322b105214831 | [
"BSD-2-Clause"
] | permissive | Briancbn/trashy-splashy | 5788bee9f8a056bdea10b258db8f34c3b5a0d68a | 55993902aecd4412747506f3c81203a4af17abf2 | refs/heads/master | 2021-04-09T16:13:20.483172 | 2018-05-07T08:12:21 | 2018-05-07T08:12:21 | 125,756,853 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,428 | cpp | Fin.cpp | /*
* Fin.cpp
*
* Created on: 20 Mar 2018
* Author: Chen Bainian
*/
#include "Fin.h"
Fin::Fin(int8_t _num_fin_servos)
: num_fin_servos(_num_fin_servos), cpg(_num_fin_servos, DEFAULT_FREQUENCY, ALPHA, BETA, MU, UPDATE_INTERVAL)
{
}
void Fin::init(PWMServo* _servos, int* _offset_angle_deg){
servos = _servos;
offset_angle_deg = _offset_angle_deg;
write_angle_deg(0);
}
void Fin::write(int linear_speed, int angular_speed, int incline)
{
std::vector<int> input_amplitude_deg, input_neutral_position_deg, input_phase_shift_deg;
int propel_L = linear_speed - angular_speed / 2 / ROBOT_RADIUS;
int propel_R = linear_speed + angular_speed / 2 / ROBOT_RADIUS;
int amplitude_deg_L, amplitude_deg_R;
if(propel_L == 0){
amplitude_deg_L = 0;
}
else{
if(propel_L > AMPLITUDE_RESOLUTION){
propel_L = AMPLITUDE_RESOLUTION;
}
else if(propel_L < -AMPLITUDE_RESOLUTION){
propel_L = -AMPLITUDE_RESOLUTION;
}
amplitude_deg_L = MIN_AMPLITUDE + (MAX_AMPLITUDE - MIN_AMPLITUDE) * abs(propel_L) / AMPLITUDE_RESOLUTION;
}
if(propel_R == 0){
amplitude_deg_R = 0;
}
else{
if(propel_R > AMPLITUDE_RESOLUTION){
propel_R = AMPLITUDE_RESOLUTION;
}
else if(propel_R < -AMPLITUDE_RESOLUTION){
propel_R = -AMPLITUDE_RESOLUTION;
}
amplitude_deg_R = MIN_AMPLITUDE + (MAX_AMPLITUDE - MIN_AMPLITUDE) * abs(propel_R) / AMPLITUDE_RESOLUTION;
}
for(int i = 0; i < num_fin_servos / 2; i++){
input_amplitude_deg.push_back(amplitude_deg_L);
if(incline > 0){
input_neutral_position_deg.push_back(incline * (i - (int)(num_fin_servos / 4)) / (num_fin_servos / 2 - 1) );
}
else{
input_neutral_position_deg.push_back(incline * ((int)(num_fin_servos / 4) - i) / (num_fin_servos / 2 - 1) );
}
if(propel_L > 0){
input_phase_shift_deg.push_back(PHASE_SHIFT * (i - (int)(num_fin_servos / 4)));
}
else{
input_phase_shift_deg.push_back(PHASE_SHIFT * ((int)(num_fin_servos / 4) - i));
}
}
for(int i = 0; i < num_fin_servos / 2; i++){
input_amplitude_deg.push_back(amplitude_deg_R);
if(incline > 0){
input_neutral_position_deg.push_back(incline * (i - (int)(num_fin_servos / 4)) / (num_fin_servos / 2 - 1) );
}
else{
input_neutral_position_deg.push_back(incline * ((int)(num_fin_servos / 4) - i) / (num_fin_servos / 2 - 1) );
}
if(propel_R > 0){
input_phase_shift_deg.push_back(PHASE_SHIFT * (i - (int)(num_fin_servos / 4)));
}
else{
input_phase_shift_deg.push_back(PHASE_SHIFT * ((int)(num_fin_servos / 4) - i));
}
}
std::vector<float> output_rad = cpg.generate_new_pose(DEFAULT_FREQUENCY, deg_to_rad(input_amplitude_deg), deg_to_rad(input_neutral_position_deg), deg_to_rad(input_phase_shift_deg));
write_angle_rad(output_rad);
}
void Fin::write_L(uint16_t propel, bool propel_direction, uint16_t incline, bool incline_direction)
{
int num_fin = num_fin_servos / 2;
std::vector<int> input_amplitude_deg, input_neutral_position_deg, input_phase_shift_deg;
int amplitude_deg;
if(propel == 0){
amplitude_deg = 0;
}
else{
if(propel > AMPLITUDE_RESOLUTION){
propel = AMPLITUDE_RESOLUTION;
}
amplitude_deg = MIN_AMPLITUDE + (MAX_AMPLITUDE - MIN_AMPLITUDE) * propel / AMPLITUDE_RESOLUTION;
}
for(int i = 0; i < num_fin; i++){
input_amplitude_deg.push_back(amplitude_deg);
if(incline_direction){
input_neutral_position_deg.push_back(incline * (i - (int)(num_fin / 2)) / (num_fin - 1) );
}
else{
input_neutral_position_deg.push_back(incline * ((int)(num_fin / 2) - i) / (num_fin - 1) );
}
if(propel_direction){
input_phase_shift_deg.push_back(PHASE_SHIFT * (i - (int)(num_fin / 2)));
}
else{
input_phase_shift_deg.push_back(PHASE_SHIFT * ((int)(num_fin / 2) - i));
}
}
std::vector<float> output_rad = cpg.generate_new_pose(DEFAULT_FREQUENCY, deg_to_rad(input_amplitude_deg), deg_to_rad(input_neutral_position_deg), deg_to_rad(input_phase_shift_deg));
write_L_angle_rad(output_rad);
}
void Fin::write_R(uint16_t propel, bool propel_direction, uint16_t incline, bool incline_direction)
{
int num_fin = num_fin_servos / 2;
std::vector<int> input_amplitude_deg, input_neutral_position_deg, input_phase_shift_deg;
int amplitude_deg;
if(propel == 0){
amplitude_deg = 0;
}
else{
if(propel > AMPLITUDE_RESOLUTION){
propel = AMPLITUDE_RESOLUTION;
}
amplitude_deg = MIN_AMPLITUDE + (MAX_AMPLITUDE - MIN_AMPLITUDE) * propel / AMPLITUDE_RESOLUTION;
}
for(int i = 0; i < num_fin; i++){
input_amplitude_deg.push_back(amplitude_deg);
if(incline_direction){
input_neutral_position_deg.push_back(incline * (i - (int)(num_fin / 2)) / (num_fin - 1) );
}
else{
input_neutral_position_deg.push_back(incline * ((int)(num_fin / 2) - i) / (num_fin - 1) );
}
if(propel_direction){
input_phase_shift_deg.push_back(PHASE_SHIFT * (i - (int)(num_fin / 2)));
}
else{
input_phase_shift_deg.push_back(PHASE_SHIFT * ((int)(num_fin / 2) - i));
}
}
std::vector<float> output_rad = cpg.generate_new_pose(DEFAULT_FREQUENCY, deg_to_rad(input_amplitude_deg), deg_to_rad(input_neutral_position_deg), deg_to_rad(input_phase_shift_deg));
write_R_angle_rad(output_rad);
}
void Fin::write_angle_rad(const std::vector<float>& angle_rad){
write_angle_deg(rad_to_deg(angle_rad));
}
void Fin::write_angle_deg(const std::vector<int>& angle_deg){
for(int i = 0; i < num_fin_servos / 2; i++){
servos[i].write(90 + (offset_angle_deg[i] + angle_deg[i]) * 180 / SERVO_ANGLE_RANGE);
}
for(int i = 0; i < num_fin_servos / 2; i++){
servos[i + num_fin_servos / 2].write(90 + (offset_angle_deg[i + num_fin_servos / 2] - angle_deg[i + num_fin_servos / 2]) * 180 / SERVO_ANGLE_RANGE);
}
}
void Fin::write_angle_rad(float angle_rad){
write_L_angle_rad(angle_rad);
write_R_angle_rad(angle_rad);
}
void Fin::write_angle_deg(int angle_deg){
write_L_angle_deg(angle_deg);
write_R_angle_deg(angle_deg);
}
void Fin::write_L_angle_rad(const std::vector<float>& angle_rad){
write_L_angle_deg(rad_to_deg(angle_rad));
}
void Fin::write_L_angle_deg(const std::vector<int>& angle_deg){
for(int i = 0; i < num_fin_servos / 2; i++){
servos[i].write(90 + (offset_angle_deg[i] + angle_deg[i]) * 180 / SERVO_ANGLE_RANGE);
}
}
void Fin::write_L_angle_rad(float angle_rad){
write_L_angle_deg(rad_to_deg(angle_rad));
}
void Fin::write_L_angle_deg(int angle_deg){
for(int i = 0; i < num_fin_servos / 2; i++){
servos[i].write(90 + (offset_angle_deg[i] + angle_deg) * 180 / SERVO_ANGLE_RANGE);
}
}
void Fin::write_R_angle_rad(const std::vector<float>& angle_rad){
write_L_angle_deg(rad_to_deg(angle_rad));
}
void Fin::write_R_angle_deg(const std::vector<int>& angle_deg){
for(int i = 0; i < num_fin_servos / 2; i++){
servos[i + num_fin_servos / 2].write(90 + (offset_angle_deg[i + num_fin_servos / 2] - angle_deg[i]) * 180 / SERVO_ANGLE_RANGE);
}
}
void Fin::write_R_angle_rad(float angle_rad){
write_L_angle_deg(rad_to_deg(angle_rad));
}
void Fin::write_R_angle_deg(int angle_deg){
for(int i = 0; i < num_fin_servos / 2; i++){
servos[i + num_fin_servos / 2].write(90 + (offset_angle_deg[i + num_fin_servos / 2] - angle_deg) * 180 / SERVO_ANGLE_RANGE);
}
}
Fin::~Fin() {
// TODO Auto-generated destructor stub
}
|
b40bd2a95e1ac97d95964ce000448e1f1ee20e7c | 6b66f3e22dec75fc7bd657a0c5fdbbb18e294b96 | /Engine/Utility/Structures/JSON.h | 25648757954fd0901ae257d1dfaee44afe0af063 | [] | no_license | AniCator/shatter-engine | cff01c191b0af3ca21b769842285c26556e2b5a9 | 9a8f715ab463418398146550af45a35626f13d3e | refs/heads/master | 2023-05-10T04:11:53.656999 | 2023-05-08T17:46:55 | 2023-05-08T17:46:55 | 119,185,578 | 41 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 6,238 | h | JSON.h | // Copyright © 2017, Christiaan Bakker, All rights reserved.
#pragma once
#include <unordered_map>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <Engine/Utility/File.h>
#include <Engine/Utility/String.h>
namespace JSON
{
struct Container;
Container Tree( const CFile& File );
Container Tree( const std::string& Data );
void PrintTree( const Container& Tree );
struct Object;
typedef std::list<Object*> Vector;
struct Object
{
bool IsObject = false;
bool IsArray = false;
bool IsField = false;
std::string Key;
std::string Value;
Object* Parent = nullptr;
Container* Owner = nullptr; // Pointer to the owning container.
Vector Objects;
void SetValue( const std::string& Key, const std::string& NewValue );
const std::string& GetValue( const std::string& Key ) const;
// Adds an object.
Object& Add();
Object* operator[]( const std::string& Key ) const;
Object& operator[]( const std::string& Key );
Object& operator[]( const Object& Object );
Object& operator=( const char* Value );
Object& operator=( const std::string& Value );
Object& operator=( const JSON::Container& Container );
Object* Find( const std::string& Key ) const;
};
inline Object* Find( const Vector& Objects, const std::string& Key )
{
if( !Objects.empty() )
{
const auto Result = std::find_if( Objects.begin(), Objects.end(), [&Key] ( Object* Item ) -> bool
{
return Item->Key == Key;
}
);
if( Result == Objects.end() )
{
return nullptr;
}
return *Result;
}
return nullptr;
}
// Casts and assigns an object value if it exists.
inline void Assign( const Vector& Objects, const std::string& Search, std::string& Target )
{
const auto* Object = JSON::Find( Objects, Search );
if( Object )
{
Target = Object->Value;
Target = String::Replace( Target, "\\\\n", "\n" );
}
}
inline void Assign( const Vector& Objects, const std::string& Search, bool& Target )
{
const auto* Object = JSON::Find( Objects, Search );
if( Object )
{
Target = Object->Value != "0";
}
}
inline void Assign( const Vector& Objects, const std::string& Search, int& Target )
{
const auto* Object = JSON::Find( Objects, Search );
if( Object )
{
Target = std::stoi( Object->Value );
}
}
inline void Assign( const Vector& Objects, const std::string& Search, unsigned int& Target )
{
const auto* Object = JSON::Find( Objects, Search );
if( Object )
{
Target = std::stoul( Object->Value );
}
}
inline void Assign( const Vector& Objects, const std::string& Search, float& Target )
{
const auto* Object = JSON::Find( Objects, Search );
if( Object )
{
Target = std::stof( Object->Value );
}
}
inline void Assign( const Vector& Objects, const std::string& Search, Vector3D& Target )
{
const auto* Object = JSON::Find( Objects, Search );
if( Object )
{
Extract( Object->Value, Target );
}
}
struct SearchEntry
{
SearchEntry() = delete;
SearchEntry( const std::string& Entry, std::string& Data )
{
Search = Entry;
Target = &Data;
Type = String;
}
SearchEntry( const std::string& Entry, bool& Data )
{
Search = Entry;
Target = &Data;
Type = Boolean;
}
SearchEntry( const std::string& Entry, int& Data )
{
Search = Entry;
Target = &Data;
Type = Integer;
}
SearchEntry( const std::string& Entry, unsigned int& Data )
{
Search = Entry;
Target = &Data;
Type = Unsigned;
}
SearchEntry( const std::string& Entry, float& Data )
{
Search = Entry;
Target = &Data;
Type = Float;
}
SearchEntry( const std::string& Entry, Vector3D& Data )
{
Search = Entry;
Target = &Data;
Type = Vector3D;
}
std::string Search;
void* Target = nullptr;
enum
{
String,
Boolean,
Integer,
Unsigned,
Float,
Vector3D
} Type;
};
// Assign function that can extract most types sequentially.
// You can use an initializer list to configure the vector array.
// JSON::Assign(
// Objects,
// {
// { "item1", Item1 },
// { "item2", Item2 },
// { "item3", Item3 },
// { "item4", Item4 },
// { "item5", Item5 }
// } );
inline void Assign( const Vector& Objects, const std::vector<SearchEntry>& Entries )
{
for( auto& Entry : Entries )
{
const auto* Object = JSON::Find( Objects, Entry.Search );
if( Object && Entry.Target )
{
if( Entry.Type == SearchEntry::String )
{
const auto Target = static_cast<std::string*>( Entry.Target );
*Target = Object->Value;
*Target = String::Replace( *Target, "\\\\n", "\n" );
}
else if( Entry.Type == SearchEntry::Boolean )
{
const auto Target = static_cast<bool*>( Entry.Target );
Extract( Object->Value, *Target );
}
else if( Entry.Type == SearchEntry::Integer )
{
const auto Target = static_cast<int*>( Entry.Target );
Extract( Object->Value, *Target );
}
else if( Entry.Type == SearchEntry::Unsigned )
{
const auto Target = static_cast<unsigned int*>( Entry.Target );
Extract( Object->Value, *Target );
}
else if( Entry.Type == SearchEntry::Float )
{
const auto Target = static_cast<float*>( Entry.Target );
Extract( Object->Value, *Target );
}
else if( Entry.Type == SearchEntry::Vector3D )
{
const auto Target = static_cast<Vector3D*>( Entry.Target );
Extract( Object->Value, *Target );
}
}
}
}
std::string Stringify( const JSON::Object* Object );
struct Container
{
std::list<Object> Objects;
Vector Tree;
Container() = default;
// Searches for an existing entry, creates a new one if it doesn't exist.
Object& operator[]( const std::string& Key );
// Appends together two containers.
Container& operator+=( const Container& Container );
Object* Allocate();
void Add( Object* Parent, Object* Child );
Object* Add( Object* Parent, const std::string& Key );
void Regenerate();
std::string Export();
// Returns true if the object is a part of this container.
bool Valid( Object* Object ) const;
// Copy constructor.
Container( Container const& Source );
// Copy operator.
Container& operator=( Container const& Source );
};
}
|
d42d8a301bb1ae0c44b965109d8de6066b45ca46 | d32031c4a838de6e5ffa1beb2dd2a714bcffa0a8 | /Hanafuda/YakuList.h | da04066eaa7c4f3093318cb64cfbd26fd990f817 | [] | no_license | nosnah3791/Hanafuda | d0bde816aafd1c6697ce2f650c29bd9173cd4394 | 60efcf96bd573d80a77b5aa7767156e3e61284bc | refs/heads/master | 2021-05-01T08:22:10.769229 | 2017-01-22T09:51:23 | 2017-01-22T09:51:23 | 79,709,081 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 668 | h | YakuList.h | #pragma once
#include "character.h"
class YakuList :
public Character
{
public:
YakuList(void);
~YakuList(void);
private:
UINT m_uiReachBit;//リーチビット
UINT m_uiAchieveBit;//達成ビット
//定数
enum{
YL_WIDTH = 75,//幅
YL_HEIGHT = 20//高さ
};
public:
// 描画
void Paint(Graphics* g);
//リセット
void Reset(void);
//指定位置のリーチビットを変更
void SetReachBit(UINT no,BOOL flg);
//指定位置のリーチビットを取得
BOOL GetReachBit(UINT no);
//指定位置の到達ビットを変更
void SetAchieveBit(UINT no,BOOL flg);
//指定位置の到達ビットを取得
BOOL GetAchieveBit(UINT no);
};
|
86550431acc02a8048f763f1cf46a16d1eee9c0a | f8b838e3805a4dde783da142e6c46062be4ff606 | /chrome/browser/ui/views/payments/payment_request_item_list.h | 71f4c04812d6eb0903b96538f6c6f5dab4fb23ab | [
"BSD-3-Clause"
] | permissive | trusslab/sugar_chromium | 1cc0eec4dd52d8b2b7bc2d871090a518495539f8 | 5f1dd3da9f21c65c4f1388f22e10585941f0cbc9 | refs/heads/master | 2022-11-08T17:36:48.367045 | 2018-02-17T07:00:15 | 2018-02-17T07:00:15 | 121,314,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,941 | h | payment_request_item_list.h | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_VIEWS_PAYMENTS_PAYMENT_REQUEST_ITEM_LIST_H_
#define CHROME_BROWSER_UI_VIEWS_PAYMENTS_PAYMENT_REQUEST_ITEM_LIST_H_
#include <memory>
#include <vector>
#include "base/macros.h"
namespace views {
class View;
}
namespace payments {
// A control representing a list of selectable items in the PaymentRequest
// dialog. These lists enforce that only one of their elements be selectable at
// a time and that "incomplete" items (for example, a credit card with no known
// expriration date) behave differently when selected. Most of the time, this
// behavior is to show an editor screen.
class PaymentRequestItemList {
public:
// Represents an item in the item list.
class Item {
public:
Item();
virtual ~Item();
// Gets the view associated with this item. It's owned by this object so
// that it can listen to any changes to the underlying model and update the
// view.
views::View* GetItemView();
protected:
// Creates and returns the view associated with this list item.
virtual std::unique_ptr<views::View> CreateItemView() = 0;
private:
std::unique_ptr<views::View> item_view_;
DISALLOW_COPY_AND_ASSIGN(Item);
};
PaymentRequestItemList();
~PaymentRequestItemList();
// Adds an item to this list.
void AddItem(std::unique_ptr<Item> item);
// Creates and returns the UI representation of this list. It iterates over
// the items it contains, creates their associated views, and adds them to the
// hierarchy.
std::unique_ptr<views::View> CreateListView();
private:
std::vector<std::unique_ptr<Item>> items_;
DISALLOW_COPY_AND_ASSIGN(PaymentRequestItemList);
};
} // namespace payments
#endif // CHROME_BROWSER_UI_VIEWS_PAYMENTS_PAYMENT_REQUEST_ITEM_LIST_H_
|
a02ac15f6b1cdf7e83e3cd0976500ace8c501859 | 09ddd2df75bce4df9e413d3c8fdfddb7c69032b4 | /include/Networking/.svn/text-base/http.h.svn-base | 9f1e40294ce6a42c02ccd186c937437ab3863d50 | [] | no_license | sigurdle/FirstProject2 | be22e4824da8cd2cb5047762478050a04a4ac63b | dee78c62a1b95e55fcdf3bf2a9bc79c69705bf94 | refs/heads/master | 2021-01-16T18:45:41.042140 | 2020-08-18T16:57:13 | 2020-08-18T16:57:13 | 3,554,336 | 6 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,732 | http.h.svn-base | #ifndef __HTTP_H
#define __HTTP_H
#include "Socket.h"
#include "HttpHeaders.h"
namespace System
{
namespace Net
{
class HttpRequest;
interface IDownloadCallback
{
virtual int OnProgress(HttpRequest* request) = 0;
virtual int OnDataAvailable(ULONG cbSize, IO::Stream* stream) = 0;
virtual int OnDone() = 0;
};
class HttpConnection;
class HttpRequest;
class NETEXT HttpContentStream : public IO::Stream
{
public:
CTOR HttpContentStream(HttpRequest* pRequest);
~HttpContentStream();
virtual size_t Read(void* pv, size_t cb) override;
virtual uint64 Seek(int64 offset, IO::SeekOrigin origin) override;
virtual uint64 GetSize() override;
// virtual LONGLONG GetSize() const;
// virtual IO::ISequentialByteStream* Clone() const;
virtual size_t Write(const void* pv, size_t cb) override;
virtual uint64 GetPosition() override
{
return m_pos;
}
uint64 m_contentLength;
String m_transferEncoding;
protected:
friend class HttpRequest;
HttpRequest* m_pRequest;
uint64 m_pos;
uint64 m_chunkBytesLeft;
};
class NETEXT HttpRequest : public Object
{
public:
CTOR HttpRequest(HttpConnection* connection, StringIn verb, StringIn objectName);
void AddHeader(StringIn field, StringIn value);
void AddHeaders(StringIn str);
void Send();
HttpContentStream* GetContentStream();
void ReadResponse();
Event1<int> m_stateChanged;
public:
// String m_additionalHeaders;
String m_verb;
String m_objectName;
String m_status;
HttpHeaders m_requestHeaders;
HttpHeaders m_responseHeaders;
IDownloadCallback* m_downloadCallback;
HttpContentStream* m_pContentStream;
protected:
friend class HttpContentStream;
HttpConnection* m_connection;
};
class NETEXT HttpConnection : public Object
{
public:
CTOR HttpConnection(StringIn server, int port = 80);
~HttpConnection();
/*
enum
{
HTTP_VERB_POST = 0 ,
HTTP_VERB_GET = 1 ,
HTTP_VERB_HEAD = 2 ,
HTTP_VERB_PUT = 3 ,
HTTP_VERB_LINK = 4 ,
HTTP_VERB_DELETE = 5 ,
HTTP_VERB_UNLINK = 6,
};
*/
HttpRequest* m_pRequest;
HttpRequest* OpenRequest(StringIn verb, StringIn objectName);
protected:
friend class HttpRequest;
friend class HttpContentStream;
class HttpSocket : public AsyncSocket
{
public:
CTOR HttpSocket(HttpConnection* connection);
virtual void OnConnect(int nErrorCode);
virtual void OnClose(int nErrorCode);
virtual void OnReceive(int nErrorCode);
virtual void OnSend(int nErrorCode);
IO::TextWriter& ReadLine(IO::TextWriter& stream);
String ReadLine();
HttpConnection* m_pConnection;
//HANDLE m_hEvent;
int64 m_sofar;
int m_state;
bool m_bDone;
};
HttpSocket* m_pSocket;
String m_server;
int m_port;
};
NETEXT String DownloadFile(String url);
} // Net
} // System
#endif // __HTTP_H
| |
9cac69203493ffa292047f3c3564c2b94b7979b4 | bcd32907dc7b292350371ac5cc9b67bd3b7a99c2 | /development/C++/src/client/Ae/ClientAeSubscription.h | eac86762abe087652ba2de3275827130a0a3f76d | [
"MIT"
] | permissive | SoftingIndustrial/OPC-Classic-SDK | c6d3777e2121d6ca34da571930a424717740171e | 08f4b3e968acfce4b775299741cef1819e24fda1 | refs/heads/main | 2022-07-28T14:53:00.481800 | 2022-01-17T13:58:46 | 2022-01-17T13:58:46 | 335,269,862 | 41 | 16 | MIT | 2022-01-17T15:11:39 | 2021-02-02T11:43:04 | C++ | UTF-8 | C++ | false | false | 3,768 | h | ClientAeSubscription.h | #ifndef _CLIENTAESUBSCRIPTION_H_
#define _CLIENTAESUBSCRIPTION_H_
#include "../ClientEnums.h"
#include "../ClientObjectSpaceElement.h"
#include "../../Trace.h"
#include "../../Enums.h"
#include "Mutex.h"
#ifdef WIN64
#pragma pack(push,8)
#else
#pragma pack(push,4)
#endif
namespace SoftingOPCToolboxClient
{
class AeSession;
class AeReturnedAttributes;
class AeCondition;
class AeEvent;
class TBC_EXPORT AeSubscription : public ObjectSpaceElement
{
//friend class Application;
friend class OTCGlobals;
friend class AeCondition;
private:
void onAeEventsReceived(
BOOL isRefresh,
BOOL lastRefresh,
const std::vector<AeEvent*>& events);
void onAeConditionsChanged(const std::vector<AeCondition*>& someAeConditions);
void onRefreshAeConditions(
unsigned long executionContext,
long result);
void onCancelRefreshAeConditions(
unsigned long executionContext,
long result);
protected:
AeSession* m_session;
std::vector<AeCondition*> m_conditionList;
Mutex m_conditionListJanitor;
void setAeConditionList(std::vector<AeCondition*> someAeConditions);
public:
AeSubscription(AeSession* parentSession);
virtual ~AeSubscription();
AeSession* getAeSession();
void setAeSession(AeSession* aSession);
unsigned long getRequestedBufferTime();
void setRequestedBufferTime(unsigned long requestedBufferTime);
unsigned long getRevisedBufferTime();
unsigned long getRequestedMaxSize();
void setRequestedMaxSize(unsigned long maxSize);
unsigned long getRevisedMaxSize();
unsigned long getFilterSeverityLow();
void setFilterSeverityLow(unsigned long filterSeverityLow);
unsigned long getFilterSeverityHigh();
void setFilterSeverityHigh(unsigned long filterSeverityHigh);
unsigned long getFilterEventTypes();
void setFilterEventTypes(unsigned long filterEventTypes);
std::vector<unsigned long> getFilterCategories();
void setFilterCategories(std::vector<unsigned long> categories);
std::vector<tstring> getFilterAreas();
void setFilterAreas(std::vector<tstring> filterAreas);
std::vector<tstring> getFilterSources();
void setFilterSources(std::vector<tstring> filterSources);
std::vector<AeReturnedAttributes*> getReturnedAttributes();
void setReturnedAttributes(std::vector<AeReturnedAttributes*> someAeReturnedAttributes);
std::vector<AeCondition*>& getAeConditionList();
virtual long refreshAeConditions(ExecutionOptions* someExecutionOptions);
virtual long cancelRefreshAeConditions(ExecutionOptions* someExecutionOptions);
virtual void handleAeEventsReceived(
BOOL isRefresh,
BOOL lastRefresh,
const std::vector<AeEvent*>& events);
virtual void handleAeConditionsChanged(const std::vector<AeCondition*>& someAeConditions);
virtual void handleRefreshAeConditionsCompleted(
unsigned long executionContext,
long result);
virtual void handleCancelRefreshAeConditionsCompleted(
unsigned long executionContext,
long result);
}; // end class AeSubscription
typedef std::pair <unsigned long, AeSubscription*> AeSubscriptionPair;
class TBC_EXPORT AeReturnedAttributes
{
protected:
unsigned long m_categoryId;
std::vector<unsigned long>m_attributesIds;
public:
AeReturnedAttributes()
{
m_categoryId = 0;
m_attributesIds.push_back(0);
} //end constructor
virtual ~AeReturnedAttributes();
unsigned long getCategoryId()
{
return m_categoryId;
} //end getCategoryId
void setCategoryId(unsigned long categoryId)
{
m_categoryId = categoryId;
} //end setCategoryId
const std::vector<unsigned long>& getAttributesIds()
{
return m_attributesIds;
} // end get
void setAttributesIds(std::vector<unsigned long> attributesIds)
{
m_attributesIds = attributesIds;
} //end set
}; //end AeReturnedAttributes
}; //end namespace OPC_Client
#pragma pack(pop)
#endif
|
6ad88540c86b3ed323c3cc4730c20f242c95ff6e | 5509788aa5c5bacc053ea21796d3ef5ba878d744 | /Practice/2018/2018.12.13/UOJ117.cpp | c5e8fb61c90bff08a266467cdcbe6d0a737be213 | [
"MIT"
] | permissive | SYCstudio/OI | 3c5a6a9c5c9cd93ef653ad77477ad1cd849b8930 | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | refs/heads/master | 2021-06-25T22:29:50.276429 | 2020-10-26T11:57:06 | 2020-10-26T11:57:06 | 108,716,217 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,384 | cpp | UOJ117.cpp | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=101000;
const int maxM=202000<<1;
const int inf=2147483647;
int Graph,n,m;
int edgecnt=1,Head[maxN],Next[maxM],V[maxM];
int top,St[maxM];
int D1[maxN],D2[maxN];
bool del[maxM];
void Add_Edge(int u,int v);
void dfs(int u);
int main(){
mem(Head,-1);
scanf("%d%d%d",&Graph,&n,&m);
for (int i=1;i<=m;i++){
int u,v;scanf("%d%d",&u,&v);
Add_Edge(u,v);
}
if (Graph==1) for (int i=1;i<=n;i++) if (D1[i]&1) {printf("NO\n");return 0;}
if (Graph==2) for (int i=1;i<=n;i++) if (D1[i]!=D2[i]) {printf("NO\n");return 0;}
for (int i=1;i<=n;i++)
if (Head[i]!=-1){
dfs(i);break;
}
//cout<<"top:"<<top<<endl;
if (top!=m) printf("NO\n");
else{
printf("YES\n");
for (int i=m;i>=1;i--)
if (Graph==1) printf("%d ",(St[i]>>1)*((St[i]&1)?(-1):(1)));
else printf("%d ",St[i]>>1);
}
return 0;
}
void Add_Edge(int u,int v){
Next[++edgecnt]=Head[u];Head[u]=edgecnt;V[edgecnt]=v;
if (Graph==1){
Next[++edgecnt]=Head[v];Head[v]=edgecnt;V[edgecnt]=u;
D1[u]++;D1[v]++;
}
else D1[u]++,D2[v]++,++edgecnt;
return;
}
void dfs(int u){
for (int &i=Head[u];i!=-1;)
if (del[i>>1]==0){
del[i>>1]=1;int j=i;i=Next[i];
dfs(V[j]);St[++top]=j;
}
else i=Next[i];
return;
}
|
7c435723942f7b48ea5883b2aac9e9cdaf2ff027 | 2b1b459706bbac83dad951426927b5798e1786fc | /src/media/audio/drivers/lib/intel-hda/include/intel-hda/utils/utils.h | 5935b68965617ce25a436ba3091988ee397ce549 | [
"BSD-2-Clause"
] | permissive | gnoliyil/fuchsia | bc205e4b77417acd4513fd35d7f83abd3f43eb8d | bc81409a0527580432923c30fbbb44aba677b57d | refs/heads/main | 2022-12-12T11:53:01.714113 | 2022-01-08T17:01:14 | 2022-12-08T01:29:53 | 445,866,010 | 4 | 3 | BSD-2-Clause | 2022-10-11T05:44:30 | 2022-01-08T16:09:33 | C++ | UTF-8 | C++ | false | false | 3,098 | h | utils.h | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SRC_MEDIA_AUDIO_DRIVERS_LIB_INTEL_HDA_INCLUDE_INTEL_HDA_UTILS_UTILS_H_
#define SRC_MEDIA_AUDIO_DRIVERS_LIB_INTEL_HDA_INCLUDE_INTEL_HDA_UTILS_UTILS_H_
#include <lib/fit/function.h>
#include <lib/zx/bti.h>
#include <lib/zx/channel.h>
#include <lib/zx/handle.h>
#include <lib/zx/vmo.h>
#include <zircon/device/audio.h>
#include <zircon/types.h>
#include <type_traits>
#include <utility>
#include <abs_clock/clock.h>
#include <fbl/ref_counted.h>
#include <fbl/ref_ptr.h>
#include <fbl/vector.h>
#include <intel-hda/utils/codec-caps.h>
#include "src/graphics/display/lib/edid/edid.h"
namespace audio {
namespace intel_hda {
using abs_clock::Clock;
using abs_clock::RealClock;
static constexpr size_t MAX_HANDLER_CAPTURE_SIZE = sizeof(void*) * 2;
using WaitConditionFn = fit::inline_function<bool(), MAX_HANDLER_CAPTURE_SIZE>;
zx_status_t WaitCondition(zx_duration_t timeout, zx_duration_t poll_interval, WaitConditionFn cond,
Clock* clock = RealClock::Get());
template <typename E>
constexpr typename std::underlying_type<E>::type to_underlying(E e) {
return static_cast<typename std::underlying_type<E>::type>(e);
}
zx_obj_type_t GetHandleType(const zx::handle& handle);
// Utility class which manages a Bus Transaction Initiator using RefPtrs
// (allowing the BTI to be shared by multiple objects)
class RefCountedBti : public fbl::RefCounted<RefCountedBti> {
public:
static fbl::RefPtr<RefCountedBti> Create(zx::bti initiator);
const zx::bti& initiator() const { return initiator_; }
private:
explicit RefCountedBti(zx::bti initiator) : initiator_(std::move(initiator)) {}
zx::bti initiator_;
};
template <typename T>
zx_status_t ConvertHandle(zx::handle* abstract_handle, T* concrete_handle) {
static_assert(std::is_base_of<zx::object<T>, T>::value,
"Target of ConvertHandle must be a concrete zx:: handle wrapper type!");
if ((abstract_handle == nullptr) || (concrete_handle == nullptr) || !abstract_handle->is_valid())
return ZX_ERR_INVALID_ARGS;
if (GetHandleType(*abstract_handle) != T::TYPE)
return ZX_ERR_WRONG_TYPE;
concrete_handle->reset(abstract_handle->release());
return ZX_OK;
}
// Generate a vector of audio stream format ranges given the supplied sample
// capabilities and max channels.
zx_status_t MakeFormatRangeList(const SampleCaps& sample_caps, uint32_t max_channels,
fbl::Vector<audio_stream_format_range_t>* ranges);
// Generates new SampleCaps by performing a logical "and" based on an exisiting SampleCaps and
// and ranges.
zx_status_t MakeNewSampleCaps(const SampleCaps& old_sample_caps,
const edid::ShortAudioDescriptor sad_list[], const size_t sad_count,
SampleCaps& new_sample_caps);
} // namespace intel_hda
} // namespace audio
#endif // SRC_MEDIA_AUDIO_DRIVERS_LIB_INTEL_HDA_INCLUDE_INTEL_HDA_UTILS_UTILS_H_
|
08e97ccea6d8b9d3ac2d8d5aad722fe051d46a53 | 3fb4a4450fee9427e0c17f7e4db58a07d38d88e6 | /Sort.cpp | 10b92131841701ade48d1c89c148cd597ea6f043 | [] | no_license | weienjun/GetHub | bae149506285cfdbd3458310915f66eb0b4c29d4 | 250aaa32fb582023d9dd45e67dd281bc7b2d8230 | refs/heads/master | 2021-10-08T18:48:39.135895 | 2018-12-16T06:48:22 | 2018-12-16T06:48:22 | 111,115,489 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,429 | cpp | Sort.cpp | #include<iostream>
#include<stdlib.h>
#include<string.h>
#include<stack>
using namespace std;
//插入排序
//typedef int size_t;
//直接插入排序----稳定排序
//时间复杂度:O(N*(N-1)) = O(N^2)
//适用于数据接近有序,和数据较少的排序
void Sort(int* arr,size_t size)
{
//外循环,从前往后遍历
//end = i-1; i表示第i个数据,也表示前i个数据是有序的
//保存当前数值,用于覆盖后的替换(key = arr[i])
//内循环(end >=0 && key < arr[end]){
//数值移动, arr[end+1] = arr[end]; end--}
//还原key值 arr[end+1] = key;
size_t i = 0;
size_t prev = 0;
for(i = 1; i < size; i++)
{
prev = i-1;
int key = arr[i];
while(prev >= 0 && key > arr[prev])//数据后移,寻找插入的位置
{
arr[prev+1] = arr[prev];
prev--;
}
arr[prev+1] = key;//将小的数据(key)放在前边
}
}
//优化插入排序----采用二分查找的方法查找插入位置
void Sort2(int* arr,size_t size)//优化插入排序
{
//外循环遍历所有数值,从前往后{
//使用二分查找,找带插入位置(循环条件 left <= right){}
//搬移元素(循环条件 left <= end){
//还原key值,arr[left+1] = key;}}
int left = 0;
int right = size-1;
size_t i = 0;
for(i = 1; i < size; i++)
{
left = 0;
right = i - 1;
int key = arr[i];
int end = i - 1;
while(left <= right)//查找插入位置
{
int mid = left + ((right - left)>>1);
if(arr[i] < arr[mid])
right = mid - 1;
else
left = mid + 1;
}
while(left <= end)//搬移数据
{
arr[end+1] = arr[end];
end--;
}
arr[left] = key;//将数据小的放在前边
}
}
//插入排序的缺点:
//当数据量比较大时,比较的次数增多,搬移的数据量大,效率低
//当数据越无序,效率越低
//希尔排序----对直接插入排序的改进(将数据分组)
//目的:处理数据一次排序太多,和数据不接近有序问题..
//时间复杂度:O(N^1.25)---O(6*N^1.25)
//注:希尔排序为不稳定排序
void Sortx(int* arr,size_t size)
{
//当gep为素数时最优:gep = size/3+1
//间距循环大于0 gep > 0 { ---->-改进gep > 1 { get = gep/3+1;
//循环遍历当前分组,i = gep;i < size;i++ (+1表示跳跃分组处理,+gep连续分组处理)
//{end = i-gep;
//循环移动数据 end >= 0 && key < arr[end]{
//arr[end+gep] = arr[end];
//end = end-gep;}
//arr[end+gep] = key还原key值}
//gep--; }
//int gep = 3;
int gep = size-1;
while(gep > 1)
{
gep = gep/3+1;
size_t i = 0 ;
for(i = gep; i < size; i++)
{
int end = i-gep;//注此处不要使用无符号类型,否则存在越界问题
int key = arr[i];
while(end >= 0 && key < arr[end])
{
arr[end+gep] = arr[end];
end = end-gep;
}
arr[end+gep] = key;
}
gep--;
}
}
template<class T>
void Swap(T* L,T* R)
{
T tmp = *L;
*L = *R;
*R = tmp;
}
//选择排序----不稳定排序
//时间复杂度O(N^2)
//template<class T>
int ChooseSort(int* arr,size_t size)
{
size_t i,j;
int max = 0;
for(i = 0; i < size-1; i++)//循环排序所有数据
{
max = 0;//起始假设第一个数据最大
for(j = 0; j < size-i; j++)//找出但前轮最大的数子的下标
{
if(arr[max] < arr[j])
max = j;
}
if(max != size-i-1)//将最大的数据放在但前轮的最后一个位置
{
int tmp = arr[max];
arr[max] = arr[size-i-1];
arr[size-i-1] = tmp;
}
}
}
//选择排序优化
//一轮找出当前轮中最大,最小的两个数,将最大,最小的数放在相应的位置处
template<class T>
void ChooseSort2(T* arr,size_t size)
{
size_t begin = 0;
size_t end = size-1;
size_t i = 0;
while(begin < end)//循环处理所用数据
{
i = begin;
T min = begin;
T max = begin;
//找出当前轮最小的数据下标
for(; i <= end; i++)//注此处必须取=
if(arr[min] > arr[i])
min = i;
//找出当前轮最大的数据下标
for(i = begin; i <= end; i++)//取=
if(arr[max] < arr[i])
max = i;
//将最小的数据放在当前轮的最前面
if(min != begin)
Swap(&arr[min],&arr[begin]);
//处理最大数据在最前面的位置处时,导致最大的数据被移动到min位置问题
if(max == begin)
max = min;
//将最大的数据放在当前轮的最后
if(max != end)
Swap(&arr[max],&arr[end]);
//当前轮最大,最小数据位置处理完毕,进行下一轮处理
begin++;end--;
}
}
//冒泡排序----稳定排序
template<class T>
void BubbleSort(T* arr,size_t size)
{
size_t i = 0;
size_t j = 0;
T tmp = 0;//标记判断是否有序
for(; i < size-1; i++)//循环排序所有数据
{
tmp = 0;
for(j = 0; j < size-i-1; j++)//每两个数据依次进行比较,将大的朝后移动,直至放在当前轮的最后
{
if(arr[j] < arr[j+1])
Swap(&arr[j],&arr[j+1]);
tmp = 1;
}
if(tmp == 0)
return ;
}
}
//快速排序---递归处理方法1,2
//时间复杂度O(lgN)
template<class T>
void FastSort(T* arr,size_t left,size_t right)
{
if(arr && left < right)//递归出口
{
//size_t dev = _FastSort(arr,left,right);
size_t dev = 0;
//dev = _FastSort2(arr,left,right);//单轮处理
dev = _FastSort3(arr,left,right);//单轮处理
FastSort(arr,left,dev);//处理前面部分
FastSort(arr,dev+1,right);//处理后面部分
}
}
//快速排序方法1
template<class T>
size_t _FastSort(T* arr,size_t left,size_t right)
{
if(!arr || left >= right)
return 0;
size_t begin = left;//左标记
size_t end = right-1;//右标记
while(begin < end)//循环出口
{
T key = arr[end];//标记最后一个数据作为参考值
while(begin < end && arr[begin] <= key )//左值<参考值,左标记向后移动
begin++;
while(begin < end && arr[end] >= key)//右值>参考值,右标记向前移
end--;
if(begin < end)//左值与右值不在同一位置
Swap(&arr[begin],&arr[end]);//交换左右数值
}
if((int)begin < (int)right-1)//左值位置不在最后位置
Swap(&arr[begin],&arr[right-1]);//交换左值与最后的数据
return begin;//返回左值位置,作为数据前后的分隔位置
}
//快速排序方法2
template<class T>
size_t _FastSort2(T* arr,size_t left,size_t right)
{
int begin = left;
int end = right-1;
if(!arr && left >= right)
return 0;
T key = arr[end];
while(begin < end)
{
while(begin < end && arr[begin] <= key)
begin++;
if(begin < end)
arr[end--] = arr[begin];
while(begin < end && arr[end] >= key)
end--;
if(begin < end)
arr[begin++] = arr[end];
}
arr[begin] = key;//注在循环外
return begin;
}
//快速排序方法3
template<class T>
void FSort(T* arr,int right)
{
int left = 0;
int end = right-1;
if(!arr || left >= end)
return ;
T key = arr[0];
while(left < end)//循环处理至左与右相遇,才一轮处理完毕
{
//处理右侧大于key的值
while(left < end && arr[end] >= key)
end--;
if(left < end)
arr[left++] = arr[end];
//处理左侧小于key的值
while(left < end && arr[left] <= key)
left++;
if(left < end)
arr[end--] = arr[left];//key处的值被覆盖
arr[left] = key;
}
//arr[left] = key;//还原key值
FSort(arr,left);
FSort(arr+left+1,right-left-1);
}
template<class T>
int _FastSort3(T*arr,int left,int right)
{
int cur = left;
int prev = left-1;
T key = arr[right-1];
while(cur < right)
{
if(arr[cur] < key && ++prev != cur)
Swap(&arr[cur],&arr[prev]);
cur++;
}
if(++prev != right)
Swap(&arr[prev],&arr[right-1]);
return prev;
}
//快排
//时间复杂度:数据刚好可分成两部分时最优O(NlgN) 最差O(N^2)
//缺陷:当数据为倒序时,排序的效率低,O(N^2)
//解决:每次使用中间值(数值大小)作为比较值
//快排使用递归,当数据量比较大时,效率低
//当数据个数大于16时,使用插入排序
//使用栈,实现非递归的快排
void FSortStack(int* arr,size_t size)
{
if(!arr || size < 1)
return ;
stack<int> s;
int left = 0;
int right = size-1;
//左右入栈
s.push(right);
s.push(left);
//循环排序
while(!s.empty())
{
//获取当前左右的范围
left = s.top();s.pop();
right = s.top();s.pop();
//进行单轮排序
int begin = left;
int end = right;
int key = arr[end];//比较值
while(begin < end)
{
if(begin < end && arr[begin] < key)
begin++;
arr[end] = arr[begin];
if(begin < end && arr[end] > key)
end--;
arr[begin] = arr[end];
}
arr[begin] = key;//还原比较值
//进行排序左侧部分
if(left < begin-1)
{
s.push(begin-1);
s.push(left);
}
//排序右侧部分
if(right > begin+1)
{
s.push(right);
s.push(begin+1);
}
}
}
//快排缺陷,当数据倒序时进行顺序排序效率低为O(N^2)
//由于每次划分不均匀,不是按倍均匀划分,所以每个数据的排列都得遍历一次所有的数据,时间复杂度为O(N^2)
//解决方法:选取合适的参考值,使数据按均匀化份分
//快排优化---三数取中法
int num(int* arr,int left,int right)//将数据排序,将中间值放在最左侧,并返回作为参考值
{
int mid = left+((right-left)>>1);
if(arr[right] < arr[mid])
Swap(&arr[mid],&arr[right]);
if(arr[left] > arr[right])
Swap(&arr[left],&arr[right]);
if(arr[left] < arr[mid])
Swap(&arr[left],&arr[mid]);
return arr[left];//返回最左值作为参考值
}
void FSortQ(int* arr,int size)
{
stack<int> s;
int left = 0;
int right = size-1;
// int key = num(arr,begin,end);
//先将左右入栈
s.push(left);
s.push(right);
//栈不为空,循环排序
while(!s.empty())
{
//获取当前轮排序范围
right = s.top(); s.pop();
left = s.top(); s.pop();
//进行当前轮排序
int begin = left;
int end = right;
int key = num(arr,begin,end);
while(begin < end)
{
while(begin < end && arr[end] >= key)
end--;
arr[begin] = arr[end];
while(begin < end && arr[begin] <= key)
begin++;
arr[end] = arr[begin];
}
arr[begin] = key;
//获取范围
if(left < begin-1)//获取左侧部分
{
s.push(left);
s.push(begin-1);
}
if(right > begin+1)//获取右侧部分
{
s.push(begin+1);
s.push(right);
}
}
}
//归并处理--选取小的数据放在新空间中,依次存放两部分的数据,即完成两部分的有序合并
void MergeData(int* arr,int left,int mid, int right,int* temp)
{
int begin1 = left;
int end1 = mid;
int begin2 = mid;
int end2 = right;
int index = 0; //注拷贝时temp未加left,此处不可赋值为left
// int index = left; //注拷贝时temp未加left,此处不可赋值为left
while(begin1 < end1 && begin2 < end2)//循环选取小的数据放在新的空间中
{
if(arr[begin1] <= arr[begin2])//前部分数据小
{
temp[index++] = arr[begin1++];//该数据放在新的空间中,前部分标记后移
}
else
{
temp[index++] = arr[begin2++];
}
}
while(begin1 < end1)//前部分数据未放完
{
temp[index++] = arr[begin1++];
}
while(begin2 < end2)//后部分数据未放完
{
temp[index++] = arr[begin2++];
}
}
//归并排序---递归函数
void MergeSort(int* arr,int left,int right,int* temp)
{
if(right - left > 1)//划分只有1个元素时退出,不在划分,进行归并处理
{
int mid = left+((right-left)>>1);//每次划分成两部分
MergeSort(arr,left,mid,temp);//处理前部分
MergeSort(arr,mid,right,temp);//处理后部分
// MergeData(arr,left,mid,right,temp);//合并处理(将两部分进行有序合并)
memcpy(arr+left,temp,sizeof(arr[0])*(right-left));//将新空间当前的新数据,存放在上次存放的后面
memcpy(arr+left,temp+left,sizeof(arr[0])*(right-left));//将新空间当前的新数据,存放在上次存放的后面
}
}
//递归归并排序
void MS(int* arr,int size)
{
int* temp = (int*)malloc(sizeof(int)*size);
if(temp == NULL)
return ;
MergeSort(arr,0,size,temp);
free(temp);
}
//非递归归并排序
void MSNor(int* arr,int size)
{
int* temp = (int*)malloc(sizeof(int)*size);//保存合并后的结果
if(temp == NULL)
return ;
int gap = 1;//先从一个数据开始合并
int left = 0,right,mid;
while(gap < size)
{
for(int i = 0; i < size; i += 2*gap)
{
left = i;
mid = left+gap;//中间位置
if(mid > size)
mid = size;//mid越界,调整mid到最后
right = mid+gap;
if(right > size)
right = size;//right越界,调整到最后
MergeData(arr,left,mid,right,temp);
memcpy(arr+left,temp,sizeof(arr[0])*(right-left));
}
gap *= 2;//每次合并后,下次合并的数据个数扩大2倍
}
// memcpy(arr,temp,sizeof(arr[0])*size);
free(temp);
}
//归并排序:稳定
//归并排序时间复杂度:O(N*lgN)
//递归空间复杂度:
//非递归空间复杂度:O(1)
//计数排序---不稳定排序
//时间复杂度:O(N), 空间复杂度:O(M) M数据范围
//统计元素个数(空间大小= max-min,先确定数据大小范围(max,min))
//将数据的的次数放在数据所映射的下标中
//按下标映射的数值和次数的顺序输出数据,即为有序的数据
//释放空间,退出
typedef struct Num
{
int Max;
int Min;
}Num;
void Fun(int* arr,int size,Num* mm)
{
mm->Max = arr[0];
mm->Min = arr[0];
int i = 1;
for(;i < size; i++)
{
if(arr[i] < mm->Min)
mm->Min = arr[i];
else if(arr[i] > mm->Max)
mm->Max = arr[i];
}
}
#include<string.h>
void NSort(int* arr,int size)
{
Num mm;
mm.Max = 9;
mm.Min = 0;
// Fun(arr,size,&mm);//计算数据范围
int sz = mm.Max - mm.Min+1;
int* num = (int*)malloc(sizeof(int)*sz);
memset(num,0,sizeof(arr[0])*sz);//初始化新开辟的空间
int i = 0;
for(; i < size; i++)//统计个数
{
num[arr[i]-mm.Min] += 1;
}
//按顺序写回原数组中
int j = 0;
i = 0;
while(j <= sz)
{
while(num[j]--)
{
arr[i++] = j+mm.Min;
}
j++;
}
free(num);
}
//堆向下调整
void AdjustDown(int* arr,int size,int parent)
{
int child = parent*2+1;
while(child < size)
{
if(child+1 < size && arr[child] < arr[child+1])
child++;
if(arr[parent] < arr[child])
{
Swap(&arr[parent],&arr[child]);
parent = child;
child = parent*2+1;
}
else
return ;
}
}
//堆排序
void HeapSort(int* arr,int size)
{
if(!arr || size < 1)
return ;
int parent = (size-2) >> 1;
int i = 0;
//堆调整
for(i = parent; i >= 0;i--)
AdjustDown(arr,size,i);
//堆排序
for(i = size-1; i > 0;)
{
Swap(&arr[0],&arr[i]);//将堆顶与当前最后一个元素交换
AdjustDown(arr,i,0);//从堆顶向下调整(调整i个元素)
i--;//注:调整是一个开区间,即i是不进行调整的,所以调整之后在--
}
}
int maxnum(int* arr,size_t size)
{
size_t i = 0;
int tmp = arr[0];
for(i = 1; i < size ; i++)
{
if(tmp < arr[i])
tmp = arr[i];
}
return tmp;
}
//基数排序(桶排序)----稳定排序,时间复杂度:O(N),空间复杂度:O(N)
//低位关键码优先---先排低位 高位关键码优先----先排高位(与低位有区别,每位排好后,数据所在的桶不可变,只能桶内调整,即需采用递归)
//根据数据位数(按个位,十位...)排序,(先求最大数据的位数)
//利用哈希函数(取模映射),有10中情况(0-9),数组大小为10
//开辟一个空间(大小10)的桶(队列),每个桶可存多个数据,根据取模的方法获取位数值,再根据值将数据放在对应的桶中
//某个桶的地址 = 桶的起始地址+偏移量(之间 数据元素个数)
void RadixSortMsd(int* arr,size_t size)
{
//1、开辟10个大小的数组(桶个数10)
//桶:桶可以为队列(开销大),
//不使用队列:使用用一个数组,桶连续放在一个内存中,下一个桶位置 = 上一个桶地址+上一个桶元素个数
//1.1 开辟一个数组,大小为10,表示10个桶---count[10],存储桶中的元素
//循环10次,遍历数据集,统计每个桶中的数据个数(数据%10作为下标),桶中存数据个数
//1.2,定义一个数组大小为10(桶个数),存储每个桶的起始位置,---startadds[10] 桶的起始地址
//循环9次,统计桶的起始地址,桶起始位置 = 上一个桶的地址+上一个桶的元素个数
//1.3、定义一个桶,桶的大小为size(动态开辟)----bucket[size]
//2、入桶:将数据进行通过哈希函数(数据取模运算)放在对应的桶中,
//2.1、循环size次,取数据的低位(%10),获取桶的下标(桶地址),将数据存在对应的桶中,同时++,(++表示存储位置后移,该位置已存储数据)
//for(i < size;i+)
//{
//int buno = arr[i]%10; //计算桶编号
//bucket[startadds[buno]++] = arr[i];//根据桶编号,将数据放在对应的桶中,同时++,表示该位置已存储数据,下次往后存储
//}
//3、回收数据:按从小到大的桶号顺序回收(放到原数组中)
//循环处理其它位(循环次数为最大数据的位数)
//处理高位:类似2-3步驻,处理完所有数据的位(个位——>高位),即得到有序数据
int max = maxnum(arr,size);//获取最大数据
int bitnum = 1;//位标记
while(bitnum < max*10)//循环处理各个位
{
int count[10]={0};//需初始化 --- 注:每个位的排列都是无关的,所以必须放在循环内部
int startadds[10] = {0};//需初始化起始地址(桶所在的下标)
size_t i = 0;
//统计每个桶中数据个数
for(i = 0;i < size; i++)
{
count[arr[i]/bitnum%10]++;
}
//计算桶的起始位置(各个桶所在的下标)
for(i = 1; i < 10; i++)
startadds[i] = startadds[i-1]+count[i-1];
int* bluck = (int*)malloc(sizeof(int)*size);
//将数据放在对应的桶中
for(i = 0; i < size; i++)
{
int number = arr[i]/bitnum%10;
bluck[startadds[number]++] = arr[i];
}
//将桶中的数据回收(放回数组)
memmove(arr,bluck,sizeof(int)*size);
bitnum *= 10;//处理下个位(高位)
}
}
void print(int* arr,size_t size)
{
size_t i = 0;
for(; i < size; i++)
{
cout << arr[i] << " " ;
}
cout << endl;
}
int main()
{
int arr[] = {1,9,8,9,4,6,9,8,2,0};
size_t sz = sizeof(arr)/sizeof(arr[0]);
print(arr,sz);
// Sortx(arr,sz);
// ChooseSort2(arr,sz);
// BubbleSort(arr,sz);
//FastSort(arr,0,sz);
// FSort(arr,sz);
//FSortStack(arr,sz);
//MS(arr,sz);
// MSNor(arr,sz);
// NSort(arr,sz);
// HeapSort(arr,sz);
// FSortQ(arr,sz);
RadixSortMsd(arr,sz);
print(arr,sz);
return 0;
}
|
415edb02c4bbca3e286a00fba1c14eb3fb7740ab | 5e6354b6e8894d4294003679166db0e5e312ef47 | /cppFiles/HttpResponse.cpp | 7af55ce62367353ee3becb7dcde409901dcfbf24 | [] | no_license | yexuechao/tiny-web-server | 35f228c86234bd353898444cb60d3f9b1526e653 | b922c5d27809605d0d19b1be3e8a8c7ca9d74fca | refs/heads/master | 2021-01-11T12:05:46.629104 | 2017-03-17T11:57:43 | 2017-03-17T11:57:43 | 76,548,653 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,921 | cpp | HttpResponse.cpp | //
// Created by yxc on 16-12-3.
//
#include <sys/stat.h>
#include <fstream>
#include <zconf.h>
#include <wait.h>
#include <iostream>
#include "../hFiles/HttpResponse.h"
std::map<std::string,std::string> filetype={
{ "txt", "text/plain" },
{ "c", "text/plain" },
{ "h", "text/plain" },
{ "html", "text/html" },
{ "htm", "text/htm" },
{ "css", "text/css" },
{ "gif", "image/gif" },
{ "jpg", "image/jpeg" },
{ "jpeg", "image/jpeg" },
{ "png", "image/png" },
{ "pdf", "application/pdf" },
{ "ps", "application/postsript" }
};
static const std::string &contentType(string path) {
//find final .
std::string url(path);
size_t found=url.find_last_of('.');
if(found==-1 || url.substr(found+1).find('/')!=std::string::npos){
//no extension
return "application/misc";
}
std::string extension=url.substr(found+1);
return filetype[extension];
}
HttpResponse::HttpResponse()
:response_error(0){}
HttpResponse::~HttpResponse() {}
void HttpResponse::unimplemented() {
//501
response.status=501;
response.version="HTTP/1.1";
response.status_description="Method Not Implemented";
response.content=
"<HTML><HEAD><TITLE>Method Not Implemented\r\n"
"</TITLE></HEAD>\r\n"
"<BODY><P>HTTP request method not supported.\r\n"
"</BODY></HTML>\r\n";
response.header["Content-Type"]="text/html";
return ;
}
void HttpResponse::getMethodResponse() {
std::string query_string(hhp_context.url);
size_t found=query_string.find_first_of('?',0);
if(found!=std::string::npos){
hhp_context.url=query_string.substr(0,found);
hhp_context.query_string=query_string.substr(found+1,std::string::npos);
hhp_context.cgi=1;
}
if(!addIndex()){
notFound();
return ;
}
if(hhp_context.cgi!=1){
successGetNoCgi();
}else{
std::cout<<"get cgi"<<std::endl;
getCgiResponse();
}
}
void HttpResponse::successGetNoCgi() {
std::ifstream in(hhp_context.url);
if(!in.is_open()){
std::cout<<"get no found"<<std::endl;
notFound();
return ;
}
successHeader();
successFile(in);
return ;
}
bool HttpResponse::addIndex() {
struct stat st;
std::string path=target;
if(hhp_context.cgi!=1){
if(hhp_context.url.at(hhp_context.url.length()-1)=='/'){
path=path+hhp_context.url+"index.html";
}else{
path=path+textSource+hhp_context.url;
}
hhp_context.url=path;
}else{
path=path+hhp_context.url;
hhp_context.url=path;
}
if (stat(path.c_str(), &st) == -1) {
std::cout<<"add index return false"<<std::endl;
return false;
} else {
if ((st.st_mode & S_IFMT) == S_IFDIR){
path=path+"/index.html";
hhp_context.url=path;
}
// if ((st.st_mode & S_IXUSR) || (st.st_mode & S_IXGRP) || (st.st_mode & S_IXOTH)){
// hhp_context->cgi=1;
// }
return true;
}
}
void HttpResponse::notFound() {
//404
response.status=404;
response.version=hhp_context.version;
response.status_description="NOT FOUND";
response.header["Content-Type"]="text/html";
response.content=
"<HTML><TITLE>Not Found</TITLE>\r\n"
"<BODY><P>The server could not fulfill\r\n"
"your request because the resource specified\r\n"
"is unavailable or nonexistent.\r\n"
"</BODY></HTML>\r\n";
return ;
}
void HttpResponse::successHeader() {
successLine();
response.header["Content-Type"]=contentType(hhp_context.url);
response.header["Connection"]="close";
}
void HttpResponse::successFile(std::ifstream &in) {
in>>response.content;
return ;
}
void HttpResponse::postResponse() {
if(!addIndex()){
std::cout<<"add index and not found"<<std::endl;
notFound();
return ;
}
map<string,string>::iterator itr=hhp_context.headers.find("Content-Length");
if(itr==hhp_context.headers.end()){
//bad request
badRequest();
}
int cgi_output[2];
int cgi_input[2];
if (pipe(cgi_output) < 0) {
cannotExecute();
return;
}
if (pipe(cgi_input) < 0) {
cannotExecute();
return;
}
pid_t pid;
if ( (pid = fork()) < 0 ) {
cannotExecute();
return;
}
successLine();
if(pid==0){
//close pipe
Close(cgi_input[1]);
Close(cgi_output[0]);
Dup2(cgi_input[0],STDIN_FILENO);
Dup2(cgi_output[1],STDOUT_FILENO);
std::string length="CONTENT-LENGTH=";
length=length+itr->second;
putenv((char *) length.c_str());
execl((hhp_context.url).c_str(), NULL);
return;
}else{
Close(cgi_input[0]);
Close(cgi_output[1]);
write(cgi_input[1],hhp_context.body.c_str(),stoi(itr->second));
char content[MAXSIZE+1];
ssize_t n=-1;
n=read(cgi_output[0],content,MAXSIZE);
content[n]='\0';
response.content.assign(content);
Close(cgi_output[0]);
Close(cgi_input[1]);
waitpid(pid,NULL, 0);
}
}
void HttpResponse::successLine() {
response.version=hhp_context.version;
response.status=200;
response.status_description="OK";
return ;
}
void HttpResponse::cannotExecute() {
response.status=500;
response.version=hhp_context.version;
response.status_description="Server error";
response.header["Content-Type"]="text/html";
response.content=
"<h1>Error prohibited CGI execution</h1>\r\n";
}
void HttpResponse::badRequest() {
response.status=400;
response.version=hhp_context.version;
response.status_description="BAD REQUEST";
response.header["Content-Type"]="text/html";
response.content=
"<h1>Your browser sent a bad request,"
"such as a POST without a Content-Length.</h1>\r\n";
return;
}
void HttpResponse::getCgiResponse() {
int cgi_output[2];
int cgi_input[2];
if (pipe(cgi_output) < 0) {
cannotExecute();
return;
}
if (pipe(cgi_input) < 0) {
cannotExecute();
return;
}
pid_t pid;
if ( (pid = fork()) < 0 ) {
cannotExecute();
return;
}
successLine();
if(pid==0){
close(cgi_output[0]);
close(cgi_input[1]);
dup2(cgi_output[1], STDOUT_FILENO);
dup2(cgi_input[0], STDIN_FILENO);
std::string query_string="QUERY_STRING=";
query_string=query_string+hhp_context.query_string;
putenv((char *) query_string.c_str());
execl(hhp_context.url.c_str(), NULL);
return ;
}else{
close(cgi_output[1]);
close(cgi_input[0]);
char content[MAXSIZE+1];
ssize_t n=-1;
n=read(cgi_output[0],content,MAXSIZE);
content[n]='\0';
response.content.assign(content);
Close(cgi_output[0]);
Close(cgi_input[1]);
waitpid(pid,NULL, 0);
}
}
void HttpResponse::Close(int fd) {
if(-1==close(fd)){
std::cerr<<"close error"<<std::endl;
response_error=1;
}
}
void HttpResponse::Dup2(int fd1, int fd2) {
if(-1==dup2(fd1,fd2)){
std::cerr<<"dup2 error"<<std::endl;
response_error=1;
}
}
int HttpResponse::getResponse_error() const {
return response_error;
}
void HttpResponse::setResponse_error(int response_error) {
HttpResponse::response_error = response_error;
}
http_response &HttpResponse::getResponse(){
return response;
}
http_request_t HttpResponse::getHhp_context() const {
return hhp_context;
}
void HttpResponse::setHhp_context(http_request_t hhp_context) {
HttpResponse::hhp_context = hhp_context;
}
|
23db8803b68654eb013f423b10ab020cea6427da | 64e4d160ed5b6df332473ec32a2e04c0356230ad | /src/ParameterList.cpp | f82f2db9256e9831a534356133ee9c2437687e7a | [
"MIT"
] | permissive | FarmBot/farmbot-arduino-firmware | aa0269977497414675dff6b268c91022cdc5b1b0 | b34190c297a5a8753cd1a63a0e7489000ed395a6 | refs/heads/main | 2023-08-23T06:02:03.733088 | 2022-11-08T19:49:57 | 2022-11-08T19:49:57 | 19,436,990 | 410 | 226 | MIT | 2022-11-07T20:25:00 | 2014-05-04T21:52:02 | C++ | UTF-8 | C++ | false | false | 21,099 | cpp | ParameterList.cpp | #include "ParameterList.h"
#include <EEPROM.h>
static ParameterList *instanceParam;
long paramValues[PARAM_NR_OF_PARAMS];
ParameterList *ParameterList::getInstance()
{
if (!instanceParam)
{
instanceParam = new ParameterList();
};
return instanceParam;
}
ParameterList::ParameterList()
{
// at the first boot, load default parameters and set the parameter version
// so during subsequent boots the values are just loaded from eeprom
// unless the eeprom is disabled with a parameter
int paramChangeNr = 0;
int tmcParamChangeNr = 0;
int paramVersion = readValueEeprom(0);
if (paramVersion <= 0)
{
setAllValuesToDefault();
writeAllValuesToEeprom();
}
else
{
if (readValueEeprom(PARAM_USE_EEPROM) == 1)
{
readAllValuesFromEeprom();
} else {
setAllValuesToDefault();
}
}
}
// ===== Interface functions for the raspberry pi =====
int ParameterList::readValue(int id)
{
// Check if the value is an existing parameter
if (validParam(id))
{
// Retrieve the value from memory
long value = paramValues[id];
// Send to the raspberry pi
Serial.print("R21");
Serial.print(" ");
Serial.print("P");
Serial.print(id);
Serial.print(" ");
Serial.print("V");
Serial.print(value);
//Serial.print("\r\n");
CurrentState::getInstance()->printQAndNewLine();
}
else
{
Serial.print("R99 Error: invalid parameter id\r\n");
}
return 0;
}
int ParameterList::writeValue(int id, long value)
{
if (paramChangeNr < 9999)
{
paramChangeNr++;
}
else
{
paramChangeNr = 0;
}
if (tmcParamChangeNr < 9999)
{
if (
id == 81 ||
id == 82 ||
id == 83 ||
id == 85 ||
id == 86 ||
id == 87 ||
id == 91 ||
id == 92 ||
id == 93 ||
id == 165 ||
id == 166 ||
id == 167
)
{
tmcParamChangeNr++;
}
}
else
{
tmcParamChangeNr = 0;
}
// Check if the value is a valid parameter
if (validParam(id))
{
// Store the value in memory
paramValues[id] = value;
writeValueEeprom(id, value);
readValue(id);
}
else
{
Serial.print("R99 Error: invalid parameter id\r\n");
}
/*
// Debugging output
Serial.print("R99");
Serial.print(" ");
Serial.print("writeValue");
Serial.print(" ");
Serial.print("P");
Serial.print(" ");
Serial.print(id);
Serial.print(" ");
Serial.print("V");
Serial.print(" ");
Serial.print(value);
//Serial.print("\r\n");
CurrentState::getInstance()->printQAndNewLine();
*/
// If any value is written,
// trigger the loading of the new configuration in all other modules
sendConfigToModules();
return 0;
}
void ParameterList::sendConfigToModules()
{
// Trigger other modules to load the new values
PinGuard::getInstance()->loadConfig();
}
int ParameterList::readAllValues()
{
// Make a dump of all values
// Check if it's a valid value to keep the junk out of the list
for (int i = 0; i < PARAM_NR_OF_PARAMS; i++)
{
if (validParam(i))
{
readValue(i);
}
}
}
long ParameterList::getValue(int id)
{
return paramValues[id];
}
int ParameterList::paramChangeNumber()
{
return paramChangeNr;
}
int ParameterList::tmcParamChangeNumber()
{
return tmcParamChangeNr;
}
// ===== eeprom handling ====
long ParameterList::readValueEeprom(int id)
{
// Assume all values are ints and calculate address for that
int address = id * 2;
//Read the 2 bytes from the eeprom memory.
long one = EEPROM.read(address + 0);
long two = EEPROM.read(address + 1);
long three = 0;
long four = 0;
// Process 2-byte or 4-byte EEPROM value
// Return -1 for negative values (1 in highest bit) to indicate value should be set to default.
if (id == 141 || id == 142 || id == 143)
{
// 4-byte EEPROM value
three = EEPROM.read(address + 20);
four = EEPROM.read(address + 21);
if ((three == 255 && four == 255) && !(one == 255 && two == 255))
{
// Value may have been recently increased to 4 bytes. Keep only the first two.
three = 0;
four = 0;
if (two > 127) { return -1; }
}
if (four > 127) { return -1; }
}
else
{
// 2-byte EEPROM value
if (two > 127) { return -1; }
}
// Return the recomposed long by using bitshift.
return ((one & 0xFFl) << 0) + ((two & 0xFFl) << 8) + ((three & 0xFFl) << 16) + ((four & 0xFFl) << 24);
}
int ParameterList::writeValueEeprom(int id, long value)
{
// Assume all values are ints and calculate address for that
int address = id * 2;
//Decomposition from a int to 2 bytes by using bitshift.
//One = Least significant -> Four = Most significant byte
byte one = (value & 0xFF);
byte two = ((value >> 8) & 0xFF);
byte three = ((value >> 16) & 0xFF);
byte four = ((value >> 24) & 0xFF);
//Write the 4 bytes into the eeprom memory.
EEPROM.write(address + 0, one);
EEPROM.write(address + 1, two);
// Only this parameter needs a long value
if (id == 141 || id == 142 || id == 143)
{
EEPROM.write(address + 20, three);
EEPROM.write(address + 21, four);
}
return 0;
}
int ParameterList::readAllValuesFromEeprom()
{
// Write all existing values to eeprom
for (int i = 0; i < PARAM_NR_OF_PARAMS; i++)
{
if (validParam(i))
{
paramValues[i] = readValueEeprom(i);
if (paramValues[i] == -1)
{
// When parameters are still on default,
// load a good value and save it
loadDefaultValue(i);
writeValueEeprom(i, paramValues[i]);
}
}
}
}
int ParameterList::writeAllValuesToEeprom()
{
// Write all existing values to eeprom
for (int i = 0; i < 150; i++)
{
if (validParam(i))
{
writeValueEeprom(i, paramValues[i]);
}
}
}
// ==== parameter valdation and defaults
int ParameterList::setAllValuesToDefault()
{
// Copy default values to the memory values
for (int i = 0; i < PARAM_NR_OF_PARAMS; i++)
{
if (validParam(i))
{
loadDefaultValue(i);
}
}
}
void ParameterList::loadDefaultValue(int id)
{
switch (id)
{
case PARAM_VERSION:
paramValues[id] = PARAM_VERSION_DEFAULT;
break;
case PARAM_TEST:
paramValues[id] = PARAM_TEST_DEFAULT;
break;
case PARAM_CONFIG_OK:
paramValues[id] = PARAM_CONFIG_OK_DEFAULT;
break;
case PARAM_USE_EEPROM:
paramValues[id] = PARAM_USE_EEPROM_DEFAULT;
break;
case PARAM_E_STOP_ON_MOV_ERR:
paramValues[id] = PARAM_E_STOP_ON_MOV_ERR_DEFAULT;
break;
case PARAM_MOV_NR_RETRY:
paramValues[id] = PARAM_MOV_NR_RETRY_DEFAULT;
break;
case MOVEMENT_TIMEOUT_X:
paramValues[id] = MOVEMENT_TIMEOUT_X_DEFAULT;
break;
case MOVEMENT_TIMEOUT_Y:
paramValues[id] = MOVEMENT_TIMEOUT_Y_DEFAULT;
break;
case MOVEMENT_TIMEOUT_Z:
paramValues[id] = MOVEMENT_TIMEOUT_Z_DEFAULT;
break;
case MOVEMENT_KEEP_ACTIVE_X:
paramValues[id] = MOVEMENT_KEEP_ACTIVE_X_DEFAULT;
break;
case MOVEMENT_KEEP_ACTIVE_Y:
paramValues[id] = MOVEMENT_KEEP_ACTIVE_Y_DEFAULT;
break;
case MOVEMENT_KEEP_ACTIVE_Z:
paramValues[id] = MOVEMENT_KEEP_ACTIVE_Z_DEFAULT;
break;
case MOVEMENT_HOME_AT_BOOT_X:
paramValues[id] = MOVEMENT_HOME_AT_BOOT_X_DEFAULT;
break;
case MOVEMENT_HOME_AT_BOOT_Y:
paramValues[id] = MOVEMENT_HOME_AT_BOOT_Y_DEFAULT;
break;
case MOVEMENT_HOME_AT_BOOT_Z:
paramValues[id] = MOVEMENT_HOME_AT_BOOT_Z_DEFAULT;
break;
case MOVEMENT_INVERT_ENDPOINTS_X:
paramValues[id] = MOVEMENT_INVERT_ENDPOINTS_X_DEFAULT;
break;
case MOVEMENT_INVERT_ENDPOINTS_Y:
paramValues[id] = MOVEMENT_INVERT_ENDPOINTS_Y_DEFAULT;
break;
case MOVEMENT_INVERT_ENDPOINTS_Z:
paramValues[id] = MOVEMENT_INVERT_ENDPOINTS_Z_DEFAULT;
break;
case MOVEMENT_ENABLE_ENDPOINTS_X:
paramValues[id] = MOVEMENT_ENABLE_ENDPOINTS_X_DEFAULT;
break;
case MOVEMENT_ENABLE_ENDPOINTS_Y:
paramValues[id] = MOVEMENT_ENABLE_ENDPOINTS_Y_DEFAULT;
break;
case MOVEMENT_ENABLE_ENDPOINTS_Z:
paramValues[id] = MOVEMENT_ENABLE_ENDPOINTS_Z_DEFAULT;
break;
case MOVEMENT_INVERT_MOTOR_X:
paramValues[id] = MOVEMENT_INVERT_MOTOR_X_DEFAULT;
break;
case MOVEMENT_INVERT_MOTOR_Y:
paramValues[id] = MOVEMENT_INVERT_MOTOR_Y_DEFAULT;
break;
case MOVEMENT_INVERT_MOTOR_Z:
paramValues[id] = MOVEMENT_INVERT_MOTOR_Z_DEFAULT;
break;
case MOVEMENT_SECONDARY_MOTOR_X:
paramValues[id] = MOVEMENT_SECONDARY_MOTOR_X_DEFAULT;
break;
case MOVEMENT_SECONDARY_MOTOR_INVERT_X:
paramValues[id] = MOVEMENT_SECONDARY_MOTOR_INVERT_X_DEFAULT;
break;
case MOVEMENT_STEPS_ACC_DEC_X:
paramValues[id] = MOVEMENT_STEPS_ACC_DEC_X_DEFAULT;
break;
case MOVEMENT_STEPS_ACC_DEC_Y:
paramValues[id] = MOVEMENT_STEPS_ACC_DEC_Y_DEFAULT;
break;
case MOVEMENT_STEPS_ACC_DEC_Z:
paramValues[id] = MOVEMENT_STEPS_ACC_DEC_Z_DEFAULT;
break;
case MOVEMENT_STEPS_ACC_DEC_Z2:
paramValues[id] = MOVEMENT_STEPS_ACC_DEC_Z2_DEFAULT;
break;
case MOVEMENT_STOP_AT_HOME_X:
paramValues[id] = MOVEMENT_STOP_AT_HOME_X_DEFAULT;
break;
case MOVEMENT_STOP_AT_HOME_Y:
paramValues[id] = MOVEMENT_STOP_AT_HOME_Y_DEFAULT;
break;
case MOVEMENT_STOP_AT_HOME_Z:
paramValues[id] = MOVEMENT_STOP_AT_HOME_Z_DEFAULT;
break;
case MOVEMENT_HOME_UP_X:
paramValues[id] = MOVEMENT_HOME_UP_X_DEFAULT;
break;
case MOVEMENT_HOME_UP_Y:
paramValues[id] = MOVEMENT_HOME_UP_Y_DEFAULT;
break;
case MOVEMENT_HOME_UP_Z:
paramValues[id] = MOVEMENT_HOME_UP_Z_DEFAULT;
break;
case MOVEMENT_STEP_PER_MM_X:
paramValues[id] = MOVEMENT_STEP_PER_MM_X_DEFAULT;
break;
case MOVEMENT_STEP_PER_MM_Y:
paramValues[id] = MOVEMENT_STEP_PER_MM_Y_DEFAULT;
break;
case MOVEMENT_STEP_PER_MM_Z:
paramValues[id] = MOVEMENT_STEP_PER_MM_Z_DEFAULT;
break;
case MOVEMENT_MIN_SPD_X:
paramValues[id] = MOVEMENT_MIN_SPD_X_DEFAULT;
break;
case MOVEMENT_MIN_SPD_Y:
paramValues[id] = MOVEMENT_MIN_SPD_Y_DEFAULT;
break;
case MOVEMENT_MIN_SPD_Z:
paramValues[id] = MOVEMENT_MIN_SPD_Z_DEFAULT;
break;
case MOVEMENT_MIN_SPD_Z2:
paramValues[id] = MOVEMENT_MIN_SPD_Z2_DEFAULT;
break;
case MOVEMENT_HOME_SPEED_X:
paramValues[id] = MOVEMENT_HOME_SPEED_X_DEFAULT;
break;
case MOVEMENT_HOME_SPEED_Y:
paramValues[id] = MOVEMENT_HOME_SPEED_Y_DEFAULT;
break;
case MOVEMENT_HOME_SPEED_Z:
paramValues[id] = MOVEMENT_HOME_SPEED_Z_DEFAULT;
break;
case MOVEMENT_MAX_SPD_X:
paramValues[id] = MOVEMENT_MAX_SPD_X_DEFAULT;
break;
case MOVEMENT_MAX_SPD_Y:
paramValues[id] = MOVEMENT_MAX_SPD_Y_DEFAULT;
break;
case MOVEMENT_MAX_SPD_Z:
paramValues[id] = MOVEMENT_MAX_SPD_Z_DEFAULT;
break;
case MOVEMENT_MAX_SPD_Z2:
paramValues[id] = MOVEMENT_MAX_SPD_Z2_DEFAULT;
break;
case MOVEMENT_INVERT_2_ENDPOINTS_X:
paramValues[id] = MOVEMENT_INVERT_2_ENDPOINTS_X_DEFAULT;
break;
case MOVEMENT_INVERT_2_ENDPOINTS_Y:
paramValues[id] = MOVEMENT_INVERT_2_ENDPOINTS_Y_DEFAULT;
break;
case MOVEMENT_INVERT_2_ENDPOINTS_Z:
paramValues[id] = MOVEMENT_INVERT_2_ENDPOINTS_Z_DEFAULT;
break;
case MOVEMENT_STOP_AT_MAX_X:
paramValues[id] = MOVEMENT_STOP_AT_MAX_X_DEFAULT;
break;
case MOVEMENT_STOP_AT_MAX_Y:
paramValues[id] = MOVEMENT_STOP_AT_MAX_Y_DEFAULT;
break;
case MOVEMENT_STOP_AT_MAX_Z:
paramValues[id] = MOVEMENT_STOP_AT_MAX_Z_DEFAULT;
break;
case MOVEMENT_CALIBRATION_RETRY_X:
paramValues[id] = MOVEMENT_CALIBRATION_RETRY_X_DEFAULT;
break;
case MOVEMENT_CALIBRATION_RETRY_Y:
paramValues[id] = MOVEMENT_CALIBRATION_RETRY_Y_DEFAULT;
break;
case MOVEMENT_CALIBRATION_RETRY_Z:
paramValues[id] = MOVEMENT_CALIBRATION_RETRY_Z_DEFAULT;
break;
case MOVEMENT_CALIBRATION_RETRY_TOTAL_X:
paramValues[id] = MOVEMENT_CALIBRATION_RETRY_X_TOTAL_DEFAULT;
break;
case MOVEMENT_CALIBRATION_RETRY_TOTAL_Y:
paramValues[id] = MOVEMENT_CALIBRATION_RETRY_Y_TOTAL_DEFAULT;
break;
case MOVEMENT_CALIBRATION_RETRY_TOTAL_Z:
paramValues[id] = MOVEMENT_CALIBRATION_RETRY_Z_TOTAL_DEFAULT;
break;
case MOVEMENT_CALIBRATION_DEADZONE_X:
paramValues[id] = MOVEMENT_CALIBRATION_DEADZONE_X_DEFAULT;
break;
case MOVEMENT_CALIBRATION_DEADZONE_Y:
paramValues[id] = MOVEMENT_CALIBRATION_DEADZONE_Y_DEFAULT;
break;
case MOVEMENT_CALIBRATION_DEADZONE_Z:
paramValues[id] = MOVEMENT_CALIBRATION_DEADZONE_Z_DEFAULT;
break;
case MOVEMENT_AXIS_STEALTH_X:
paramValues[id] = MOVEMENT_AXIS_STEALTH_X_DEFAULT;
break;
case MOVEMENT_AXIS_STEALTH_Y:
paramValues[id] = MOVEMENT_AXIS_STEALTH_Y_DEFAULT;
break;
case MOVEMENT_AXIS_STEALTH_Z:
paramValues[id] = MOVEMENT_AXIS_STEALTH_Z_DEFAULT;
break;
case MOVEMENT_MOTOR_CURRENT_X:
paramValues[id] = MOVEMENT_MOTOR_CURRENT_X_DEFAULT;
break;
case MOVEMENT_MOTOR_CURRENT_Y:
paramValues[id] = MOVEMENT_MOTOR_CURRENT_Y_DEFAULT;
break;
case MOVEMENT_MOTOR_CURRENT_Z:
paramValues[id] = MOVEMENT_MOTOR_CURRENT_Z_DEFAULT;
break;
case MOVEMENT_STALL_SENSITIVITY_X:
paramValues[id] = MOVEMENT_STALL_SENSITIVITY_X_DEFAULT;
break;
case MOVEMENT_STALL_SENSITIVITY_Y:
paramValues[id] = MOVEMENT_STALL_SENSITIVITY_Y_DEFAULT;
break;
case MOVEMENT_STALL_SENSITIVITY_Z:
paramValues[id] = MOVEMENT_STALL_SENSITIVITY_Z_DEFAULT;
break;
case MOVEMENT_MICROSTEPS_X:
paramValues[id] = MOVEMENT_MICROSTEPS_X_DEFAULT;
break;
case MOVEMENT_MICROSTEPS_Y:
paramValues[id] = MOVEMENT_MICROSTEPS_Y_DEFAULT;
break;
case MOVEMENT_MICROSTEPS_Z:
paramValues[id] = MOVEMENT_MICROSTEPS_Z_DEFAULT;
break;
case ENCODER_ENABLED_X:
paramValues[id] = ENCODER_ENABLED_X_DEFAULT;
break;
case ENCODER_ENABLED_Y:
paramValues[id] = ENCODER_ENABLED_Y_DEFAULT;
break;
case ENCODER_ENABLED_Z:
paramValues[id] = ENCODER_ENABLED_Z_DEFAULT;
break;
case ENCODER_TYPE_X:
paramValues[id] = ENCODER_TYPE_X_DEFAULT;
break;
case ENCODER_TYPE_Y:
paramValues[id] = ENCODER_TYPE_Y_DEFAULT;
break;
case ENCODER_TYPE_Z:
paramValues[id] = ENCODER_TYPE_Z_DEFAULT;
break;
case ENCODER_MISSED_STEPS_MAX_X:
paramValues[id] = ENCODER_MISSED_STEPS_MAX_X_DEFAULT;
break;
case ENCODER_MISSED_STEPS_MAX_Y:
paramValues[id] = ENCODER_MISSED_STEPS_MAX_Y_DEFAULT;
break;
case ENCODER_MISSED_STEPS_MAX_Z:
paramValues[id] = ENCODER_MISSED_STEPS_MAX_Z_DEFAULT;
break;
case ENCODER_SCALING_X:
paramValues[id] = ENCODER_SCALING_X_DEFAULT;
break;
case ENCODER_SCALING_Y:
paramValues[id] = ENCODER_SCALING_Y_DEFAULT;
break;
case ENCODER_SCALING_Z:
paramValues[id] = ENCODER_SCALING_Z_DEFAULT;
break;
case ENCODER_MISSED_STEPS_DECAY_X:
paramValues[id] = ENCODER_MISSED_STEPS_DECAY_X_DEFAULT;
break;
case ENCODER_MISSED_STEPS_DECAY_Y:
paramValues[id] = ENCODER_MISSED_STEPS_DECAY_Y_DEFAULT;
break;
case ENCODER_MISSED_STEPS_DECAY_Z:
paramValues[id] = ENCODER_MISSED_STEPS_DECAY_Z_DEFAULT;
break;
case ENCODER_USE_FOR_POS_X:
paramValues[id] = ENCODER_USE_FOR_POS_X_DEFAULT;
break;
case ENCODER_USE_FOR_POS_Y:
paramValues[id] = ENCODER_USE_FOR_POS_Y_DEFAULT;
break;
case ENCODER_USE_FOR_POS_Z:
paramValues[id] = ENCODER_USE_FOR_POS_Z_DEFAULT;
break;
case ENCODER_INVERT_X:
paramValues[id] = ENCODER_INVERT_X_DEFAULT;
break;
case ENCODER_INVERT_Y:
paramValues[id] = ENCODER_INVERT_Y_DEFAULT;
break;
case ENCODER_INVERT_Z:
paramValues[id] = ENCODER_INVERT_Z_DEFAULT;
break;
case PIN_GUARD_1_PIN_NR:
paramValues[id] = PIN_GUARD_1_PIN_NR_DEFAULT;
break;
case PIN_GUARD_1_TIME_OUT:
paramValues[id] = PIN_GUARD_1_TIME_OUT_DEFAULT;
break;
case PIN_GUARD_1_ACTIVE_STATE:
paramValues[id] = PIN_GUARD_1_ACTIVE_STATE_DEFAULT;
break;
case PIN_GUARD_2_PIN_NR:
paramValues[id] = PIN_GUARD_2_PIN_NR_DEFAULT;
break;
case PIN_GUARD_2_TIME_OUT:
paramValues[id] = PIN_GUARD_2_TIME_OUT_DEFAULT;
break;
case PIN_GUARD_2_ACTIVE_STATE:
paramValues[id] = PIN_GUARD_2_ACTIVE_STATE_DEFAULT;
break;
case PIN_GUARD_3_PIN_NR:
paramValues[id] = PIN_GUARD_3_PIN_NR_DEFAULT;
break;
case PIN_GUARD_3_TIME_OUT:
paramValues[id] = PIN_GUARD_3_TIME_OUT_DEFAULT;
break;
case PIN_GUARD_3_ACTIVE_STATE:
paramValues[id] = PIN_GUARD_3_ACTIVE_STATE_DEFAULT;
break;
case PIN_GUARD_4_PIN_NR:
paramValues[id] = PIN_GUARD_4_PIN_NR_DEFAULT;
break;
case PIN_GUARD_4_TIME_OUT:
paramValues[id] = PIN_GUARD_4_TIME_OUT_DEFAULT;
break;
case PIN_GUARD_4_ACTIVE_STATE:
paramValues[id] = PIN_GUARD_4_ACTIVE_STATE_DEFAULT;
break;
case PIN_GUARD_5_PIN_NR:
paramValues[id] = PIN_GUARD_5_PIN_NR_DEFAULT;
break;
case PIN_GUARD_5_TIME_OUT:
paramValues[id] = PIN_GUARD_5_TIME_OUT_DEFAULT;
break;
case PIN_GUARD_5_ACTIVE_STATE:
paramValues[id] = PIN_GUARD_5_ACTIVE_STATE_DEFAULT;
break;
case PIN_REPORT_1_PIN_NR:
paramValues[id] = PIN_REPORT_1_PIN_NR_DEFAULT;
break;
case PIN_REPORT_2_PIN_NR:
paramValues[id] = PIN_REPORT_1_PIN_NR_DEFAULT;
break;
default:
paramValues[id] = 0;
break;
}
}
bool ParameterList::validParam(int id)
{
// Check if the id is a valid one
switch (id)
{
case PARAM_VERSION:
case PARAM_CONFIG_OK:
case PARAM_USE_EEPROM:
case PARAM_E_STOP_ON_MOV_ERR:
case PARAM_MOV_NR_RETRY:
case MOVEMENT_TIMEOUT_X:
case MOVEMENT_TIMEOUT_Y:
case MOVEMENT_TIMEOUT_Z:
case MOVEMENT_KEEP_ACTIVE_X:
case MOVEMENT_KEEP_ACTIVE_Y:
case MOVEMENT_KEEP_ACTIVE_Z:
case MOVEMENT_HOME_AT_BOOT_X:
case MOVEMENT_HOME_AT_BOOT_Y:
case MOVEMENT_HOME_AT_BOOT_Z:
case MOVEMENT_ENABLE_ENDPOINTS_X:
case MOVEMENT_ENABLE_ENDPOINTS_Y:
case MOVEMENT_ENABLE_ENDPOINTS_Z:
case MOVEMENT_INVERT_ENDPOINTS_X:
case MOVEMENT_INVERT_ENDPOINTS_Y:
case MOVEMENT_INVERT_ENDPOINTS_Z:
case MOVEMENT_INVERT_2_ENDPOINTS_X:
case MOVEMENT_INVERT_2_ENDPOINTS_Y:
case MOVEMENT_INVERT_2_ENDPOINTS_Z:
case MOVEMENT_INVERT_MOTOR_X:
case MOVEMENT_INVERT_MOTOR_Y:
case MOVEMENT_INVERT_MOTOR_Z:
case MOVEMENT_SECONDARY_MOTOR_X:
case MOVEMENT_SECONDARY_MOTOR_INVERT_X:
case MOVEMENT_STEPS_ACC_DEC_X:
case MOVEMENT_STEPS_ACC_DEC_Y:
case MOVEMENT_STEPS_ACC_DEC_Z:
case MOVEMENT_STEPS_ACC_DEC_Z2:
case MOVEMENT_STOP_AT_HOME_X:
case MOVEMENT_STOP_AT_HOME_Y:
case MOVEMENT_STOP_AT_HOME_Z:
case MOVEMENT_HOME_UP_X:
case MOVEMENT_HOME_UP_Y:
case MOVEMENT_HOME_UP_Z:
case MOVEMENT_STEP_PER_MM_X:
case MOVEMENT_STEP_PER_MM_Y:
case MOVEMENT_STEP_PER_MM_Z:
case MOVEMENT_MIN_SPD_X:
case MOVEMENT_MIN_SPD_Y:
case MOVEMENT_MIN_SPD_Z:
case MOVEMENT_MIN_SPD_Z2:
case MOVEMENT_HOME_SPEED_X:
case MOVEMENT_HOME_SPEED_Y:
case MOVEMENT_HOME_SPEED_Z:
case MOVEMENT_MAX_SPD_X:
case MOVEMENT_MAX_SPD_Y:
case MOVEMENT_MAX_SPD_Z:
case MOVEMENT_MAX_SPD_Z2:
case MOVEMENT_MOTOR_CURRENT_X:
case MOVEMENT_MOTOR_CURRENT_Y:
case MOVEMENT_MOTOR_CURRENT_Z:
case MOVEMENT_STALL_SENSITIVITY_X:
case MOVEMENT_STALL_SENSITIVITY_Y:
case MOVEMENT_STALL_SENSITIVITY_Z:
case MOVEMENT_MICROSTEPS_X:
case MOVEMENT_MICROSTEPS_Y:
case MOVEMENT_MICROSTEPS_Z:
case ENCODER_ENABLED_X:
case ENCODER_ENABLED_Y:
case ENCODER_ENABLED_Z:
case ENCODER_TYPE_X:
case ENCODER_TYPE_Y:
case ENCODER_TYPE_Z:
case ENCODER_MISSED_STEPS_MAX_X:
case ENCODER_MISSED_STEPS_MAX_Y:
case ENCODER_MISSED_STEPS_MAX_Z:
case ENCODER_SCALING_X:
case ENCODER_SCALING_Y:
case ENCODER_SCALING_Z:
case ENCODER_MISSED_STEPS_DECAY_X:
case ENCODER_MISSED_STEPS_DECAY_Y:
case ENCODER_MISSED_STEPS_DECAY_Z:
case ENCODER_USE_FOR_POS_X:
case ENCODER_USE_FOR_POS_Y:
case ENCODER_USE_FOR_POS_Z:
case ENCODER_INVERT_X:
case ENCODER_INVERT_Y:
case ENCODER_INVERT_Z:
case MOVEMENT_AXIS_NR_STEPS_X:
case MOVEMENT_AXIS_NR_STEPS_Y:
case MOVEMENT_AXIS_NR_STEPS_Z:
case MOVEMENT_STOP_AT_MAX_X:
case MOVEMENT_STOP_AT_MAX_Y:
case MOVEMENT_STOP_AT_MAX_Z:
case MOVEMENT_CALIBRATION_RETRY_X:
case MOVEMENT_CALIBRATION_RETRY_Y:
case MOVEMENT_CALIBRATION_RETRY_Z:
case MOVEMENT_CALIBRATION_RETRY_TOTAL_X:
case MOVEMENT_CALIBRATION_RETRY_TOTAL_Y:
case MOVEMENT_CALIBRATION_RETRY_TOTAL_Z:
case MOVEMENT_AXIS_STEALTH_X:
case MOVEMENT_AXIS_STEALTH_Y:
case MOVEMENT_AXIS_STEALTH_Z:
case MOVEMENT_CALIBRATION_DEADZONE_X:
case MOVEMENT_CALIBRATION_DEADZONE_Y:
case MOVEMENT_CALIBRATION_DEADZONE_Z:
case PIN_GUARD_1_PIN_NR:
case PIN_GUARD_1_TIME_OUT:
case PIN_GUARD_1_ACTIVE_STATE:
case PIN_GUARD_2_PIN_NR:
case PIN_GUARD_2_TIME_OUT:
case PIN_GUARD_2_ACTIVE_STATE:
case PIN_GUARD_3_PIN_NR:
case PIN_GUARD_3_TIME_OUT:
case PIN_GUARD_3_ACTIVE_STATE:
case PIN_GUARD_4_PIN_NR:
case PIN_GUARD_4_TIME_OUT:
case PIN_GUARD_4_ACTIVE_STATE:
case PIN_GUARD_5_PIN_NR:
case PIN_GUARD_5_TIME_OUT:
case PIN_GUARD_5_ACTIVE_STATE:
case PIN_REPORT_1_PIN_NR:
case PIN_REPORT_2_PIN_NR:
return true;
default:
return false;
}
}
|
c22537f18d19fed60f6f7f5cee64228a65a79e04 | afb7006e47e70c1deb2ddb205f06eaf67de3df72 | /security/sandbox/chromium/base/template_util.h | 43bd0c346641028bc24a654594898e8482f329c6 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | marco-c/gecko-dev-wordified | a66383f85db33911b6312dd094c36f88c55d2e2c | 3509ec45ecc9e536d04a3f6a43a82ec09c08dff6 | refs/heads/master | 2023-08-10T16:37:56.660204 | 2023-08-01T00:39:54 | 2023-08-01T00:39:54 | 211,297,590 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,882 | h | template_util.h | /
/
Copyright
(
c
)
2011
The
Chromium
Authors
.
All
rights
reserved
.
/
/
Use
of
this
source
code
is
governed
by
a
BSD
-
style
license
that
can
be
/
/
found
in
the
LICENSE
file
.
#
ifndef
BASE_TEMPLATE_UTIL_H_
#
define
BASE_TEMPLATE_UTIL_H_
#
include
<
stddef
.
h
>
#
include
<
iosfwd
>
#
include
<
iterator
>
#
include
<
type_traits
>
#
include
<
utility
>
#
include
<
vector
>
#
include
"
build
/
build_config
.
h
"
/
/
Some
versions
of
libstdc
+
+
have
partial
support
for
type_traits
but
misses
/
/
a
smaller
subset
while
removing
some
of
the
older
non
-
standard
stuff
.
Assume
/
/
that
all
versions
below
5
.
0
fall
in
this
category
along
with
one
5
.
0
/
/
experimental
release
.
Test
for
this
by
consulting
compiler
major
version
/
/
the
only
reliable
option
available
so
theoretically
this
could
fail
should
/
/
you
attempt
to
mix
an
earlier
version
of
libstdc
+
+
with
>
=
GCC5
.
But
/
/
that
'
s
unlikely
to
work
out
especially
as
GCC5
changed
ABI
.
#
define
CR_GLIBCXX_5_0_0
20150123
#
if
(
defined
(
__GNUC__
)
&
&
__GNUC__
<
5
)
|
|
\
(
defined
(
__GLIBCXX__
)
&
&
__GLIBCXX__
=
=
CR_GLIBCXX_5_0_0
)
#
define
CR_USE_FALLBACKS_FOR_OLD_EXPERIMENTAL_GLIBCXX
#
endif
/
/
This
hacks
around
using
gcc
with
libc
+
+
which
has
some
incompatibilies
.
/
/
-
is_trivially_
*
doesn
'
t
work
:
https
:
/
/
llvm
.
org
/
bugs
/
show_bug
.
cgi
?
id
=
27538
/
/
TODO
(
danakj
)
:
Remove
this
when
android
builders
are
all
using
a
newer
version
/
/
of
gcc
or
the
android
ndk
is
updated
to
a
newer
libc
+
+
that
works
with
older
/
/
gcc
versions
.
#
if
!
defined
(
__clang__
)
&
&
defined
(
_LIBCPP_VERSION
)
#
define
CR_USE_FALLBACKS_FOR_GCC_WITH_LIBCXX
#
endif
namespace
base
{
template
<
class
T
>
struct
is_non_const_reference
:
std
:
:
false_type
{
}
;
template
<
class
T
>
struct
is_non_const_reference
<
T
&
>
:
std
:
:
true_type
{
}
;
template
<
class
T
>
struct
is_non_const_reference
<
const
T
&
>
:
std
:
:
false_type
{
}
;
namespace
internal
{
/
/
Implementation
detail
of
base
:
:
void_t
below
.
template
<
typename
.
.
.
>
struct
make_void
{
using
type
=
void
;
}
;
}
/
/
namespace
internal
/
/
base
:
:
void_t
is
an
implementation
of
std
:
:
void_t
from
C
+
+
17
.
/
/
/
/
We
use
|
base
:
:
internal
:
:
make_void
|
as
a
helper
struct
to
avoid
a
C
+
+
14
/
/
defect
:
/
/
http
:
/
/
en
.
cppreference
.
com
/
w
/
cpp
/
types
/
void_t
/
/
http
:
/
/
open
-
std
.
org
/
JTC1
/
SC22
/
WG21
/
docs
/
cwg_defects
.
html
#
1558
template
<
typename
.
.
.
Ts
>
using
void_t
=
typename
:
:
base
:
:
internal
:
:
make_void
<
Ts
.
.
.
>
:
:
type
;
namespace
internal
{
/
/
Uses
expression
SFINAE
to
detect
whether
using
operator
<
<
would
work
.
template
<
typename
T
typename
=
void
>
struct
SupportsOstreamOperator
:
std
:
:
false_type
{
}
;
template
<
typename
T
>
struct
SupportsOstreamOperator
<
T
decltype
(
void
(
std
:
:
declval
<
std
:
:
ostream
&
>
(
)
<
<
std
:
:
declval
<
T
>
(
)
)
)
>
:
std
:
:
true_type
{
}
;
template
<
typename
T
typename
=
void
>
struct
SupportsToString
:
std
:
:
false_type
{
}
;
template
<
typename
T
>
struct
SupportsToString
<
T
decltype
(
void
(
std
:
:
declval
<
T
>
(
)
.
ToString
(
)
)
)
>
:
std
:
:
true_type
{
}
;
/
/
Used
to
detech
whether
the
given
type
is
an
iterator
.
This
is
normally
used
/
/
with
std
:
:
enable_if
to
provide
disambiguation
for
functions
that
take
/
/
templatzed
iterators
as
input
.
template
<
typename
T
typename
=
void
>
struct
is_iterator
:
std
:
:
false_type
{
}
;
template
<
typename
T
>
struct
is_iterator
<
T
void_t
<
typename
std
:
:
iterator_traits
<
T
>
:
:
iterator_category
>
>
:
std
:
:
true_type
{
}
;
}
/
/
namespace
internal
/
/
is_trivially_copyable
is
especially
hard
to
get
right
.
/
/
-
Older
versions
of
libstdc
+
+
will
fail
to
have
it
like
they
do
for
other
/
/
type
traits
.
This
has
become
a
subset
of
the
second
point
but
used
to
be
/
/
handled
independently
.
/
/
-
An
experimental
release
of
gcc
includes
most
of
type_traits
but
misses
/
/
is_trivially_copyable
so
we
still
have
to
avoid
using
libstdc
+
+
in
this
/
/
case
which
is
covered
by
CR_USE_FALLBACKS_FOR_OLD_EXPERIMENTAL_GLIBCXX
.
/
/
-
When
compiling
libc
+
+
from
before
r239653
with
a
gcc
compiler
the
/
/
std
:
:
is_trivially_copyable
can
fail
.
So
we
need
to
work
around
that
by
not
/
/
using
the
one
in
libc
+
+
in
this
case
.
This
is
covered
by
the
/
/
CR_USE_FALLBACKS_FOR_GCC_WITH_LIBCXX
define
and
is
discussed
in
/
/
https
:
/
/
llvm
.
org
/
bugs
/
show_bug
.
cgi
?
id
=
27538
#
c1
where
they
point
out
that
/
/
in
libc
+
+
'
s
commit
r239653
this
is
fixed
by
libc
+
+
checking
for
gcc
5
.
1
.
/
/
-
In
both
of
the
above
cases
we
are
using
the
gcc
compiler
.
When
defining
/
/
this
ourselves
on
compiler
intrinsics
the
__is_trivially_copyable
(
)
/
/
intrinsic
is
not
available
on
gcc
before
version
5
.
1
(
see
the
discussion
in
/
/
https
:
/
/
llvm
.
org
/
bugs
/
show_bug
.
cgi
?
id
=
27538
#
c1
again
)
so
we
must
check
for
/
/
that
version
.
/
/
-
When
__is_trivially_copyable
(
)
is
not
available
because
we
are
on
gcc
older
/
/
than
5
.
1
we
need
to
fall
back
to
something
so
we
use
__has_trivial_copy
(
)
/
/
instead
based
on
what
was
done
one
-
off
in
bit_cast
(
)
previously
.
/
/
TODO
(
crbug
.
com
/
554293
)
:
Remove
this
when
all
platforms
have
this
in
the
std
/
/
namespace
and
it
works
with
gcc
as
needed
.
#
if
defined
(
CR_USE_FALLBACKS_FOR_OLD_EXPERIMENTAL_GLIBCXX
)
|
|
\
defined
(
CR_USE_FALLBACKS_FOR_GCC_WITH_LIBCXX
)
template
<
typename
T
>
struct
is_trivially_copyable
{
/
/
TODO
(
danakj
)
:
Remove
this
when
android
builders
are
all
using
a
newer
version
/
/
of
gcc
or
the
android
ndk
is
updated
to
a
newer
libc
+
+
that
does
this
for
/
/
us
.
#
if
_GNUC_VER
>
=
501
static
constexpr
bool
value
=
__is_trivially_copyable
(
T
)
;
#
else
static
constexpr
bool
value
=
__has_trivial_copy
(
T
)
&
&
__has_trivial_destructor
(
T
)
;
#
endif
}
;
#
else
template
<
class
T
>
using
is_trivially_copyable
=
std
:
:
is_trivially_copyable
<
T
>
;
#
endif
#
if
defined
(
__GNUC__
)
&
&
!
defined
(
__clang__
)
&
&
__GNUC__
<
=
7
/
/
Workaround
for
g
+
+
7
and
earlier
family
.
/
/
Due
to
https
:
/
/
gcc
.
gnu
.
org
/
bugzilla
/
show_bug
.
cgi
?
id
=
80654
without
this
/
/
Optional
<
std
:
:
vector
<
T
>
>
where
T
is
non
-
copyable
causes
a
compile
error
.
/
/
As
we
know
it
is
not
trivially
copy
constructible
explicitly
declare
so
.
template
<
typename
T
>
struct
is_trivially_copy_constructible
:
std
:
:
is_trivially_copy_constructible
<
T
>
{
}
;
template
<
typename
.
.
.
T
>
struct
is_trivially_copy_constructible
<
std
:
:
vector
<
T
.
.
.
>
>
:
std
:
:
false_type
{
}
;
#
else
/
/
Otherwise
use
std
:
:
is_trivially_copy_constructible
as
is
.
template
<
typename
T
>
using
is_trivially_copy_constructible
=
std
:
:
is_trivially_copy_constructible
<
T
>
;
#
endif
/
/
base
:
:
in_place_t
is
an
implementation
of
std
:
:
in_place_t
from
/
/
C
+
+
17
.
A
tag
type
used
to
request
in
-
place
construction
in
template
vararg
/
/
constructors
.
/
/
Specification
:
/
/
https
:
/
/
en
.
cppreference
.
com
/
w
/
cpp
/
utility
/
in_place
struct
in_place_t
{
}
;
constexpr
in_place_t
in_place
=
{
}
;
/
/
base
:
:
in_place_type_t
is
an
implementation
of
std
:
:
in_place_type_t
from
/
/
C
+
+
17
.
A
tag
type
used
for
in
-
place
construction
when
the
type
to
construct
/
/
needs
to
be
specified
such
as
with
base
:
:
unique_any
designed
to
be
a
/
/
drop
-
in
replacement
.
/
/
Specification
:
/
/
http
:
/
/
en
.
cppreference
.
com
/
w
/
cpp
/
utility
/
in_place
template
<
typename
T
>
struct
in_place_type_t
{
}
;
template
<
typename
T
>
struct
is_in_place_type_t
{
static
constexpr
bool
value
=
false
;
}
;
template
<
typename
.
.
.
Ts
>
struct
is_in_place_type_t
<
in_place_type_t
<
Ts
.
.
.
>
>
{
static
constexpr
bool
value
=
true
;
}
;
}
/
/
namespace
base
#
undef
CR_USE_FALLBACKS_FOR_GCC_WITH_LIBCXX
#
undef
CR_USE_FALLBACKS_FOR_OLD_EXPERIMENTAL_GLIBCXX
#
endif
/
/
BASE_TEMPLATE_UTIL_H_
|
58063c13af0396ffae741f7d83392ce6d6a2638b | fcc3fee8c22a3ce5eaaaae2ffcd60b298c1a0d6b | /Firebase code.ino | 7207eed5a1315b2e68b412f33d285d3daaf7ea7e | [] | no_license | hmiche/MasterBDIOT | 352e97629cbca13e72e56d5c7f0c5099e837237a | 667dcb162ada3280fa72ad420470db55d9c0b5f2 | refs/heads/main | 2023-06-09T02:02:38.801989 | 2021-06-30T00:21:42 | 2021-06-30T00:21:42 | 381,529,545 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,510 | ino | Firebase code.ino |
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include <SPI.h>
#include <MFRC522.h>
// Set these to run example.
#define SS_PIN D4 //D2
#define RST_PIN D0 //D1
#define FIREBASE_HOST "gestion-absence-cdb21-default-rtdb.firebaseio.com" //https://wemos4firebase.firebaseio.com/
#define FIREBASE_AUTH "AKs7Eh4GolvUHym7ExQFM0QZZnGjHUzoGSIzK8tw"
#define WIFI_SSID "ESP1"
#define WIFI_PASSWORD "12345678"
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance/object.
int variable = 0;
void setup() {
Serial.begin(9600); // Initiate a serial communication
SPI.begin(); // Initiate SPI bus
mfrc522.PCD_Init(); // Initiate MFRC522
Serial.println("Show your card:");
// connect to wifi.
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
Serial.print("connected: ");
Serial.println(WiFi.localIP());
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}
void loop() {
int n = 0;
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
//Show UID on serial monitor
Serial.println();
String content= "";
byte letter;
content =printString(mfrc522.uid.uidByte, mfrc522.uid.size);
Firebase.pushString("ID",content);
//Serial.print("pushed: /logs/(mfrc522.uid.uidByte[s])");
if (Firebase.failed()) {
Serial.print("setting /number2 failed:");
Serial.println(Firebase.error());
return;
}
delay(1000);
// update value
Firebase.setFloat("number", 43.0);
// handle error
if (Firebase.failed()) {
Serial.print("setting /number1 failed:");
Serial.println(Firebase.error());
return;
}
delay(1000);
// get value
Serial.print("number: ");
Serial.println(Firebase.getFloat("number"));
delay(1000);
// remove value
Firebase.remove("number");
delay(1000);
// set string value
Firebase.setString("message", "hello world");
// handle error
if (Firebase.failed()) {
Serial.print("setting /message failed:");
Serial.println(Firebase.error());
return;
}
delay(1000);
// set bool value
Firebase.setBool("truth", false);
// handle error
if (Firebase.failed()) {
Serial.print("setting /truth failed:");
Serial.println(Firebase.error());
return;
}
delay(1000);
// append a new value to /logs
// handle error
delay(1000);
}
void printDec(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], DEC);
}
}
String printString(byte *buffer, byte bufferSize) {
String rfid_uid = "";
for (byte i = 0; i < bufferSize; i++) {
String uid_part = String(buffer[i], HEX);
Serial.print(uid_part);
rfid_uid += uid_part;
}
return rfid_uid;
}
////////////////////////////////////////////////////////////
client.println("Ana hna");
// Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
if ( ! rfid.PICC_IsNewCardPresent())
return;
// Verify if the NUID has been readed
if ( ! rfid.PICC_ReadCardSerial())
return;
/////////////////esp |
fb77e7c21ad6bc91689c6c03266e69ac5e35b496 | 3f3095dbf94522e37fe897381d9c76ceb67c8e4f | /Current/BP_CleanupPod_Beacon.hpp | 90f6979e8d0217a1fb2502946531a568bfcf1887 | [] | no_license | DRG-Modding/Header-Dumps | 763c7195b9fb24a108d7d933193838d736f9f494 | 84932dc1491811e9872b1de4f92759616f9fa565 | refs/heads/main | 2023-06-25T11:11:10.298500 | 2023-06-20T13:52:18 | 2023-06-20T13:52:18 | 399,652,576 | 8 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 359 | hpp | BP_CleanupPod_Beacon.hpp | #ifndef UE4SS_SDK_BP_CleanupPod_Beacon_HPP
#define UE4SS_SDK_BP_CleanupPod_Beacon_HPP
class ABP_CleanupPod_Beacon_C : public ABP_SupplyPod_Beacon_C
{
FPointerToUberGraphFrame UberGraphFrame;
class UTerrainPlacementComponent* terrainPlacement;
void ReceiveBeginPlay();
void ExecuteUbergraph_BP_CleanupPod_Beacon(int32 EntryPoint);
};
#endif
|
208779ba69f67fbb7c8af821c729192f2fadaa62 | 02e5ce9efeadd040f7489a5a72b4c7e521018b92 | /cuCareQtApp/CUCare/moc_patientlistview.cpp | 317357a967cab33f3d51446cdd462ac67b94477f | [] | no_license | chrispwright/comp3004cuCarePrivate | 73545a4ce08bd0608cd6d56525243dca584281fc | 14f3a822555ed0d025047d25cee56ffce4673c93 | refs/heads/master | 2021-01-20T12:04:07.118828 | 2012-12-02T06:51:00 | 2012-12-02T06:51:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,749 | cpp | moc_patientlistview.cpp | /****************************************************************************
** Meta object code from reading C++ file 'patientlistview.h'
**
** Created: Sun Dec 2 01:23:37 2012
** by: The Qt Meta Object Compiler version 63 (Qt 4.8.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "patientlistview.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'patientlistview.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_PatientListView[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
10, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
17, 16, 16, 16, 0x0a,
43, 16, 16, 16, 0x0a,
61, 57, 16, 16, 0x0a,
98, 57, 16, 16, 0x0a,
140, 57, 16, 16, 0x0a,
178, 16, 16, 16, 0x0a,
210, 16, 16, 16, 0x0a,
255, 246, 16, 16, 0x08,
305, 291, 16, 16, 0x08,
361, 351, 16, 16, 0x08,
0 // eod
};
static const char qt_meta_stringdata_PatientListView[] = {
"PatientListView\0\0setupPhysiciansComboBox()\0"
"setupTables()\0,,,\0"
"patientTableClicked(int,int,int,int)\0"
"consultationTableClicked(int,int,int,int)\0"
"followUpTableClicked(int,int,int,int)\0"
"filterByStatusComboChanged(int)\0"
"filterByPhysiciansComboChanged(int)\0"
"patients\0loadPatientTable(QVector<Patient*>)\0"
"consultations\0"
"loadConsultationTable(QVector<Consultation*>)\0"
"followUps\0loadFollowUpTable(QVector<FollowUp*>)\0"
};
void PatientListView::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
PatientListView *_t = static_cast<PatientListView *>(_o);
switch (_id) {
case 0: _t->setupPhysiciansComboBox(); break;
case 1: _t->setupTables(); break;
case 2: _t->patientTableClicked((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< int(*)>(_a[4]))); break;
case 3: _t->consultationTableClicked((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< int(*)>(_a[4]))); break;
case 4: _t->followUpTableClicked((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< int(*)>(_a[4]))); break;
case 5: _t->filterByStatusComboChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 6: _t->filterByPhysiciansComboChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 7: _t->loadPatientTable((*reinterpret_cast< QVector<Patient*>(*)>(_a[1]))); break;
case 8: _t->loadConsultationTable((*reinterpret_cast< QVector<Consultation*>(*)>(_a[1]))); break;
case 9: _t->loadFollowUpTable((*reinterpret_cast< QVector<FollowUp*>(*)>(_a[1]))); break;
default: ;
}
}
}
const QMetaObjectExtraData PatientListView::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject PatientListView::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_PatientListView,
qt_meta_data_PatientListView, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &PatientListView::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *PatientListView::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *PatientListView::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_PatientListView))
return static_cast<void*>(const_cast< PatientListView*>(this));
return QDialog::qt_metacast(_clname);
}
int PatientListView::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 10)
qt_static_metacall(this, _c, _id, _a);
_id -= 10;
}
return _id;
}
QT_END_MOC_NAMESPACE
|
15eaa18effa6a7fb1e8e72dd2cf84047dc13f166 | 851d12adffa6dcdc85816c2ee6f6af129c5542b6 | /TDEngine2/plugins/OGLGraphicsContext/source/COGLMappings.cpp | b05f5d3d5b79908102f23edb5178f37af4ddc18f | [
"Apache-2.0"
] | permissive | bnoazx005/TDEngine2 | 775c018e1aebfe4a42f727e132780e52a80f6a96 | ecc1683aac5df5b1581a56b6d240893f5c79161b | refs/heads/master | 2023-08-31T08:07:19.288783 | 2022-05-12T16:41:06 | 2022-05-12T16:45:02 | 149,013,665 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 16,862 | cpp | COGLMappings.cpp | #include "./../include/COGLMappings.h"
namespace TDEngine2
{
GLenum COGLMappings::GetUsageType(E_BUFFER_USAGE_TYPE type)
{
if (type == BUT_DYNAMIC)
{
return GL_DYNAMIC_DRAW;
}
return GL_STATIC_DRAW;
}
GLenum COGLMappings::GetBufferMapAccessType(E_BUFFER_MAP_TYPE type)
{
switch (type)
{
case BMT_READ:
return GL_READ_ONLY;
case BMT_READ_WRITE:
return GL_READ_WRITE;
case BMT_WRITE:
return GL_WRITE_ONLY;
}
return GL_WRITE_ONLY;
}
GLint COGLMappings::GetInternalFormat(E_FORMAT_TYPE format)
{
switch (format)
{
case FT_FLOAT1:
case FT_FLOAT1_TYPELESS:
return GL_R32F;
case FT_FLOAT2:
case FT_FLOAT2_TYPELESS:
return GL_RG32F;
case FT_FLOAT3:
case FT_FLOAT3_TYPELESS:
return GL_RGB32F;
case FT_FLOAT4:
case FT_FLOAT4_TYPELESS:
return GL_RGBA32F;
case FT_NORM_BYTE1:
case FT_BYTE1:
return GL_R8_SNORM;
case FT_NORM_BYTE2:
case FT_BYTE2:
return GL_RG8_SNORM;
case FT_NORM_BYTE4:
case FT_BYTE4:
return GL_RGBA8_SNORM;
case FT_NORM_UBYTE1:
case FT_UBYTE1:
return GL_R8;
case FT_NORM_UBYTE2:
case FT_UBYTE2:
return GL_RG8;
case FT_NORM_UBYTE4:
case FT_UBYTE4:
case FT_UBYTE4_BGRA_UNORM:
return GL_RGBA8;
case FT_NORM_SHORT1:
case FT_SHORT1:
return GL_R16_SNORM;
case FT_NORM_SHORT2:
case FT_SHORT2:
return GL_RG16_SNORM;
case FT_NORM_SHORT4:
case FT_SHORT4:
return GL_RGBA16_SNORM;
case FT_NORM_USHORT1:
case FT_USHORT1:
return GL_R16;
case FT_NORM_USHORT2:
case FT_USHORT2:
return GL_RG16;
case FT_NORM_USHORT4:
case FT_USHORT4:
return GL_RGBA16;
case FT_UINT1:
return GL_R32UI;
case FT_UINT2:
return GL_RG32UI;
case FT_UINT3:
return GL_RGB32UI;
case FT_UINT4:
return GL_RGBA32UI;
case FT_SINT1:
return GL_R32I;
case FT_SINT2:
return GL_RGB32I;
case FT_SINT3:
return GL_RGB32I;
case FT_SINT4:
return GL_RGBA32I;
case FT_D32:
return GL_DEPTH_COMPONENT;
}
return 0;
}
GLenum COGLMappings::GetPixelDataFormat(E_FORMAT_TYPE format)
{
switch (format)
{
case FT_FLOAT1:
case FT_FLOAT1_TYPELESS:
case FT_D32:
return GL_DEPTH_COMPONENT;
case FT_NORM_BYTE1:
case FT_NORM_UBYTE1:
case FT_NORM_SHORT1:
case FT_NORM_USHORT1:
return GL_RED;
case FT_BYTE1:
case FT_UBYTE1:
case FT_SHORT1:
case FT_USHORT1:
case FT_UINT1:
case FT_SINT1:
return GL_RED_INTEGER;
case FT_NORM_BYTE2:
case FT_BYTE2:
case FT_FLOAT2:
case FT_FLOAT2_TYPELESS:
case FT_NORM_UBYTE2:
case FT_UBYTE2:
case FT_NORM_SHORT2:
case FT_SHORT2:
case FT_NORM_USHORT2:
case FT_USHORT2:
case FT_UINT2:
case FT_SINT2:
return GL_RG;
case FT_FLOAT3:
case FT_FLOAT3_TYPELESS:
case FT_UINT3:
case FT_SINT3:
return GL_RGB;
case FT_FLOAT4:
case FT_FLOAT4_TYPELESS:
case FT_NORM_UBYTE4:
case FT_UBYTE4:
case FT_NORM_BYTE4:
case FT_BYTE4:
case FT_NORM_SHORT4:
case FT_SHORT4:
case FT_NORM_USHORT4:
case FT_USHORT4:
case FT_UINT4:
case FT_SINT4:
return GL_RGBA;
case FT_UBYTE4_BGRA_UNORM:
return GL_BGRA;
}
return GL_DEPTH_STENCIL;
}
GLenum COGLMappings::GetShaderStageType(E_SHADER_STAGE_TYPE shaderStageType)
{
switch (shaderStageType)
{
case SST_VERTEX:
return GL_VERTEX_SHADER;
case SST_PIXEL:
return GL_FRAGMENT_SHADER;
case SST_GEOMETRY:
return GL_GEOMETRY_SHADER;
}
return 0;
}
U32 COGLMappings::GetNumOfChannelsOfFormat(E_FORMAT_TYPE format)
{
switch (format)
{
case FT_BYTE1:
case FT_NORM_BYTE1:
case FT_UBYTE1:
case FT_NORM_UBYTE1:
case FT_FLOAT1:
case FT_D32:
case FT_SHORT1:
case FT_NORM_SHORT1:
case FT_USHORT1:
case FT_NORM_USHORT1:
case FT_UINT1:
case FT_NORM_UINT1:
case FT_SINT1:
case FT_NORM_SINT1:
return 1;
case FT_BYTE2:
case FT_NORM_BYTE2:
case FT_UBYTE2:
case FT_NORM_UBYTE2:
case FT_FLOAT2:
case FT_FLOAT2_TYPELESS:
case FT_SHORT2:
case FT_NORM_SHORT2:
case FT_USHORT2:
case FT_NORM_USHORT2:
case FT_UINT2:
case FT_NORM_UINT2:
case FT_SINT2:
case FT_NORM_SINT2:
return 2;
case FT_BYTE3:
case FT_NORM_BYTE3:
case FT_UBYTE3:
case FT_NORM_UBYTE3:
case FT_FLOAT3:
case FT_FLOAT3_TYPELESS:
case FT_SHORT3:
case FT_NORM_SHORT3:
case FT_USHORT3:
case FT_NORM_USHORT3:
case FT_UINT3:
case FT_NORM_UINT3:
case FT_SINT3:
case FT_NORM_SINT3:
return 3;
case FT_BYTE4:
case FT_NORM_BYTE4:
case FT_UBYTE4:
case FT_NORM_UBYTE4:
case FT_NORM_BYTE4_SRGB:
case FT_UBYTE4_BGRA_UNORM:
case FT_SHORT4:
case FT_NORM_SHORT4:
case FT_SINT4:
case FT_NORM_SINT4:
case FT_UINT4:
case FT_NORM_UINT4:
case FT_USHORT4:
case FT_NORM_USHORT4:
case FT_FLOAT4:
case FT_FLOAT4_TYPELESS:
return 4;
}
return 0;
}
GLenum COGLMappings::GetBaseTypeOfFormat(E_FORMAT_TYPE format)
{
switch (format)
{
case FT_NORM_BYTE1:
case FT_BYTE1:
case FT_NORM_BYTE2:
case FT_BYTE2:
case FT_NORM_BYTE4:
case FT_BYTE4:
return GL_BYTE;
case FT_NORM_UBYTE1:
case FT_UBYTE1:
case FT_NORM_UBYTE2:
case FT_UBYTE2:
case FT_NORM_UBYTE4:
case FT_UBYTE4:
case FT_UBYTE4_BGRA_UNORM:
return GL_UNSIGNED_BYTE;
case FT_NORM_SHORT1:
case FT_SHORT1:
case FT_NORM_SHORT2:
case FT_SHORT2:
case FT_NORM_SHORT4:
case FT_SHORT4:
return GL_SHORT;
case FT_NORM_USHORT1:
case FT_USHORT1:
case FT_NORM_USHORT2:
case FT_USHORT2:
case FT_NORM_USHORT4:
case FT_USHORT4:
return GL_UNSIGNED_SHORT;
case FT_UINT1:
case FT_UINT2:
case FT_UINT3:
case FT_UINT4:
return GL_UNSIGNED_INT;
case FT_SINT1:
case FT_SINT2:
case FT_SINT3:
case FT_SINT4:
return GL_INT;
}
return GL_FLOAT;
}
GLsizei COGLMappings::GetFormatSize(E_FORMAT_TYPE format)
{
switch (format)
{
case FT_BYTE1:
case FT_NORM_BYTE1:
return sizeof(char);
case FT_BYTE2:
case FT_NORM_BYTE2:
return 2 * sizeof(char);
case FT_BYTE3:
case FT_NORM_BYTE3:
return 3 * sizeof(char);
case FT_BYTE4:
case FT_NORM_BYTE4:
return 4 * sizeof(char);
case FT_UBYTE1:
case FT_NORM_UBYTE1:
return sizeof(unsigned char);
case FT_UBYTE2:
case FT_NORM_UBYTE2:
return 2 * sizeof(unsigned char);
case FT_UBYTE3:
case FT_NORM_UBYTE3:
return 3 * sizeof(unsigned char);
case FT_UBYTE4:
case FT_NORM_UBYTE4:
case FT_NORM_BYTE4_SRGB:
case FT_UBYTE4_BGRA_UNORM:
return 4 * sizeof(unsigned char);
case FT_FLOAT1:
case FT_D32:
return sizeof(float);
case FT_FLOAT2:
case FT_FLOAT2_TYPELESS:
return 2 * sizeof(float);
case FT_FLOAT3:
case FT_FLOAT3_TYPELESS:
return 3 * sizeof(float);
case FT_FLOAT4:
case FT_FLOAT4_TYPELESS:
return 4 * sizeof(float);
case FT_SHORT1:
case FT_NORM_SHORT1:
return 1 * sizeof(short);
case FT_SHORT2:
case FT_NORM_SHORT2:
return 2 * sizeof(short);
case FT_SHORT3:
case FT_NORM_SHORT3:
return 3 * sizeof(short);
case FT_SHORT4:
case FT_NORM_SHORT4:
return 4 * sizeof(short);
case FT_USHORT1:
case FT_NORM_USHORT1:
return 1 * sizeof(short);
case FT_USHORT2:
case FT_NORM_USHORT2:
return 2 * sizeof(short);
case FT_USHORT3:
case FT_NORM_USHORT3:
return 3 * sizeof(short);
case FT_USHORT4:
case FT_NORM_USHORT4:
return 4 * sizeof(short);
case FT_UINT1:
case FT_NORM_UINT1:
return 1 * sizeof(int);
case FT_UINT2:
case FT_NORM_UINT2:
return 2 * sizeof(int);
case FT_UINT3:
case FT_NORM_UINT3:
return 3 * sizeof(int);
case FT_UINT4:
case FT_NORM_UINT4:
return 4 * sizeof(int);
case FT_SINT1:
case FT_NORM_SINT1:
return 1 * sizeof(int);
case FT_SINT2:
case FT_NORM_SINT2:
return 2 * sizeof(int);
case FT_SINT3:
case FT_NORM_SINT3:
return 3 * sizeof(int);
case FT_SINT4:
case FT_NORM_SINT4:
return 4 * sizeof(int);
}
return 0;
}
GLint COGLMappings::GetTypeSize(GLenum type)
{
switch (type)
{
case GL_FLOAT:
return sizeof(F32);
case GL_FLOAT_VEC2:
return sizeof(F32) * 2;
case GL_FLOAT_VEC3:
return sizeof(F32) * 3;
case GL_FLOAT_VEC4:
return sizeof(F32) * 4;
case GL_DOUBLE:
return sizeof(F64);
case GL_DOUBLE_VEC2:
return sizeof(F64) * 2;
case GL_DOUBLE_VEC3:
return sizeof(F64) * 3;
case GL_DOUBLE_VEC4:
return sizeof(F64) * 4;
case GL_INT:
return sizeof(I32);
case GL_INT_VEC2:
return sizeof(I32) * 2;
case GL_INT_VEC3:
return sizeof(I32) * 3;
case GL_INT_VEC4:
return sizeof(I32) * 4;
case GL_UNSIGNED_INT:
return sizeof(U32);
case GL_UNSIGNED_INT_VEC2:
return sizeof(U32) * 2;
case GL_UNSIGNED_INT_VEC3:
return sizeof(U32) * 3;
case GL_UNSIGNED_INT_VEC4:
return sizeof(U32) * 4;
case GL_BOOL:
return sizeof(bool);
case GL_BOOL_VEC2:
return sizeof(bool) * 2;
case GL_BOOL_VEC3:
return sizeof(bool) * 3;
case GL_BOOL_VEC4:
return sizeof(bool) * 4;
case GL_FLOAT_MAT2:
return sizeof(F32) * 4;
case GL_FLOAT_MAT3:
return sizeof(F32) * 9;
case GL_FLOAT_MAT4:
return sizeof(F32) * 16;
case GL_FLOAT_MAT2x3:
case GL_FLOAT_MAT3x2:
return sizeof(F32) * 6;
case GL_FLOAT_MAT4x2:
case GL_FLOAT_MAT2x4:
return sizeof(F32) * 8;
case GL_FLOAT_MAT4x3:
case GL_FLOAT_MAT3x4:
return sizeof(F32) * 12;
case GL_DOUBLE_MAT2:
return sizeof(F64) * 9;
case GL_DOUBLE_MAT3:
return sizeof(F64) * 9;
case GL_DOUBLE_MAT4:
return sizeof(F64) * 9;
case GL_DOUBLE_MAT2x3:
case GL_DOUBLE_MAT3x2:
return sizeof(F64) * 6;
case GL_DOUBLE_MAT2x4:
case GL_DOUBLE_MAT4x2:
return sizeof(F64) * 8;
case GL_DOUBLE_MAT3x4:
case GL_DOUBLE_MAT4x3:
return sizeof(F64) * 12;
}
TDE2_UNREACHABLE();
return 0;
}
bool COGLMappings::IsFormatNormalized(E_FORMAT_TYPE format)
{
switch (format)
{
case FT_NORM_BYTE1:
case FT_NORM_BYTE2:
case FT_NORM_BYTE4:
case FT_NORM_UBYTE1:
case FT_NORM_UBYTE2:
case FT_NORM_UBYTE4:
case FT_UBYTE4_BGRA_UNORM:
case FT_NORM_SHORT1:
case FT_NORM_SHORT2:
case FT_NORM_SHORT4:
case FT_NORM_USHORT1:
case FT_NORM_USHORT2:
case FT_NORM_USHORT4:
case FT_D32:
return true;
}
return false;
}
GLenum COGLMappings::GetPrimitiveTopology(E_PRIMITIVE_TOPOLOGY_TYPE topologyType)
{
switch (topologyType)
{
case E_PRIMITIVE_TOPOLOGY_TYPE::PTT_POINT_LIST:
return GL_POINTS;
case E_PRIMITIVE_TOPOLOGY_TYPE::PTT_LINE_LIST:
return GL_LINES;
case E_PRIMITIVE_TOPOLOGY_TYPE::PTT_TRIANGLE_LIST:
return GL_TRIANGLES;
case E_PRIMITIVE_TOPOLOGY_TYPE::PTT_TRIANGLE_STRIP:
return GL_TRIANGLE_STRIP;
case E_PRIMITIVE_TOPOLOGY_TYPE::PTT_TRIANGLE_FAN:
return GL_TRIANGLE_FAN;
}
return GL_TRIANGLES;
}
GLenum COGLMappings::GetIndexFormat(E_INDEX_FORMAT_TYPE indexFormatType)
{
switch (indexFormatType)
{
case IFT_INDEX16:
return GL_UNSIGNED_SHORT;
case IFT_INDEX32:
return GL_UNSIGNED_INT;
}
return 0;
}
GLint COGLMappings::GetMinFilterType(E_TEXTURE_FILTER_TYPE filterValue, bool useMipMaps)
{
switch (filterValue)
{
case E_TEXTURE_FILTER_TYPE::FT_POINT:
return useMipMaps ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST;
case E_TEXTURE_FILTER_TYPE::FT_BILINEAR:
return useMipMaps ? GL_NEAREST_MIPMAP_LINEAR : GL_LINEAR;
case E_TEXTURE_FILTER_TYPE::FT_TRILINEAR:
return GL_LINEAR_MIPMAP_LINEAR;
case E_TEXTURE_FILTER_TYPE::FT_ANISOTROPIC:
return GL_LINEAR_MIPMAP_LINEAR;
}
return GL_NEAREST;
}
GLint COGLMappings::GetMagFilterType(E_TEXTURE_FILTER_TYPE filterValue)
{
switch (filterValue)
{
case E_TEXTURE_FILTER_TYPE::FT_POINT:
return GL_NEAREST;
case E_TEXTURE_FILTER_TYPE::FT_BILINEAR:
case E_TEXTURE_FILTER_TYPE::FT_TRILINEAR:
return GL_LINEAR;
case E_TEXTURE_FILTER_TYPE::FT_ANISOTROPIC:
TDE2_UNIMPLEMENTED();
return 0;
}
return GL_NEAREST;
}
GLint COGLMappings::GetTextureAddressMode(E_ADDRESS_MODE_TYPE addressMode)
{
switch (addressMode)
{
case E_ADDRESS_MODE_TYPE::AMT_BORDER:
return GL_CLAMP_TO_BORDER;
case E_ADDRESS_MODE_TYPE::AMT_CLAMP:
return GL_CLAMP_TO_EDGE;
case E_ADDRESS_MODE_TYPE::AMT_MIRROR:
return GL_MIRRORED_REPEAT;
case E_ADDRESS_MODE_TYPE::AMT_WRAP:
return GL_REPEAT;
}
return GL_REPEAT;
}
E_RESULT_CODE COGLMappings::GetErrorCode(GLenum error)
{
switch (error)
{
case GL_INVALID_ENUM:
return RC_INVALID_ARGS;
case GL_INVALID_VALUE:
return RC_INVALID_ARGS;
case GL_OUT_OF_MEMORY:
return RC_OUT_OF_MEMORY;
case GL_INVALID_OPERATION:
case GL_STACK_OVERFLOW:
case GL_STACK_UNDERFLOW:
case GL_INVALID_FRAMEBUFFER_OPERATION:
case GL_CONTEXT_LOST:
return RC_FAIL;
case GL_NO_ERROR:
return RC_OK;
}
return RC_OK;
}
std::string COGLMappings::ErrorCodeToString(GLenum error)
{
switch (error)
{
case GL_INVALID_ENUM:
return "GL_INVALID_ENUM";
case GL_INVALID_VALUE:
return "GL_INVALID_VALUE";
case GL_OUT_OF_MEMORY:
return "GL_OUT_OF_MEMORY";
case GL_INVALID_OPERATION:
return "GL_INVALID_OPERATION";
case GL_STACK_UNDERFLOW:
return "GL_STACK_UNDERFLOW";
case GL_INVALID_FRAMEBUFFER_OPERATION:
return "GL_INVALID_FRAMEBUFFER_OPERATION";
case GL_CONTEXT_LOST:
return "GL_CONTEXT_LOST";
case GL_NO_ERROR:
return "GL_NO_ERROR";
}
return "";
}
GLenum COGLMappings::GetBlendFactorValue(E_BLEND_FACTOR_VALUE factor)
{
switch (factor)
{
case E_BLEND_FACTOR_VALUE::ZERO:
return GL_ZERO;
case E_BLEND_FACTOR_VALUE::ONE:
return GL_ONE;
case E_BLEND_FACTOR_VALUE::SOURCE_ALPHA:
return GL_SRC_ALPHA;
case E_BLEND_FACTOR_VALUE::ONE_MINUS_SOURCE_ALPHA:
return GL_ONE_MINUS_SRC_ALPHA;
case E_BLEND_FACTOR_VALUE::DEST_ALPHA:
return GL_DST_ALPHA;
case E_BLEND_FACTOR_VALUE::ONE_MINUS_DEST_ALPHA:
return GL_ONE_MINUS_DST_ALPHA;
case E_BLEND_FACTOR_VALUE::CONSTANT_ALPHA:
return GL_CONSTANT_ALPHA;
case E_BLEND_FACTOR_VALUE::ONE_MINUS_CONSTANT_ALPHA:
return GL_ONE_MINUS_CONSTANT_ALPHA;
case E_BLEND_FACTOR_VALUE::SOURCE_COLOR:
return GL_SRC_COLOR;
case E_BLEND_FACTOR_VALUE::ONE_MINUS_SOURCE_COLOR:
return GL_ONE_MINUS_SRC_COLOR;
case E_BLEND_FACTOR_VALUE::DEST_COLOR:
return GL_DST_COLOR;
case E_BLEND_FACTOR_VALUE::ONE_MINUS_DEST_COLOR:
return GL_ONE_MINUS_DST_COLOR;
}
return GL_ZERO;
}
GLenum COGLMappings::GetBlendOpType(E_BLEND_OP_TYPE opType)
{
switch (opType)
{
case E_BLEND_OP_TYPE::ADD:
return GL_FUNC_ADD;
case E_BLEND_OP_TYPE::SUBT:
return GL_FUNC_SUBTRACT;
case E_BLEND_OP_TYPE::REVERSED_SUBT:
return GL_FUNC_REVERSE_SUBTRACT;
}
return GL_FUNC_ADD;
}
GLenum COGLMappings::GetCubemapFace(E_CUBEMAP_FACE faceType)
{
switch (faceType)
{
case E_CUBEMAP_FACE::POSITIVE_X:
return GL_TEXTURE_CUBE_MAP_POSITIVE_X;
case E_CUBEMAP_FACE::NEGATIVE_X:
return GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
case E_CUBEMAP_FACE::POSITIVE_Y:
return GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
case E_CUBEMAP_FACE::NEGATIVE_Y:
return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
case E_CUBEMAP_FACE::POSITIVE_Z:
return GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
case E_CUBEMAP_FACE::NEGATIVE_Z:
return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
}
return 0x0;
}
GLenum COGLMappings::GetComparisonFunc(const E_COMPARISON_FUNC& func)
{
switch (func)
{
case E_COMPARISON_FUNC::NEVER:
return GL_NEVER;
case E_COMPARISON_FUNC::LESS:
return GL_LESS;
case E_COMPARISON_FUNC::EQUAL:
return GL_EQUAL;
case E_COMPARISON_FUNC::LESS_EQUAL:
return GL_LEQUAL;
case E_COMPARISON_FUNC::GREATER:
return GL_GREATER;
case E_COMPARISON_FUNC::NOT_EQUAL:
return GL_NOTEQUAL;
case E_COMPARISON_FUNC::GREATER_EQUAL:
return GL_GEQUAL;
case E_COMPARISON_FUNC::ALWAYS:
return GL_ALWAYS;
}
return 0;
}
GLenum COGLMappings::GetStencilOpType(const E_STENCIL_OP& stencilOp)
{
switch (stencilOp)
{
case E_STENCIL_OP::ZERO:
return GL_ZERO;
case E_STENCIL_OP::REPLACE:
return GL_REPLACE;
case E_STENCIL_OP::INVERT:
return GL_INVERT;
case E_STENCIL_OP::INCR:
case E_STENCIL_OP::INCR_SAT:
return GL_INCR;
case E_STENCIL_OP::DECR:
case E_STENCIL_OP::DECR_SAT:
return GL_DECR;
case E_STENCIL_OP::KEEP:
return GL_KEEP;
}
return 0;
}
GLenum COGLMappings::GetCullMode(const E_CULL_MODE& cullMode)
{
switch (cullMode)
{
case E_CULL_MODE::FRONT:
return GL_FRONT;
case E_CULL_MODE::BACK:
return GL_BACK;
case E_CULL_MODE::NONE:
TDE2_ASSERT(false);
return 0;
}
return 0;
}
} |
10d4972baaea893d546180706350ebb48a3e0fb2 | 569d64661f9e6557022cc45428b89eefad9a6984 | /code/gameholder/state_singing.cpp | 604e03eadeedd539dbefbd86dee4031158c1a655 | [] | no_license | dgkang/ROG | a2a3c8233c903fa416df81a8261aab2d8d9ac449 | 115d8d952a32cca7fb7ff01b63939769b7bfb984 | refs/heads/master | 2020-05-25T02:44:44.555599 | 2019-05-20T08:33:51 | 2019-05-20T08:33:51 | 187,584,950 | 0 | 1 | null | 2019-05-20T06:59:06 | 2019-05-20T06:59:05 | null | UTF-8 | C++ | false | false | 471 | cpp | state_singing.cpp | #include "gameholder_pch.h"
#include "state_singing.h"
#include "state_define.h"
/*
StateSinging::StateSinging( BattleUnit* owner ) :
State(STATE_SINGING, owner)
{
m_CanBreak = true;
}
StateSinging::~StateSinging()
{
}
bool StateSinging::CanChangeTo( uint32 state )
{
if(m_CanBreak)
{
return true;
}
else
{
if(state == STATE_STUN || state == STATE_DIE)
return true;
else
return false;
}
}
*/ |
c9031d3f7edfb404112e169b440cd065bdca0d8d | 1fea4fb191099ff1e64a77f16a10128b1c91659d | /src/HEMAX_Undo.cpp | e13a99587876cef1d0cbba3bad43ea1d5a9431c5 | [] | no_license | vfxleo/HoudiniEngineFor3dsMax | 603e3b2e8f7e472811908b9dbc8dd67f814bf86d | 208637dee25c1d32645dd02f4e877efc3912ea25 | refs/heads/master | 2020-11-24T06:37:30.203672 | 2018-10-31T20:27:11 | 2018-10-31T20:27:11 | 228,012,240 | 1 | 0 | null | 2019-12-14T11:33:36 | 2019-12-14T11:33:35 | null | UTF-8 | C++ | false | false | 27,951 | cpp | HEMAX_Undo.cpp | #include "HEMAX_Undo.h"
HEMAX_ParameterRestore::HEMAX_ParameterRestore(INode* TheNode, std::string ParameterName)
: Node(TheNode), Name(ParameterName), ParamNodeId(-1), ParamId(-1)
{
}
HEMAX_ParameterRestore::HEMAX_ParameterRestore(INode* TheNode, HEMAX_NodeId NodeId, HEMAX_ParameterId Param)
: Node(TheNode), ParamNodeId(NodeId), ParamId(Param), Name("")
{
}
HEMAX_ParameterRestore::~HEMAX_ParameterRestore() {}
void
HEMAX_ParameterRestore::EndHold()
{
Node->ClearAFlag(A_HELD);
}
int
HEMAX_ParameterRestore::Size()
{
return (sizeof(Node) + (int)Name.size() + sizeof(ParamNodeId) + sizeof(ParamId));
}
TSTR
HEMAX_ParameterRestore::Description()
{
return L"HDA Parameter State";
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HEMAX_IntParameterRestore::HEMAX_IntParameterRestore(INode* TheNode, std::string ParameterName, std::vector<int> OldIntValues, std::vector<int> NewIntValues)
: HEMAX_ParameterRestore(TheNode, ParameterName), OldParamValues(OldIntValues), NewParamValues(NewIntValues)
{
}
HEMAX_IntParameterRestore::HEMAX_IntParameterRestore(INode* TheNode, HEMAX_NodeId NodeId, HEMAX_ParameterId ParameterId, std::vector<int> OldIntValues, std::vector<int> NewIntValues)
: HEMAX_ParameterRestore(TheNode, NodeId, ParameterId), OldParamValues(OldIntValues), NewParamValues(NewIntValues)
{
}
void
HEMAX_IntParameterRestore::Restore(int IsUndo)
{
if (ParamNodeId > -1 && ParamId > -1)
{
HEMAX_Undo::Instance().UpdateIntParameterValues(Node, ParamNodeId, ParamId, OldParamValues);
}
else
{
HEMAX_Undo::Instance().UpdateIntParameterValues(Node, Name, OldParamValues);
}
}
void
HEMAX_IntParameterRestore::Redo()
{
if (ParamNodeId > -1 && ParamId > -1)
{
HEMAX_Undo::Instance().UpdateIntParameterValues(Node, ParamNodeId, ParamId, NewParamValues);
}
else
{
HEMAX_Undo::Instance().UpdateIntParameterValues(Node, Name, NewParamValues);
}
}
int
HEMAX_IntParameterRestore::Size()
{
return (HEMAX_ParameterRestore::Size() + (int)OldParamValues.size() + (int)NewParamValues.size());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HEMAX_FloatParameterRestore::HEMAX_FloatParameterRestore(INode* TheNode, std::string ParameterName, std::vector<float> OldFloatValues, std::vector<float> NewFloatValues)
: HEMAX_ParameterRestore(TheNode, ParameterName), OldParamValues(OldFloatValues), NewParamValues(NewFloatValues)
{
}
HEMAX_FloatParameterRestore::HEMAX_FloatParameterRestore(INode* TheNode, HEMAX_NodeId NodeId, HEMAX_ParameterId ParameterId, std::vector<float> OldFloatValues, std::vector<float> NewFloatValues)
: HEMAX_ParameterRestore(TheNode, NodeId, ParameterId), OldParamValues(OldFloatValues), NewParamValues(NewFloatValues)
{
}
void
HEMAX_FloatParameterRestore::Restore(int IsUndo)
{
if (ParamNodeId > -1 && ParamId > -1)
{
HEMAX_Undo::Instance().UpdateFloatParameterValues(Node, ParamNodeId, ParamId, OldParamValues);
}
else
{
HEMAX_Undo::Instance().UpdateFloatParameterValues(Node, Name, OldParamValues);
}
}
void
HEMAX_FloatParameterRestore::Redo()
{
if (ParamNodeId > -1 && ParamId > -1)
{
HEMAX_Undo::Instance().UpdateFloatParameterValues(Node, ParamNodeId, ParamId, NewParamValues);
}
else
{
HEMAX_Undo::Instance().UpdateFloatParameterValues(Node, Name, NewParamValues);
}
}
int
HEMAX_FloatParameterRestore::Size()
{
return (HEMAX_ParameterRestore::Size() + (int)OldParamValues.size() + (int)NewParamValues.size());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HEMAX_StringParameterRestore::HEMAX_StringParameterRestore(INode* TheNode, std::string ParameterName, std::vector<std::string> OldStringValues, std::vector<std::string> NewStringValues)
: HEMAX_ParameterRestore(TheNode, ParameterName), OldParamValues(OldStringValues), NewParamValues(NewStringValues)
{
}
HEMAX_StringParameterRestore::HEMAX_StringParameterRestore(INode* TheNode, HEMAX_NodeId NodeId, HEMAX_ParameterId ParameterId, std::vector<std::string> OldStringValues, std::vector<std::string> NewStringValues)
: HEMAX_ParameterRestore(TheNode, NodeId, ParameterId), OldParamValues(OldStringValues), NewParamValues(NewStringValues)
{
}
void
HEMAX_StringParameterRestore::Restore(int IsUndo)
{
if (ParamNodeId > -1 && ParamId > -1)
{
HEMAX_Undo::Instance().UpdateStringParameterValues(Node, ParamNodeId, ParamId, OldParamValues);
}
else
{
HEMAX_Undo::Instance().UpdateStringParameterValues(Node, Name, OldParamValues);
}
}
void
HEMAX_StringParameterRestore::Redo()
{
if (ParamNodeId > -1 && ParamId > -1)
{
HEMAX_Undo::Instance().UpdateStringParameterValues(Node, ParamNodeId, ParamId, NewParamValues);
}
else
{
HEMAX_Undo::Instance().UpdateStringParameterValues(Node, Name, NewParamValues);
}
}
int
HEMAX_StringParameterRestore::Size()
{
return (HEMAX_ParameterRestore::Size() + (int)OldParamValues.size() + (int)NewParamValues.size());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HEMAX_MultiParameterRestore::HEMAX_MultiParameterRestore(INode* TheNode, std::string ParameterName, HEMAX_MultiParameterChangeInfo ChangeInfo)
: HEMAX_ParameterRestore(TheNode, ParameterName), MultiParamChangeInfo(ChangeInfo)
{
}
HEMAX_MultiParameterRestore::HEMAX_MultiParameterRestore(INode* TheNode, HEMAX_NodeId NodeId, HEMAX_ParameterId ParameterId, HEMAX_MultiParameterChangeInfo ChangeInfo)
: HEMAX_ParameterRestore(TheNode, NodeId, ParameterId), MultiParamChangeInfo(ChangeInfo)
{
}
void
HEMAX_MultiParameterRestore::Restore(int IsUndo)
{
if (ParamNodeId > -1 && ParamId > -1)
{
HEMAX_Undo::Instance().UndoMultiParameterChange(Node, ParamNodeId, ParamId, MultiParamChangeInfo);
}
else
{
HEMAX_Undo::Instance().UndoMultiParameterChange(Node, Name, MultiParamChangeInfo);
}
}
void
HEMAX_MultiParameterRestore::Redo()
{
if (ParamNodeId > -1 && ParamId > -1)
{
HEMAX_Undo::Instance().RedoMultiParameterChange(Node, ParamNodeId, ParamId, MultiParamChangeInfo);
}
else
{
HEMAX_Undo::Instance().RedoMultiParameterChange(Node, Name, MultiParamChangeInfo);
}
}
int
HEMAX_MultiParameterRestore::Size()
{
return (HEMAX_ParameterRestore::Size() + sizeof(MultiParamChangeInfo));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HEMAX_InputRestore::HEMAX_InputRestore(INode* TheNode, std::string ParameterName, INode* OldInput, INode* NewInput)
: HEMAX_ParameterRestore(TheNode, ParameterName), OldInputNode(OldInput), NewInputNode(NewInput)
{
}
HEMAX_InputRestore::HEMAX_InputRestore(INode* TheNode, HEMAX_NodeId NodeId, HEMAX_ParameterId ParameterId, INode* OldInput, INode* NewInput)
: HEMAX_ParameterRestore(TheNode, NodeId, ParameterId), OldInputNode(OldInput), NewInputNode(NewInput)
{
}
void
HEMAX_InputRestore::Restore(int IsUndo)
{
if (ParamNodeId > -1 && ParamId > -1)
{
HEMAX_Undo::Instance().UpdateInputParameterValue(Node, ParamNodeId, ParamId, OldInputNode);
}
else
{
HEMAX_Undo::Instance().UpdateInputParameterValue(Node, Name, OldInputNode);
}
}
void
HEMAX_InputRestore::Redo()
{
if (ParamNodeId > -1 && ParamId > -1)
{
HEMAX_Undo::Instance().UpdateInputParameterValue(Node, ParamNodeId, ParamId, NewInputNode);
}
else
{
HEMAX_Undo::Instance().UpdateInputParameterValue(Node, Name, NewInputNode);
}
}
int
HEMAX_InputRestore::Size()
{
return (HEMAX_ParameterRestore::Size() + sizeof(OldInputNode) + sizeof(NewInputNode));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HEMAX_SubnetworkRestore::HEMAX_SubnetworkRestore(INode* TheNode, int Subnetwork, INode* OldInput, INode* NewInput)
: HEMAX_ParameterRestore(TheNode, ""), SubnetworkIndex(Subnetwork), OldInputNode(OldInput), NewInputNode(NewInput)
{
}
HEMAX_SubnetworkRestore::HEMAX_SubnetworkRestore(INode* TheNode, HEMAX_NodeId NodeId, int Subnetwork, INode* OldInput, INode* NewInput)
: HEMAX_ParameterRestore(TheNode, NodeId, -1), SubnetworkIndex(Subnetwork), OldInputNode(OldInput), NewInputNode(NewInput)
{
}
void
HEMAX_SubnetworkRestore::Restore(int IsUndo)
{
if (ParamNodeId > -1)
{
HEMAX_Undo::Instance().UpdateSubnetworkInputValue(Node, ParamNodeId, SubnetworkIndex, OldInputNode);
}
else
{
HEMAX_Undo::Instance().UpdateSubnetworkInputValue(Node, SubnetworkIndex, OldInputNode);
}
}
void
HEMAX_SubnetworkRestore::Redo()
{
if (ParamNodeId > -1)
{
HEMAX_Undo::Instance().UpdateSubnetworkInputValue(Node, ParamNodeId, SubnetworkIndex, NewInputNode);
}
else
{
HEMAX_Undo::Instance().UpdateSubnetworkInputValue(Node, SubnetworkIndex, NewInputNode);
}
}
int
HEMAX_SubnetworkRestore::Size()
{
return (HEMAX_ParameterRestore::Size() + sizeof(SubnetworkIndex) + sizeof(OldInputNode) + sizeof(NewInputNode));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HEMAX_Undo&
HEMAX_Undo::Instance()
{
static HEMAX_Undo UndoInstance;
return UndoInstance;
}
HEMAX_Undo::HEMAX_Undo()
: PluginStore(nullptr), PluginUserInterface(nullptr)
{}
HEMAX_Undo::~HEMAX_Undo() {}
void
HEMAX_Undo::ConnectPlugin(HEMAX_Plugin* Plugin)
{
ThePlugin = Plugin;
}
void
HEMAX_Undo::ConnectPluginStore(HEMAX_Store* Store)
{
PluginStore = Store;
}
void
HEMAX_Undo::ConnectPluginUserInterface(HEMAX_UI* UserInterface)
{
PluginUserInterface = UserInterface;
}
void
HEMAX_Undo::UpdateIntParameterValues(INode* Node, std::string ParameterName, std::vector<int>& IntValues)
{
/*
if (ThePlugin && PluginStore && PluginUserInterface)
{
theHold.Resume();
HEMAX_MaxHoudiniAsset* GeoContainer = PluginStore->GetMaxHoudiniAsset(Node->GetHandle());
GeoContainer->UpdateNodeParameterIntValues(ParameterName, IntValues);
HEMAX_Node* HDANode = GeoContainer->GetNode();
if (HDANode)
{
if (HDANode->AutoRecookOnParameterUpdate)
{
GeoContainer->CookHDA();
ThePlugin->CookMaxHoudiniAsset(GeoContainer->GetNode());
}
}
PluginUserInterface->HandleParameterUndoRedoEvent();
theHold.Suspend();
}
*/
}
void
HEMAX_Undo::UpdateFloatParameterValues(INode* Node, std::string ParameterName, std::vector<float>& FloatValues)
{
/*
if (ThePlugin && PluginStore && PluginUserInterface)
{
theHold.Resume();
HEMAX_MaxHoudiniAsset* GeoContainer = PluginStore->GetMaxHoudiniAsset(Node->GetHandle());
GeoContainer->UpdateNodeParameterFloatValues(ParameterName, FloatValues);
HEMAX_Node* HDANode = GeoContainer->GetNode();
if (HDANode)
{
if (HDANode->AutoRecookOnParameterUpdate)
{
GeoContainer->CookHDA();
ThePlugin->CookMaxHoudiniAsset(GeoContainer->GetNode());
}
}
PluginUserInterface->HandleParameterUndoRedoEvent();
theHold.Suspend();
}
*/
}
void
HEMAX_Undo::UpdateStringParameterValues(INode* Node, std::string ParameterName, std::vector<std::string>& StringValues)
{
/*
if (ThePlugin && PluginStore && PluginUserInterface)
{
theHold.Resume();
HEMAX_MaxHoudiniAsset* GeoContainer = PluginStore->GetMaxHoudiniAsset(Node->GetHandle());
GeoContainer->UpdateNodeParameterStringValues(ParameterName, StringValues);
HEMAX_Node* HDANode = GeoContainer->GetNode();
if (HDANode)
{
if (HDANode->AutoRecookOnParameterUpdate)
{
GeoContainer->CookHDA();
ThePlugin->CookMaxHoudiniAsset(GeoContainer->GetNode());
}
}
PluginUserInterface->HandleParameterUndoRedoEvent();
theHold.Suspend();
}
*/
}
void
HEMAX_Undo::UpdateInputParameterValue(INode* Node, std::string ParameterName, INode* InputNode)
{
/*
if (ThePlugin && PluginStore && PluginUserInterface)
{
theHold.Resume();
HEMAX_MaxHoudiniAsset* GeoContainer = PluginStore->GetMaxHoudiniAsset(Node->GetHandle());
if (GeoContainer)
{
HEMAX_Parameter* TheParameter = GeoContainer->GetNode()->GetParameter(ParameterName);
if (TheParameter)
{
if (InputNode)
{
HEMAX_Input* TheInput = ThePlugin->CreateInputNode(GeoContainer, InputNode->GetHandle(), TheParameter);
if (TheInput)
{
GeoContainer->UpdateInputNode(TheParameter->GetParameterId());
}
}
else
{
GeoContainer->ClearInputNode(TheParameter->GetParameterId());
}
HEMAX_Node* HDANode = GeoContainer->GetNode();
if (HDANode)
{
if (HDANode->IsAutoRecookEnabled())
{
GeoContainer->CookHDA();
ThePlugin->UpdateRecookedHDA(Node->GetHandle());
}
}
}
}
PluginUserInterface->HandleParameterUndoRedoEvent();
theHold.Suspend();
}
*/
}
void
HEMAX_Undo::UpdateSubnetworkInputValue(INode* Node, int Subnetwork, INode* InputNode)
{
/*
if (ThePlugin && PluginStore && PluginUserInterface)
{
theHold.Resume();
HEMAX_MaxHoudiniAsset* GeoContainer = PluginStore->GetMaxHoudiniAsset(Node->GetHandle());
if (GeoContainer)
{
if (InputNode)
{
HEMAX_Input* TheInput = ThePlugin->CreateSubnetworkInputNode(InputNode->GetHandle(), GeoContainer, Subnetwork);
if (TheInput)
{
GeoContainer->UpdateSubnetworkInput(Subnetwork, TheInput);
}
}
else
{
GeoContainer->ClearSubnetworkInput(Subnetwork);
}
HEMAX_Node* HDANode = GeoContainer->GetNode();
if (HDANode)
{
if (HDANode->IsAutoRecookEnabled())
{
GeoContainer->CookHDA();
ThePlugin->UpdateRecookedHDA(Node->GetHandle());
}
}
}
PluginUserInterface->HandleParameterUndoRedoEvent();
theHold.Suspend();
}
*/
}
void
HEMAX_Undo::UndoMultiParameterChange(INode* Node, std::string ParameterName, HEMAX_MultiParameterChangeInfo ChangeInfo)
{
/*
if (ThePlugin && PluginStore && PluginUserInterface)
{
theHold.Resume();
HEMAX_MaxHoudiniAsset* GeoContainer = PluginStore->GetMaxHoudiniAsset(Node->GetHandle());
HEMAX_Parameter TheParameter = GetParameter(*GeoContainer->GetNode(), ParameterName);
if (TheParameter.Type != HEMAX_PARAM_INVALID)
{
if (ChangeInfo.Added)
{
// If the number of params added/removed is greater than 1, then the action has to be occuring at the end of the multi
// parm list.
if (ChangeInfo.Count > 1)
{
for (int c = 0; c < ChangeInfo.Count; ++c)
{
RemoveMultiParameterInstance(TheParameter, TheParameter.Info.instanceCount - 1 - c);
}
}
else
{
RemoveMultiParameterInstance(TheParameter, ChangeInfo.Position);
}
}
else
{
// If the number of params added/removed is greater than 1, then the action has to be occuring at the end of the multi
// parm list.
if (ChangeInfo.Count > 1)
{
for (int c = 0; c < ChangeInfo.Count; ++c)
{
InsertMultiParameterInstance(TheParameter, TheParameter.Info.instanceCount + c);
}
}
else
{
InsertMultiParameterInstance(TheParameter, ChangeInfo.Position);
}
}
}
GeoContainer->CookHDA();
GeoContainer->UpdateMultiParameterList(TheParameter.Info.id);
HEMAX_Node* HDANode = GeoContainer->GetNode();
if (HDANode)
{
GeoContainer->CookHDA();
ThePlugin->CookMaxHoudiniAsset(GeoContainer->GetNode());
}
PluginUserInterface->HandleParameterUndoRedoEvent();
theHold.Suspend();
}
*/
}
void
HEMAX_Undo::RedoMultiParameterChange(INode* Node, std::string ParameterName, HEMAX_MultiParameterChangeInfo ChangeInfo)
{
/*
if (ThePlugin && PluginStore && PluginUserInterface)
{
theHold.Resume();
HEMAX_MaxHoudiniAsset* GeoContainer = PluginStore->GetMaxHoudiniAsset(Node->GetHandle());
HEMAX_Parameter TheParameter = GetParameter(*GeoContainer->GetNode(), ParameterName);
if (TheParameter.Type != HEMAX_PARAM_INVALID)
{
if (ChangeInfo.Added)
{
// If the number of params added/removed is greater than 1, then the action has to be occuring at the end of the multi
// parm list.
if (ChangeInfo.Count > 1)
{
for (int c = 0; c < ChangeInfo.Count; ++c)
{
InsertMultiParameterInstance(TheParameter, TheParameter.Info.instanceCount + c);
}
}
else
{
InsertMultiParameterInstance(TheParameter, ChangeInfo.Position);
}
}
else
{
// If the number of params added/removed is greater than 1, then the action has to be occuring at the end of the multi
// parm list.
if (ChangeInfo.Count > 1)
{
for (int c = 0; c < ChangeInfo.Count; ++c)
{
RemoveMultiParameterInstance(TheParameter, TheParameter.Info.instanceCount - 1 - c);
}
}
else
{
RemoveMultiParameterInstance(TheParameter, ChangeInfo.Position);
}
}
}
GeoContainer->CookHDA();
GeoContainer->UpdateMultiParameterList(TheParameter.Info.id);
HEMAX_Node* HDANode = GeoContainer->GetNode();
if (HDANode)
{
GeoContainer->CookHDA();
ThePlugin->CookMaxHoudiniAsset(GeoContainer->GetNode());
}
PluginUserInterface->HandleParameterUndoRedoEvent();
theHold.Suspend();
}
*/
}
void
HEMAX_Undo::UpdateIntParameterValues(INode* Node, HEMAX_NodeId NodeId, HEMAX_ParameterId ParameterId, std::vector<int>& IntValues)
{
/*
if (ThePlugin && PluginStore && PluginUserInterface)
{
HEMAX_ModifierAsset* ModifierContainer = PluginStore->FindModifierAsset(Node->GetHandle());
if (ModifierContainer)
{
ModifierContainer->UpdateNodeParameterIntValues(NodeId, ParameterId, IntValues);
HEMAX_Modifier* TheModifier = ModifierContainer->SearchModifierStackByNodeId(NodeId);
if (TheModifier)
{
if (TheModifier->GetNode()->AutoRecookOnParameterUpdate)
{
ModifierContainer->CookModifier(NodeId);
}
}
else
{
ModifierContainer->CookModifier(NodeId);
}
}
PluginUserInterface->HandleParameterUndoRedoEvent();
}
*/
}
void
HEMAX_Undo::UpdateFloatParameterValues(INode* Node, HEMAX_NodeId NodeId, HEMAX_ParameterId ParameterId, std::vector<float>& FloatValues)
{
/*
if (ThePlugin && PluginStore && PluginUserInterface)
{
HEMAX_ModifierAsset* ModifierContainer = PluginStore->FindModifierAsset(Node->GetHandle());
if (ModifierContainer)
{
ModifierContainer->UpdateNodeParameterFloatValues(NodeId, ParameterId, FloatValues);
HEMAX_Modifier* TheModifier = ModifierContainer->SearchModifierStackByNodeId(NodeId);
if (TheModifier)
{
if (TheModifier->GetNode()->AutoRecookOnParameterUpdate)
{
ModifierContainer->CookModifier(NodeId);
}
}
else
{
ModifierContainer->CookModifier(NodeId);
}
}
PluginUserInterface->HandleParameterUndoRedoEvent();
}
*/
}
void
HEMAX_Undo::UpdateStringParameterValues(INode* Node, HEMAX_NodeId NodeId, HEMAX_ParameterId ParameterId, std::vector<std::string>& StringValues)
{
/*
if (ThePlugin && PluginStore && PluginUserInterface)
{
HEMAX_ModifierAsset* ModifierContainer = PluginStore->FindModifierAsset(Node->GetHandle());
if (ModifierContainer)
{
ModifierContainer->UpdateNodeParameterStringValues(NodeId, ParameterId, StringValues);
HEMAX_Modifier* TheModifier = ModifierContainer->SearchModifierStackByNodeId(NodeId);
if (TheModifier)
{
if (TheModifier->GetNode()->AutoRecookOnParameterUpdate)
{
ModifierContainer->CookModifier(NodeId);
}
}
else
{
ModifierContainer->CookModifier(NodeId);
}
}
PluginUserInterface->HandleParameterUndoRedoEvent();
}
*/
}
void
HEMAX_Undo::UpdateInputParameterValue(INode* Node, HEMAX_NodeId NodeId, HEMAX_ParameterId ParameterId, INode* InputNode)
{
}
void
HEMAX_Undo::UpdateSubnetworkInputValue(INode* Node, HEMAX_NodeId NodeId, int Subnetwork, INode* InputNode)
{
}
void
HEMAX_Undo::UndoMultiParameterChange(INode* Node, HEMAX_NodeId NodeId, HEMAX_ParameterId ParameterId, HEMAX_MultiParameterChangeInfo ChangeInfo)
{
/*
if (ThePlugin && PluginStore && PluginUserInterface)
{
HEMAX_ModifierAsset* ModifierContainer = PluginStore->FindModifierAsset(Node->GetHandle());
if (ModifierContainer)
{
HEMAX_Modifier* TheModifier = ModifierContainer->SearchModifierStackByNodeId(NodeId);
if (TheModifier)
{
HEMAX_Parameter TheParameter = GetParameter(*TheModifier->GetNode(), ParameterId);
if (TheParameter.Type != HEMAX_PARAM_INVALID)
{
if (ChangeInfo.Added)
{
// If the number of params added/removed is greater than 1, then the action has to be occuring at the end of the multi
// parm list.
if (ChangeInfo.Count > 1)
{
for (int c = 0; c < ChangeInfo.Count; ++c)
{
RemoveMultiParameterInstance(TheParameter, TheParameter.Info.instanceCount - 1 - c);
}
}
else
{
RemoveMultiParameterInstance(TheParameter, ChangeInfo.Position);
}
}
else
{
// If the number of params added/removed is greater than 1, then the action has to be occuring at the end of the multi
// parm list.
if (ChangeInfo.Count > 1)
{
for (int c = 0; c < ChangeInfo.Count; ++c)
{
InsertMultiParameterInstance(TheParameter, TheParameter.Info.instanceCount + c);
}
}
else
{
InsertMultiParameterInstance(TheParameter, ChangeInfo.Position);
}
}
}
}
ModifierContainer->CookModifier(NodeId);
ModifierContainer->UpdateMultiParameterList(NodeId, ParameterId);
ModifierContainer->CookModifier(NodeId);
}
PluginUserInterface->HandleParameterUndoRedoEvent();
}
*/
}
void
HEMAX_Undo::RedoMultiParameterChange(INode* Node, HEMAX_NodeId NodeId, HEMAX_ParameterId ParameterId, HEMAX_MultiParameterChangeInfo ChangeInfo)
{
/*
if (ThePlugin && PluginStore && PluginUserInterface)
{
HEMAX_ModifierAsset* ModifierContainer = PluginStore->FindModifierAsset(Node->GetHandle());
if (ModifierContainer)
{
HEMAX_Modifier* TheModifier = ModifierContainer->SearchModifierStackByNodeId(NodeId);
if (TheModifier)
{
HEMAX_Parameter TheParameter = GetParameter(*TheModifier->GetNode(), ParameterId);
if (TheParameter.Type != HEMAX_PARAM_INVALID)
{
if (ChangeInfo.Added)
{
// If the number of params added/removed is greater than 1, then the action has to be occuring at the end of the multi
// parm list.
if (ChangeInfo.Count > 1)
{
for (int c = 0; c < ChangeInfo.Count; ++c)
{
InsertMultiParameterInstance(TheParameter, TheParameter.Info.instanceCount + c);
}
}
else
{
InsertMultiParameterInstance(TheParameter, ChangeInfo.Position);
}
}
else
{
// If the number of params added/removed is greater than 1, then the action has to be occuring at the end of the multi
// parm list.
if (ChangeInfo.Count > 1)
{
for (int c = 0; c < ChangeInfo.Count; ++c)
{
RemoveMultiParameterInstance(TheParameter, TheParameter.Info.instanceCount - 1 - c);
}
}
else
{
RemoveMultiParameterInstance(TheParameter, ChangeInfo.Position);
}
}
}
}
ModifierContainer->CookModifier(NodeId);
ModifierContainer->UpdateMultiParameterList(NodeId, ParameterId);
ModifierContainer->CookModifier(NodeId);
}
PluginUserInterface->HandleParameterUndoRedoEvent();
}
*/
} |
6bb171dc84406ee6eaa2477a720b44b192c87d8f | 0157ea33437a430d93439c4e0d98b830fc42731b | /Week2/Day12/SingleElementInAsortedArray/cpp/SingleElementInASortedArray.cpp | 71121b7b58de2e9ce823553e8e39b73353ffa0b6 | [] | no_license | shubhanshu1995/May-LeetCoding-Challenge-2020 | 3979f678e3e8b5edf1359fa121a45ad50c73d12d | d22246ffe5078ba45aa4ec6cf46d75cbc7beecfe | refs/heads/master | 2022-08-27T20:01:22.425724 | 2020-05-28T13:46:27 | 2020-05-28T13:46:27 | 262,260,855 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 901 | cpp | SingleElementInASortedArray.cpp | // Source : https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/535/week-2-may-8th-may-14th/3327/
// Author : Shubhanshu Singh
// Date : 13-05-2020
/***************** Using Binary Search *******************************/
// For odd position compare with the previous number.
// For even position compare with the next number.
// The unique number must be at even position.
// Time Complexity: O(logn)
// Space Complexiy: O(1)
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int l = 0, r= nums.size()-1;
while(l < r)
{
int mid = l + (r-l)/2;
if((mid % 2 == 0 && nums[mid] == nums[mid + 1]) || (mid % 2 != 0 && nums[mid] == nums[mid - 1]))
l = mid + 1;
else
r = mid;
}
return nums[l];
}
}; |
54b7a7096c4b05063caebd40ede49a0c0e6ec0a6 | a33aac97878b2cb15677be26e308cbc46e2862d2 | /program_data/PKU_raw/99/200.c | 703bfd1e012a7ab769667633686e8bd676ae652c | [] | no_license | GabeOchieng/ggnn.tensorflow | f5d7d0bca52258336fc12c9de6ae38223f28f786 | 7c62c0e8427bea6c8bec2cebf157b6f1ea70a213 | refs/heads/master | 2022-05-30T11:17:42.278048 | 2020-05-02T11:33:31 | 2020-05-02T11:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 583 | c | 200.c | int main()
{
int n;
double x,y,z,p;
int a=0;
int b=0;
int c=0;
int d=0;
int i;
int sz[100];
scanf("%d\n",&n);
for(i=0;i<n;i++){
scanf("%d",&sz[i]);
}
for(i=0;i<n;i++){
if(sz[i]<=18){
a+=1;
}
else if(sz[i]>18,sz[i]<=35){
b+=1;
}
else if(sz[i]>35,sz[i]<=60){
c+=1;
}
else{
d+=1;
}
}
x=(double)a/n*100;
y=(double)b/n*100;
z=(double)c/n*100;
p=(double)d/n*100;
printf("1-18: %.2lf%%\n",x);
printf("19-35: %.2lf%%\n",y);
printf("36-60: %.2lf%%\n",z);
printf("60??: %.2lf%%\n",p);
return 0;
} |
7fa260ac062e7437300e976e29196f22407b5306 | e06a10d698e3796eba8fa9d7a2d39bb619517bbf | /GeeksForGeeks/Mixed_Problems/Next_Greater_Element.cpp | 164f034aeeaa5732c69c880dc7d13b864d81f6d0 | [] | no_license | FelixFelicis555/Data-Structure-And-Algorithms | df5434f56c7ba3468e29fe46c23fb52b650867e3 | 9af25d035c336894aee9f9d534a54bd5be752409 | refs/heads/master | 2021-10-23T13:04:35.445435 | 2019-03-17T14:44:37 | 2019-03-17T14:44:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | cpp | Next_Greater_Element.cpp | #include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<int>s;
int a[]={11,3,2,5,6};
int n=sizeof(a)/sizeof(a[0]);
s.push(a[0]);
for (int i=1;i<n;i++){
if(a[i]>s.top()){
cout<<s.top()<<"--->"<<a[i]<<endl;
s.pop();
}
else
{
s.push(a[i]);
}
}
return 0;
}
|
4d337025b8a89b4ba446f3934b014cc87cab0892 | bccf1778a4dec5a22f1e86fbc05eb7eb2d7b5bc8 | /engine/include/ClippingMode.h | ea612db072cdc78b8cc1d4169083f22334867887 | [] | no_license | alexander-koval/PlayTest | 09820f92427bb0bb4fb77390a7e751d0f50cfaaf | ddff52e5704685cac37f7d8584378600ecb6131e | refs/heads/master | 2016-08-12T06:46:11.039255 | 2016-04-05T16:00:27 | 2016-04-05T16:00:27 | 43,216,377 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,364 | h | ClippingMode.h | #ifndef _CLIPPINGMODE_H_
#define _CLIPPINGMODE_H_
//
// Класс обрезания
//
class ClippingMode {
friend bool operator == (const ClippingMode& first, const ClippingMode& second);
friend bool operator != (const ClippingMode& first, const ClippingMode& second);
private:
bool _isLeft;
bool _isTop;
bool _isRight;
bool _isBottom;
ClippingMode(bool isLeft, bool isTop, bool isRight, bool isBottom);
public:
static const ClippingMode NONE;
static const ClippingMode LEFT;
static const ClippingMode TOP;
static const ClippingMode RIGHT;
static const ClippingMode BOTTOM;
static const ClippingMode LEFT_RIGHT;
static const ClippingMode TOP_BOTTOM;
static const ClippingMode ALL;
bool IsLeft();
bool IsTop();
bool IsRight();
bool IsBottom();
static ClippingMode Add(ClippingMode first, ClippingMode second);
static ClippingMode Sub(ClippingMode first, ClippingMode second);
};
inline ClippingMode operator + (ClippingMode first, ClippingMode second) {
return ClippingMode::Add(first, second);
}
inline ClippingMode operator - (ClippingMode first, ClippingMode second) {
return ClippingMode::Sub(first, second);
}
bool operator == (const ClippingMode& first, const ClippingMode& second);
bool operator != (const ClippingMode& first, const ClippingMode& second);
#endif
|
58c5846d9b8a05d07c256a20584f59e7e702e046 | 8f5aad744ec475e69a08daa50053300b1dd639da | /main.cpp | 54e0748e63a000dd1a4871b2ae3d860e1c178537 | [] | no_license | CalvinYiuHK/Poker_Comparison | 16223e268af50eba64f2cbbe56ba1e85da0ba2c5 | a86f8a22e4af8cdb43527b1f2dacab5e5e57fd56 | refs/heads/master | 2023-02-21T16:40:40.275683 | 2021-01-22T11:50:26 | 2021-01-22T11:50:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,606 | cpp | main.cpp | #include <iostream>
#include <compare>
#include <vector>
#include <functional>
#include <map>
#include "compare.h"
int main() {
std::cout << "Hello, World!" << std::endl;
std::cout << "testing" << std::endl;
compare::hand hand1;
compare::hand hand2;
for (int hand = 1; hand < 3; hand++) {
for (int i = 1; i < 6; i++) {
int number, suit;
while ((std::cout << "[Hand " << hand << " Card " << i << "] Enter a number(1-13): " &&
!(std::cin >> number)) || number > 13 || number < 1) {
std::cin.clear(); //clear bad input flag
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
std::cout << "Invalid input; please re-enter.\n";
}
while ((std::cout << "[Hand " << hand << " Card " << i << "] Enter a suit (1-4): " &&
!(std::cin >> suit)) || suit > 4 || suit < 1) {
std::cin.clear(); //clear bad input flag
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
std::cout << "Invalid input; please re-enter.\n";
}
if (number == 1)
number = 14;
if (hand == 1)
hand1.push_back(std::make_tuple(number, suit));
else
hand2.push_back(std::make_tuple(number, suit));
}
}
int result = compare::compare_hand(hand1, hand2);
std::cout << (result? "Hand 1 win.": (result == 0)? "Hand 2 win.": "Draw." )<< '\n';
return 0;
}
|
5a733643ecdc19509af207aa6c1518beb555c28f | 248cf752bd16da45b3af486d3acf1a7257bb48ca | /src/command/createfeedcommand.cpp | 55c1d2d166d5346dd43bc339723f33f3f3c3a605 | [
"BSD-3-Clause",
"CC0-1.0"
] | permissive | KDE/akregator | e38dab81c9842cad5ba4fc0ecfd2794704ed09b5 | 00e15965065ab2be9efe886f849f982da307290d | refs/heads/master | 2023-08-03T03:40:56.033717 | 2023-08-03T02:13:06 | 2023-08-03T02:13:06 | 66,922,843 | 49 | 12 | null | null | null | null | UTF-8 | C++ | false | false | 3,862 | cpp | createfeedcommand.cpp | /*
This file is part of Akregator.
SPDX-FileCopyrightText: 2008 Frank Osterfeld <osterfeld@kde.org>
SPDX-License-Identifier: GPL-2.0-or-later WITH Qt-Commercial-exception-1.0
*/
#include "createfeedcommand.h"
#include "addfeeddialog.h"
#include "feed.h"
#include "feedlist.h"
#include "feedpropertiesdialog.h"
#include "folder.h"
#include "mainwidget.h"
#include "subscriptionlistview.h"
#include <QUrl>
#include <QClipboard>
#include <QPointer>
#include <QTimer>
#include <cassert>
using namespace Akregator;
class Akregator::CreateFeedCommandPrivate
{
CreateFeedCommand *const q;
public:
explicit CreateFeedCommandPrivate(CreateFeedCommand *qq);
void doCreate();
QPointer<MainWidget> m_parent;
QPointer<Folder> m_rootFolder;
QPointer<SubscriptionListView> m_subscriptionListView;
QString m_url;
QPointer<Folder> m_parentFolder;
QPointer<TreeNode> m_after;
bool m_autoexec = false;
};
CreateFeedCommandPrivate::CreateFeedCommandPrivate(CreateFeedCommand *qq)
: q(qq)
, m_rootFolder(nullptr)
, m_subscriptionListView(nullptr)
, m_parentFolder(nullptr)
, m_after(nullptr)
{
}
void CreateFeedCommandPrivate::doCreate()
{
Q_ASSERT(m_rootFolder);
Q_ASSERT(m_subscriptionListView);
QPointer<AddFeedDialog> afd = new AddFeedDialog(q->parentWidget(), QStringLiteral("add_feed"));
QString url = m_url;
if (url.isEmpty()) {
const QClipboard *const clipboard = QApplication::clipboard();
Q_ASSERT(clipboard);
const QString clipboardText = clipboard->text();
// Check for the hostname, since the isValid method is not strict enough
if (!QUrl(clipboardText).host().isEmpty()) {
url = clipboardText;
}
}
afd->setUrl(QUrl::fromPercentEncoding(QUrl::fromUserInput(url).toEncoded()));
QPointer<QObject> thisPointer(q);
if (m_autoexec) {
afd->accept();
} else {
afd->exec();
}
if (!thisPointer) { // "this" might have been deleted while exec()!
delete afd;
return;
}
Feed *const feed = afd->feed();
delete afd;
if (!feed) {
q->done();
return;
}
QPointer<FeedPropertiesDialog> dlg = new FeedPropertiesDialog(q->parentWidget(), QStringLiteral("edit_feed"));
dlg->setFeed(feed);
dlg->selectFeedName();
if (!m_autoexec && (dlg->exec() != QDialog::Accepted || !thisPointer)) {
delete feed;
} else {
if (!m_parentFolder) {
if (!m_rootFolder) {
if (m_parent->allFeedsList()) {
q->setRootFolder(m_parent->allFeedsList()->allFeedsFolder());
}
}
m_parentFolder = m_rootFolder;
}
if (m_parentFolder) {
m_parentFolder->insertChild(feed, m_after);
m_subscriptionListView->ensureNodeVisible(feed);
}
}
delete dlg;
q->done();
}
CreateFeedCommand::CreateFeedCommand(MainWidget *parent)
: Command(parent)
, d(new CreateFeedCommandPrivate(this))
{
d->m_parent = parent;
}
CreateFeedCommand::~CreateFeedCommand() = default;
void CreateFeedCommand::setSubscriptionListView(SubscriptionListView *view)
{
d->m_subscriptionListView = view;
}
void CreateFeedCommand::setRootFolder(Folder *rootFolder)
{
d->m_rootFolder = rootFolder;
}
void CreateFeedCommand::setUrl(const QString &url)
{
d->m_url = url;
}
void CreateFeedCommand::setPosition(Folder *parent, TreeNode *after)
{
d->m_parentFolder = parent;
d->m_after = after;
}
void CreateFeedCommand::setAutoExecute(bool autoexec)
{
d->m_autoexec = autoexec;
}
void CreateFeedCommand::doStart()
{
QTimer::singleShot(0, this, [this]() {
d->doCreate();
});
}
void CreateFeedCommand::doAbort()
{
}
#include "moc_createfeedcommand.cpp"
|
ba8cb493db18dd50f92da971453575ead1926dbe | 99bffee52d9004723e9cafe96898b3a4a56240bb | /03_Exercise/amp.cpp | cc5b6dbbd138520bb9fe923be05a1e97d2c654d7 | [] | no_license | kadermat/ProgAlg | b37238f9a1574c3bd9706c387b50416921e6e0da | c1a6113234b2b7b43f48d36ee35d107b5a67559e | refs/heads/main | 2023-03-18T11:02:44.242772 | 2021-03-05T14:02:13 | 2021-03-05T14:02:13 | 344,827,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,046 | cpp | amp.cpp | #include <amp.h>
#include <amp_math.h>
#include "main.h"
////////////////////////////////////////////////////////////////////////
// Documentation
// https://docs.microsoft.com/en-us/cpp/parallel/amp/cpp-amp-cpp-accelerated-massive-parallelism?redirectedfrom=MSDN&view=vs-2019
// https://www.microsoftpressstore.com/articles/article.aspx?p=2201645
////////////////////////////////////////////////////////////////////////
// RGB macros
#undef GetBValue
#undef GetGValue
#undef GetRValue
#undef RGB
#define GetBValue(rgb) (0xFF & rgb)
#define GetGValue(rgb) (0xFF & (rgb >> 8))
#define GetRValue(rgb) (0xFF & (rgb >> 16))
#define RGB(r, g, b) ((((r << 8) | g) << 8) | b | 0xFF000000)
////////////////////////////////////////////////////////////////////////
static int dist(int x, int y) restrict(amp) {
#ifdef FAST_MATH
int d = (int)Concurrency::fast_math::sqrtf((float)(x*x) + (float)(y*y));
#else
int d = (int)Concurrency::precise_math::sqrtf((float)(x*x) + (float)(y*y));
#endif
return (d < 256) ? d : 255;
}
////////////////////////////////////////////////////////////////////////
void processAMP(const fipImage& input, fipImage& output, const int *hFilter, const int *vFilter, int fSize, Stopwatch& sw) {
const int bypp = 4;
const int w = input.getWidth();
const int h = input.getHeight();
assert(w == output.getWidth() && h == output.getHeight() && input.getImageSize() == output.getImageSize());
assert(input.getBitsPerPixel() == bypp*8);
const unsigned int stride = input.getScanWidth();
const int fSizeD2 = fSize/2;
// list accelerators
std::vector<Concurrency::accelerator> accls = Concurrency::accelerator::get_all();
std::wcout << "Found " << accls.size() << " C++ AMP accelerator(s):" << std::endl;
std::for_each(accls.cbegin(), accls.cend(), [](const Concurrency::accelerator& a)
{
std::wcout << " " << a.device_path << std::endl << " " << a.description << std::endl << std::endl;
});
std::wcout << "AMP default accelerator: " << Concurrency::accelerator(Concurrency::accelerator::default_accelerator).description << std::endl;
sw.Start();
// create array-views: they manage data transport between host and GPU
Concurrency::array_view<const COLORREF, 2> avI(stride/bypp, h, reinterpret_cast<COLORREF*>(input.getScanLine(0)));
Concurrency::array_view<COLORREF, 2> avR(stride/bypp, h, reinterpret_cast<COLORREF*>(output.getScanLine(0)));
avR.discard_data(); // don't copy avR from host to GPU
Concurrency::array_view<const int, 2> avH(fSize, fSize, hFilter);
Concurrency::array_view<const int, 2> avV(fSize, fSize, vFilter);
// parallel processing on GPU
Concurrency::parallel_for_each(avI.extent, [=](Concurrency::index<2> idx) restrict(amp) {
// TODO implement convolution
// use COLORREF c = avI[idx] to read a pixel, and use GetBValue(c) to access the blue channel of color c
// use avR[idx] = RGB(r, g, b) to write a pixel with RGB channels to output image
});
// wait until the GPU has finished and the result has been copied back to output
avR.synchronize();
sw.Stop();
}
|
3e5b6fde098c74e43e3d3c339a4413f887a43d25 | 235bccb2fc4f06898ac53402706371bef544f377 | /UVA/721 - Invitation Cards.cpp | eb578edb5b5efb92c3693edae86d6cb39567d473 | [] | no_license | GaziNazim/CPP | 76fa44bff7e11d87ffcf95426b0306ea9f9dca93 | 78b0d68642efe33fef5ce6bb50153bd38a11b4bc | refs/heads/master | 2016-08-08T00:50:50.996535 | 2015-05-10T15:33:13 | 2015-05-10T15:33:13 | 30,353,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,319 | cpp | 721 - Invitation Cards.cpp | #include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(__typeof(n) i=0;i<(n);i++)
#define inf 1000000000
#define rep2(i,a,b) for(__typeof(b) i=(a);i<=(b);i++)
#define pb push_back
int total;
int cgo[1000000],cret[1000000]; // cgo going cost and cret for return cost.
vector < vector < int > > node,cost,rnode,rcost;
struct state
{
int a,cost;
bool operator < (const state& a)const
{
return cost>a.cost;
}
};
void intialize_all(int p)
{
node.clear();
cost.clear();
rnode.clear();
rcost.clear();
node.resize(p);
rnode.resize(p);
cost.resize(p);
rcost.resize(p);
}
int bfs(int n)
{
rep(i,n+1) cgo[i]=inf;
priority_queue<state> q;
cgo[1]=0;
state u,v;
u.a=1;
u.cost=0;
q.push(u);
int vnode,ucost,vcost,tcost=0;
while(!q.empty())
{
u=q.top();
q.pop();
rep(i,node[u.a].size())
{
vnode=node[u.a][i];
ucost=u.cost;
vcost=ucost+cost[u.a][i];
if(cgo[vnode]>=vcost)
{
cgo[vnode]=vcost;
v.a=vnode;
v.cost=vcost;
q.push(v);
}
}
}
rep2(i,2,n) {tcost = tcost+ cgo[i];}
return tcost;
}
int rbfs(int n)
{
rep(i,n+1) cret[i]=inf;
priority_queue<state> q;
cret[1]=0;
state u,v;
u.a=1;
u.cost=0;
q.push(u);
int vnode,ucost,vcost,tcost=0;
while(!q.empty())
{
u=q.top();
q.pop();
rep(i,rnode[u.a].size())
{
vnode=rnode[u.a][i];
ucost=u.cost;
vcost=ucost+rcost[u.a][i];
if(cret[vnode]>=vcost)
{
cret[vnode]=vcost;
v.a=vnode;
v.cost=vcost;
q.push(v);
}
}
}
rep2(i,2,n) {tcost = tcost+ cret[i];}
return tcost;
}
int main()
{
int t,p,q,x,y,c;
cin>>t;
while(t--)
{
total=0;
cin>>p>>q;
intialize_all(p+1);
rep(i,q)
{
cin>>x>>y>>c;
node[x].pb(y);
rnode[y].pb(x);
cost[x].pb(c);
rcost[y].pb(c);
}
total =total + bfs(p);
total = total + rbfs(p);
cout<< total<<endl;
}
return 0;
}
|
f9fde9048430467a1a95d4bff79dcc3b0542d354 | 0d39f41dfa42bb9164309700d21ab7fed00264d1 | /phoenix/SDL_Initializer.h | 8da32e37ecacc07cfc2b7d41b4d0091aeb244365 | [] | no_license | qnope/Phoenix | 832dc271dcf445a9b78d75e50e402789e7aaaf75 | f4259bc625f6b2150e1c823078c80e3be9fd79c6 | refs/heads/master | 2021-07-09T15:17:53.975985 | 2020-07-26T17:45:18 | 2020-07-26T17:50:55 | 166,474,743 | 0 | 0 | null | 2020-06-24T22:31:19 | 2019-01-18T21:28:18 | C++ | UTF-8 | C++ | false | false | 311 | h | SDL_Initializer.h | #pragma once
#include <SDL2/SDL.h>
#include <string>
namespace phx {
struct PhoenixSDLInitializationException {
std::string exception;
};
class SDL_Initializer {
public:
SDL_Initializer();
~SDL_Initializer();
private:
inline static std::size_t numberInstance = 0;
};
} // namespace phx
|
80f6fc47ca1e3cdf8034d9f84711a7090864983a | 754d1fd9bd0f02c4a6ab62c277c6c06edb80efa8 | /RPCProxy4Rep.h | 64cfd17cdc2ce75a3ea60ff2a84e8edb477f440f | [] | no_license | Lights999/RPCProxyForRep | 0f962568db0319e5340f993eafcb29658c7ea5c9 | bcaf041c11ba33d6258ff516056f2df8a5ae6fde | refs/heads/master | 2022-01-06T18:15:14.346957 | 2019-05-11T16:36:15 | 2019-05-11T16:36:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,199 | h | RPCProxy4Rep.h | #pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "CoreNet.h"
#include <type_traits>
#include "RPCProxy4Rep.generated.h"
class APlayerController;
UCLASS(NotBlueprintType, NotBlueprintable)
class UE4SINGLETONS_API URPCProxy4Rep : public UActorComponent
{
GENERATED_BODY()
URPCProxy4Rep();
protected:
UFUNCTION(Server, Reliable, WithValidation)
void RPC_Reuqest(UObject* Object, const FName& FuncName, const TArray<uint8>& Buffer);
UFUNCTION(Client, Reliable)
void RPC_Notify(UObject* Object, const FName& FuncName, const TArray<uint8>& Buffer);
void __Internal_Call(UObject* InUserObject, FName InFunctionName, const TArray<uint8>& Buffer);
static void __Internal_CallRemote(APlayerController* PC, UObject* InUserObject, const FName& InFunctionName,
const TArray<uint8>& Buffer);
static class UPackageMap* GetPackageMap(APlayerController* PC);
static int64 MaxBitCount;
template<typename... Args>
static void MemoryWrite(FArchive& Ar, Args... InArgs)
{
int Temp[] = {0, (void(Ar << InArgs), 0)...};
(void)(Temp);
}
public:
template<typename>
friend struct RepRPCHelper;
};
template<typename F>
struct RepRPCHelper;
template<typename UserClass, typename... Args>
struct RepRPCHelper<void (UserClass::*)(Args...)>
{
static auto CallRemote(APlayerController* PC, UserClass* InUserObject, const FName& InFunctionName, Args... InArgs)
{
check(InUserObject && PC);
FNetBitWriter Writer{URPCProxy4Rep::GetPackageMap(PC), 8};
URPCProxy4Rep::MemoryWrite(Writer, ((std::remove_cv_t<Args>&)InArgs)...);
if (ensure(!Writer.IsError() && Writer.GetNumBits() <= UPlayerRPCProxy::MaxBitCount))
URPCProxy4Rep::__Internal_CallRemote(PC, InUserObject, InFunctionName, *Writer.GetBuffer());
}
};
#define _RepCallRemote(PC, Obj, FuncName, ...) \
RepRPCHelper<decltype(FuncName)>::CallRemote(PC, Obj, STATIC_FUNCTION_FNAME(TEXT(#FuncName)), __VA_ARGS__)
#if __MSV_VER__
#define _RepCallExpand(x) x
#define RepCallRequest(...) _RepCallExpand(_RepCallRemote(__VA_ARGS__))
#define RepCallNotify(...) _RepCallExpand(_RepCallRemote(__VA_ARGS__))
#else
#define RepCallRequest _RepCallRemote
#define RepCallNotify _RepCallRemote
#endif
|
4ff41987c0a0a304880a6f5d3d83e4441dc081cc | 5255d111fdc2f45137298dcffc51d7ade2404ca5 | /Practices/source/generic-type.cpp | 6daac4e9951219c102d39693f36253a45bf96394 | [] | no_license | terrysky18/Cpp-training | ae4ae2a84fe8c383b52c29be3e9746795c0c50db | 9d06033cef53c22e964595daaff20d61aad6d6c1 | refs/heads/master | 2021-03-16T07:56:46.217053 | 2017-11-26T19:30:12 | 2017-11-26T19:30:12 | 109,452,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 369 | cpp | generic-type.cpp | #include <iostream>
using namespace std;
template <class Numeric>
Numeric Max(const Numeric& x, const Numeric& y);
int main()
{
long dA = 123456;
long dB = 45678;
cout<<"The bigger number is: ";
cout<<Max<long>(dA, dB)<<endl;
return 0;
}
template <class Numeric>
Numeric Max(const Numeric& x, const Numeric& y)
{
if(x>y) { return x; }
else { return y; }
}
|
23fe7faa2d0a34311b68c1c82900736b64137211 | 73851ed86c963ea38fe8f204f75e0c7af5f24088 | /SuperWisdomUtils/LSP/lsp_helper.cpp | 097a783bb9fde9f1914fe1321207bda6d5e65088 | [
"Apache-2.0"
] | permissive | zhichao281/SuperWisdom | f0a121ac1ebc88644aed5f904272318baa929fb3 | 9d722c856c08238023f16896301b5106286c0fad | refs/heads/master | 2023-04-02T03:26:07.294875 | 2023-03-23T13:03:20 | 2023-03-23T13:03:20 | 125,453,975 | 11 | 9 | null | null | null | null | GB18030 | C++ | false | false | 4,022 | cpp | lsp_helper.cpp | #include "stdafx.h"
#include <strsafe.h>
#include "lsp_helper.h"
namespace lsp_helper{
/*
* 多字节转宽字节
* code by Root
* E-mail: cppcoffee@gmail.com
*/
int MByteToWChar( LPCSTR lpMultiByteStr,
LPWSTR lpWideCharStr,
int cchWideChar )
{
return MultiByteToWideChar(CP_ACP,
0,
lpMultiByteStr,
-1,
lpWideCharStr,
cchWideChar );
}
/*
* 展开环境变量
* code by Root
* E-mail: cppcoffee@gmail.com
*/
CString ExpandEnvironment(LPCTSTR item_data)
{
const TCHAR *env_begin_pos;
const TCHAR *env_end_pos;
TCHAR env_name[MAX_PATH];
TCHAR buffer[MAX_PATH];
if ( item_data == NULL )
return _T("");
if ( *item_data != '%' )
return item_data;
env_begin_pos = CharNext(item_data);
env_end_pos = _tcschr(env_begin_pos, '%');
if ( !env_end_pos )
return _T("");
memset(env_name, 0, sizeof(env_name));
_tcsncpy_s(env_name, MAX_PATH, env_begin_pos, env_end_pos - env_begin_pos);
if ( !GetEnvironmentVariable(env_name, buffer, _countof(buffer)) )
return _T("");
env_end_pos = CharNext(env_end_pos);
CString full_path(buffer);
full_path += env_end_pos;
return full_path;
}
/*
* 从指定的文件获取说明和公司名称
* code by Root
* E-mail: cppcoffee@gmail.com
*/
BOOL GetFileDescAndCompany( LPCTSTR file_path, CString& file_descript, CString& company_name )
{
file_descript.Empty();
company_name.Empty();
DWORD version_size = GetFileVersionInfoSize( file_path, 0 );
if ( version_size == 0 )
return FALSE;
CTempBuffer<BYTE> version_data(version_size);
GetFileVersionInfo( file_path, 0, version_size, version_data );
LANGANDCODEPAGE* codepage;
UINT len;
if ( !VerQueryValue(version_data,
_T("\\VarFileInfo\\Translation"),
(LPVOID*)&codepage,
&len) )
{
return FALSE;
}
TCHAR subblock[MAX_PATH] = {0};
StringCchPrintf( subblock,
_countof(subblock),
_T("\\StringFileInfo\\%04x%04x\\FileDescription"),
codepage->wLanguage,
codepage->wCodePage );
LPCWSTR value = NULL;
if ( VerQueryValue(version_data, subblock, (LPVOID*)&value, &len ) )
{
file_descript = value;
}
StringCchPrintf( subblock,
_countof(subblock),
_T("\\StringFileInfo\\%04x%04x\\CompanyName"),
codepage->wLanguage,
codepage->wCodePage );
if ( VerQueryValue(version_data, subblock, (LPVOID*)&value, &len) )
{
company_name = value;
}
return TRUE;
}
/*
* 导出指定注册表路径到指定的文件路径
* code by Root
* E-mail: cppcoffee@gmail.com
*/
BOOL ExportRegPath( LPCTSTR reg_path, LPCTSTR export_path )
{
// 进行导出操作
SHELLEXECUTEINFO ExecInfo = {0};
ExecInfo.cbSize = sizeof(ExecInfo);
ExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ExecInfo.lpVerb = _T("open");
ExecInfo.lpFile = _T("regedit.exe");
ExecInfo.nShow = SW_SHOW;
CString strParams(_T("/e \""));
strParams += export_path;
strParams += _T("\" ");
strParams += _T("\"");
strParams += reg_path;
strParams += _T("\"");
ExecInfo.lpParameters = strParams;
if ( !ShellExecuteEx(&ExecInfo) )
return FALSE;
WaitForSingleObject(ExecInfo.hProcess, INFINITE);
CloseHandle(ExecInfo.hProcess);
return TRUE;
}
/*
* 读取保存文件的列表信息
* code by Root
* E-mail: cppcoffee@gmail.com
*/
BOOL ReadRestoreData( TCHAR* buf, DWORD buf_size, LPCTSTR file_path )
{
HANDLE hFile = CreateFile( file_path,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL );
if ( hFile == INVALID_HANDLE_VALUE )
return FALSE;
DWORD dwFileSize = GetFileSize(hFile, NULL);
if ( dwFileSize > buf_size )
return FALSE;
DWORD dwSize;
++dwFileSize;
CHAR* data = new CHAR[dwFileSize];
ZeroMemory(data, dwFileSize);
ReadFile(hFile, data, dwFileSize, &dwSize, NULL);
int len = MByteToWChar(data, NULL, 0);
if ( buf_size < (DWORD)len )
{
delete [] data;
return FALSE;
}
MByteToWChar( data, buf, buf_size );
delete [] data;
return TRUE;
}
}
|
61af0ecb9303c1db5dd51be9d166e2643d8a6757 | 976239166f6a2ed72972e2244ba62438391323f7 | /include/tuw_airskin/AirSkinColorNodelet.h | 6c09b6a4e58bdebd143012b9df86ff2fc1ac4172 | [] | no_license | tuw-robotics/tuw_airskin | 7271eb1a36bcffa2c14b36b61ee6a3431d67402c | 375d6dfbc3af721a40b00ce8a17a8b6ebb3233ee | refs/heads/master | 2020-03-31T21:51:24.960910 | 2019-01-31T10:08:21 | 2019-01-31T10:08:21 | 152,596,251 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,438 | h | AirSkinColorNodelet.h | #ifndef AIRSKINCONTROL_NODELET_H
#define AIRSKINCONTROL_NODELET_H
#include <nodelet/nodelet.h>
#include <ros/ros.h>
#include <tuw_airskin_msgs/AirskinInfo.h>
#include <tuw_airskin_msgs/AirskinColors.h>
#include <tuw_airskin_msgs/AirskinPressures.h>
#include <geometry_msgs/Twist.h>
#include <tuw_nav_msgs/JointsIWS.h>
#include <tf/transform_listener.h>
#include <tuw_airskin/AirSkinColorNodeletConfig.h>
#include <dynamic_reconfigure/server.h>
namespace tuw
{
class AirSkinColorNodelet : public nodelet::Nodelet
{
public:
virtual void onInit();
private:
ros::NodeHandle nh_;
ros::NodeHandle n_;
ros::Subscriber sub_pressures_;
ros::Subscriber sub_info_;
ros::Publisher pub_colors_;
tf::TransformListener tf_listener_;
double info_timeout_;
std::vector<std::string> pad_names_;
std::map<std::string, int> pads_;
bool publish_joint_;
dynamic_reconfigure::Server<tuw_airskin::AirSkinColorNodeletConfig> reconfigureServer_;
dynamic_reconfigure::Server<tuw_airskin::AirSkinColorNodeletConfig>::CallbackType reconfigureFnc_;
tuw_airskin::AirSkinColorNodeletConfig config_;
tuw_airskin_msgs::AirskinInfo airskin_info_;
void infoCallback(const tuw_airskin_msgs::AirskinInfo::ConstPtr &msg);
void pressuresCallback(const tuw_airskin_msgs::AirskinPressures::ConstPtr &msg);
void configCallback(tuw_airskin::AirSkinColorNodeletConfig &config, uint32_t level);
};
}
#endif // AIRSKINCONTROL_NODELET_H
|
aee88ac7611b9472fc051d6711c1a7f6906ce60b | 300e2c6ec1aec1032e9cf8f6802020877a8f4cb9 | /exercice_cpp/vect.cpp | 9e89a516eff4a6923becaa71b4d3dedc9ddcabe4 | [] | no_license | Freackles/Exercice_cpp_Vect_heritage | 63e5d2a075ee85ae98fadfd5fc2db1c03f5ce97a | 78a66d9c0dfd3910050b9ecd23c6a0f636169ba6 | refs/heads/master | 2020-12-29T15:23:04.976838 | 2020-02-06T09:37:26 | 2020-02-06T09:37:26 | 238,652,657 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 235 | cpp | vect.cpp | #include "vect.h"
#include <iostream>
#include <cstdlib>
vect::vect(int nI)
{
this->nelem = nI;
this->adr = (int*)malloc(nI+1);
}
vect::~vect()
{
free(adr);
}
int& vect::operator[](int nI)
{
return adr[nI];
}
|
30586e056ecdf04b9a1fde864f3ef81eebd4d0ea | 8a3776ded3116f2fc51d6ed2cffda9651c4f50ff | /HW3Q1/HW3Q1/landmark.cpp | b26eec071e1c6b9ff7fb277da1bedd816642ca0c | [] | no_license | charliet2020/CS32HW3 | c967dca5c5f6f50e5dcc40e70894d251f5150217 | adb96454016b79df0ab8fdee20e03a88a7b2fb5f | refs/heads/master | 2022-11-23T22:42:20.275820 | 2020-07-20T20:46:24 | 2020-07-20T20:46:24 | 281,222,194 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,958 | cpp | landmark.cpp | /*
#include <iostream>
#include <string>
using namespace std;
//all about polymorphism
//*/
//Landmark declaration
class Landmark
{
public:
Landmark(string name);
virtual string name() const; //not pure because I want this to be inherited into Restaurant and Hotel
virtual string icon() const = 0; //alone is sufficient to prevent Landmark construction
virtual string color() const;
//want color to be inherited since no 2 functions with non-empty bodies
//may have the same implementation
virtual ~Landmark();
private:
string m_name;
//Landmark* m_landmark;
};
//Hotel declaration
class Hotel : public Landmark
{
public:
Hotel(string name);
virtual string icon() const;
//color inherited from Landmark
//name inherited from Landmark
virtual ~Hotel();
private:
//string m_name; No class may have a data member whose value is identical for every object of a particular class type
//Landmark *lm;
};
//Restaurant declaration
class Restaurant : public Landmark
{
public:
Restaurant(string name, int cap);
virtual string icon() const;
virtual ~Restaurant();
//color inherited from Landmark
//name inherited from Landmark
private:
//string m_name; No class may have a data member whose value is identical for every object of a particular class type
int m_cap;
//Landmark *lm;
};
//Hospital declaration
class Hospital : public Landmark
{
public:
Hospital(string name);
virtual string icon() const;
virtual string color() const;
virtual ~Hospital();
//name inherited from Landmark
private:
//string m_name; No class may have a data member whose value is identical for every object of a particular class type
//Landmark *lm;
};
//Landmark implementation
Landmark::Landmark(string name)
: m_name(name)
{}
Landmark::~Landmark()
{
/*
string lm;
if (m_landmark->icon() == "H")
lm = "hospital";
else if (m_landmark->icon() == "bed")
lm = "hotel";
else lm = "restaurant";
*/
}
string Landmark::name() const
{
return m_name;
}
string Landmark::color() const
{
return "yellow";
}
//Hotel implementation
Hotel::Hotel(string name)
: Landmark(name)
{
//cerr << "hotel constructor called" << endl;
//lm = new Hotel(name);
}
string Hotel::icon() const
{
return "bed";
}
Hotel::~Hotel()
{
//cout << "Destroying the " << "hotel" << " " << lm->name() << endl;
cout << "Destroying the hotel " << name() << "." << endl; //or Landmark::name()?
}
//Restaurant implementation
Restaurant::Restaurant(string name, int cap)
: Landmark(name), m_cap(cap)
{}
string Restaurant::icon() const
{
if (m_cap < 40)
return "small knife/fork";
else
return "large knife/fork";
}
Restaurant::~Restaurant()
{
//cout << "Destroying the " << "restaurant" << " " << lm->name() << endl;
cout << "Destroying the restaurant " << name() << "." << endl;
}
//Hospital implementation
Hospital::Hospital(string name)
: Landmark(name)
{}
string Hospital::icon() const
{
return "H";
}
string Hospital::color() const
{
return "blue";
}
Hospital::~Hospital()
{
//cout << "Destroying the " << "hospital" << " " << lm->name() << endl;
cout << "Destroying the hospital " << name() << "." << endl;
}
/*
void display(const Landmark* lm)
{
cout << "Display a " << lm->color() << " " << lm->icon() << " icon for "
<< lm->name() << "." << endl;
}
int main()
{
Landmark* landmarks[4];
landmarks[0] = new Hotel("Westwood Rest Good");
// Restaurants have a name and seating capacity. Restaurants with a
// capacity under 40 have a small knife/fork icon; those with a capacity
// 40 or over have a large knife/fork icon.
landmarks[1] = new Restaurant("Bruin Bite", 30);
landmarks[2] = new Restaurant("La Morsure de l'Ours", 100);
landmarks[3] = new Hospital("UCLA Medical Center");
cout << "Here are the landmarks." << endl;
for (int k = 0; k < 4; k++)
display(landmarks[k]);
// Clean up the landmarks before exiting
cout << "Cleaning up." << endl;
for (int k = 0; k < 4; k++)
delete landmarks[k];
}
//*/ |
e3d478b76775568e0cc0db0e3ab0fd05a669acfd | 9e3078c8dfce7499dd39a5fcb1aaca203db5a177 | /libraries/LightSensor/LightSensor.cpp | 8fb79aaa5fe72679b9fd56378af294a16e166b18 | [] | no_license | JSisques/Garden.ia | 8f806787a069d6daaf55b5db19de8366e37b4307 | 4afac101e678d40050773480d46af56bd6c4d8ad | refs/heads/master | 2023-05-29T12:19:48.581813 | 2021-06-11T15:42:36 | 2021-06-11T15:42:36 | 376,063,628 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | cpp | LightSensor.cpp | #include "Arduino.h"
#include "LightSensor.h"
LightSensor::LightSensor(String inputPin){
pin = inputPin;
}
void LightSensor::setPin(String inputPin){
pin = inputPin;
}
void LightSensor::setLight(int inputLight){
light = inputLight;
}
String LightSensor::getPin(){
return pin;
}
int LightSensor::getLight(){
return light;
}
void LightSensor::checkLight(){
light = analogRead(pin);
} |
98dcd5b71235598c00daad38518b5c5eb74bea66 | bfc88535fa1495c64672f048a5559e8bb6de1ae1 | /CF/ACM Tishreen 2017/k.cpp | 17762be2dd33d1afb0f1b07cfc212dfa4c344f49 | [] | no_license | famus2310/CP | 59839ffe23cf74019e2f655f49af224390846776 | d8a77572830fb3927de92f1e913ee729d04865e1 | refs/heads/master | 2021-07-05T00:23:31.113026 | 2020-08-07T22:28:24 | 2020-08-07T22:28:24 | 144,426,214 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,358 | cpp | k.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, pair<int, int> > piii;
#define pb push_back
#define debug(x) cout << x << endl
#define fastio ios_base::sync_with_stdio(0), cin.tie(0)
#define PI acos(-1)
#define all(c) c.begin(), c.end()
#define SET(x, y) memset((x), y, sizeof(x))
const int MOD = 1e9 + 7;
const int INF = 1e9 + 5;
const LL INF64 = 1e18;
const int N = 1e5 + 5;
LL dp[55][55]; //start, length
LL prefix[55];
LL s[55];
string inp;
int main() {
int t;
scanf("%d", &t);
while (t--) {
SET(dp, 0);
prefix[0] = 0;
cin >> inp;
int sz = inp.size();
for (int i = 1; i <= sz; i++) {
s[i] = inp[i - 1] - '0';
prefix[i] = prefix[i - 1] + s[i];
}
for (int i = 1; i <= sz; i++) {
dp[i][0] = 1;
dp[i][1] = 1;
}
for (int i = 2; i <= sz; i++) {
for (int j = 1; j + i - 1 <= sz; j++) {
dp[j][i] = 1;
int rg = j;
int lf = j + i - 1;
for (int k = rg; k < lf; k++) {
for (int l = lf; l > rg; l--) {
if (l <= k)
break;
LL sumlf = prefix[lf] - prefix[l - 1];
LL sumrg = prefix[k] - prefix[rg - 1];
if (sumlf == sumrg)
dp[j][i] = (dp[j][i] + dp[k + 1][l - k - 1]) % MOD;
// cout << k << " " << l << " : " << dp[j][i] << " ";
}
}
}
}
printf("%lld\n", dp[1][sz]);
}
return 0;
}
|
3803e970cd277691754b54167e586e0a4702b6f7 | 6eb9e9609de1e2ca05867783c109f919477a32e1 | /src/UuDriver.cpp | 24a6e27b33f0ec0c8d440fbeebed04166a9a71ce | [] | no_license | stijn-volckaert/udemo | 0afbfc847e45fe0a1bacc949841c345b2b312d91 | f01edd6d7472ea1de4d52f9554086e139df5e0f2 | refs/heads/master | 2023-08-31T17:59:05.899264 | 2023-08-11T16:06:40 | 2023-08-11T16:06:40 | 74,786,332 | 8 | 3 | null | 2023-09-05T19:00:12 | 2016-11-25T20:28:25 | UnrealScript | UTF-8 | C++ | false | false | 29,538 | cpp | UuDriver.cpp | /*=============================================================================
UuDriver.cpp: Advanced Demo Driver
Revision history:
* Created by UsAaR33
* Anth: Cleaned up, made some cross-platform modifications
* Anth: Added Level.TimeSecond syncing (gets screwed when demo pauses)
* Anth: Added illegal actor cleanup (fixes UTDC crash)
TODO:
* Anth: Add Pure Hidden flag fix here.
=============================================================================*/
/*-----------------------------------------------------------------------------
Includes/Definitions
-----------------------------------------------------------------------------*/
#include "udemoprivate.h"
/*-----------------------------------------------------------------------------
Globals
-----------------------------------------------------------------------------*/
ULinkerLoad* Linker = NULL;
/*-----------------------------------------------------------------------------
Constructor
-----------------------------------------------------------------------------*/
UuDemoDriver::UuDemoDriver()
{
/*UuDemoPackageMap* DemoPackageMap = new UuDemoPackageMap;
delete MasterMap;
MasterMap = DemoPackageMap;*/
}
/*-----------------------------------------------------------------------------
StaticConstructor
-----------------------------------------------------------------------------*/
void UuDemoDriver::StaticConstructor()
{
guard(UuDemoDriver::StaticConstructor);
new(GetClass(),TEXT("DemoSpectatorClass"), RF_Public)UStrProperty(CPP_PROPERTY(DemoSpectatorClass), TEXT("Client"), CPF_Config);
unguard;
}
/*-----------------------------------------------------------------------------
TimeSync - (Anth) Synchronizes time between demo and game after every packet
read from the demo! Also works while seeking/slomo and when the game is paused
-----------------------------------------------------------------------------*/
void UuDemoDriver::TimeSync(FTime NewTime, FTime OldTime)
{
guard(UuDemoDriver::TimeSync);
if (ServerConnection &&
Notify &&
GetLevel() &&
GetLevel()->GetLevelInfo() &&
Interface &&
Interface->DemoSpec &&
Interface->DemoSpec->GameReplicationInfo)
{
// disable stock counter
Interface->DemoSpec->GameReplicationInfo->SecondCount = GetLevel()->GetLevelInfo()->TimeSeconds + LTS_OFFSET;
if (GetLevel()->GetLevelInfo()->Pauser == TEXT(""))
{
// next code based on GameReplicationInfo uscript code with some changes
if (ServerPacketTime - GameTime >= 1.0)
{
Interface->DemoSpec->GameReplicationInfo->ElapsedTime++;
if (Interface->DemoSpec->GameReplicationInfo->RemainingMinute != 0)
{
Interface->DemoSpec->GameReplicationInfo->RemainingTime = Interface->DemoSpec->GameReplicationInfo->RemainingMinute;
Interface->DemoSpec->GameReplicationInfo->RemainingMinute = 0;
}
if (Interface->DemoSpec->GameReplicationInfo->RemainingTime > 0 && !Interface->DemoSpec->GameReplicationInfo->bStopCountDown)
Interface->DemoSpec->GameReplicationInfo->RemainingTime--;
GameTime += 1.0;
}
}
else
{
// Prevent time goes during pause by server (client pause not change ServerPacketTime, so ignored)
if (!Paused)
GameTime += NewTime - OldTime;
}
}
unguard;
}
/*-----------------------------------------------------------------------------
TickDispatch - Tick the netdriver and the demospec etc! Read packets from
the ServerConnection and process them
-----------------------------------------------------------------------------*/
void UuDemoDriver::TickDispatch( FLOAT Delta )
{
guard(UuDemoDriver:TickDispatch);
// rollback seconds spent to seeking demo
if (Interface && Interface->bFixLevelTime)
{
Interface->bFixLevelTime = FALSE;
if (Interface->DemoSpec)
Interface->DemoSpec->XLevel->TimeSeconds += -Delta*Interface->DemoSpec->Level->TimeDilation;
Delta = 0;
}
// Calc deltatime
FLOAT DeltaTime = Delta;
if(ServerConnection)
{
if (!NoFrameCap)
DeltaTime*=Speed; //alter speed!
if (Paused)
{
if (Interface)
{
FLOAT DeltaSeconds = Delta*Interface->DemoSpec->Level->TimeDilation;
Interface->DemoSpec->Tick(DeltaSeconds, LEVELTICK_All);
TimeSync(ServerPacketTime, ServerPacketTime);
}
return;
}
}
// update netdriver
UNetDriver::TickDispatch( DeltaTime );
FrameNum++;
if (!ServerConnection)
return;
//hack
if (bNoTick)
{
FrameNum--;
return;
}
UBOOL CheckTime = (ServerConnection->State == USOCK_Pending); //true if should set starttime
BYTE Data[520]; //512+8
FTime OldTime;
int oldFrame;
if(ServerConnection->State==USOCK_Pending || ServerConnection->State==USOCK_Open )
{
// Read data from the demo file
DWORD PacketBytes;
INT PlayedThisTick = 0;
for( ; ; )
{
// At end of file?
if( FileAr->AtEnd() || FileAr->IsError() )
{
AtEnd:
ServerConnection->State = USOCK_Closed;
DemoEnded = 1;
if (FileAr->IsError())
debugf(TEXT("udemo: This demo is corrupt!"));
//detatch demo link!
if (FileAr)
{
delete FileAr;
FileAr = NULL;
}
if( Loop || MessagePlay)
GetLevel()->Exec( *FString::Printf(TEXT("DEMOPLAY \"%ls\""), *LoopURL.String()), *GLog );
return;
}
// Update frames and time
oldFrame = ServerFrameNum;
OldTime = ServerPacketTime;
*FileAr << ServerFrameNum;
*FileAr << ServerPacketTime;
if(!MessagePlay && ((!TimeBased && ServerFrameNum > FrameNum) || (TimeBased && ServerPacketTime > Time)))
{
if(CheckTime && ServerConnection->State == USOCK_Pending)
StartTime = ServerPacketTime; //set start to packet after welcome?
FileAr->Seek(FileAr->Tell() - sizeof(ServerFrameNum) - sizeof(ServerPacketTime));
ServerPacketTime = OldTime;
ServerFrameNum = oldFrame;
if (NoFrameCap && !TimeBased) //sync time
Time = OldTime;
else if (TimeBased) //sync frames (only for transitions)
FrameNum=oldFrame;
break;
}
if(!MessagePlay && !NoFrameCap && !TimeBased && ServerPacketTime > Time)
{
// Busy-wait until it's time to play the frame.
// WARNING: use appSleep() if appSeconds() isn't using CPU timestamp!
// appSleep(ServerPacketTime - Time);
appSleepLong(ServerPacketTime - Time);
}
//sync level time with demo!
else if (NoFrameCap && GetLevel() && GetLevel()->GetLevelInfo() )
GetLevel()->GetLevelInfo()->TimeDilation = RealDilation+(ServerPacketTime - Time);
//alter timedilation with nofcap here!!!!
*FileAr << PacketBytes;
//stops crashes on truncated demos:
if ((FileAr->Tell() + PacketBytes) > (unsigned int) FileAr->TotalSize())
goto AtEnd;
// Read data from file.
FileAr->Serialize( Data, PacketBytes );
if( FileAr->IsError() )
{
debugf( NAME_DevNet, TEXT("Failed to read demo file packet") );
goto AtEnd;
}
// Update stats.
if( PacketBytes )
PlayedThisTick++;
// Process incoming packet.
float oldDilation = 0.0;
if (GetLevel() && GetLevel()->GetLevelInfo())
oldDilation = GetLevel()->GetLevelInfo()->TimeDilation;
UPlayer* OldPlayer = NULL;
if (SoundPlayer)
{
OldPlayer = SoundPlayer->Player;
SoundPlayer->Player = GetLevel()->Engine->Client->Viewports(0);
if (OldPlayer == SoundPlayer->Player) // pass actual viewport to tick loop can destroy input
OldPlayer = NULL;
}
// (Anth) Being called in normal playback mode...
CheckActors();
UuReceivedRawPacket( Data, PacketBytes );
TimeSync(ServerPacketTime, OldTime);
if (SoundPlayer)
SoundPlayer->Player = OldPlayer;
if (GetLevel() && GetLevel()->GetLevelInfo() && Abs(GetLevel()->GetLevelInfo()->TimeDilation-oldDilation) >0.01)
{
RealDilation=GetLevel()->GetLevelInfo()->TimeDilation;
if (!NoFrameCap)
GetLevel()->GetLevelInfo()->TimeDilation*=Speed;
}
if (MessagePlay && Interface)
Interface->eventNetPacketReceived(); //notify new packet!
// Only play one packet per tick on demo playback, until we're
// fully connected. This is like the handshake for net play.
if(ServerConnection->State == USOCK_Pending)
break;
}
}
// call event PreTick
if (Interface)
{
FLOAT DeltaSeconds = Delta*Interface->DemoSpec->Level->TimeDilation;
Interface->DemoSpec->eventPlayerTick(-DeltaSeconds);
}
unguard;
}
/*-----------------------------------------------------------------------------
CheckActors - (Anth) Uber lame hack to disable illegal actors
-----------------------------------------------------------------------------*/
void UuDemoDriver::CheckActors()
{
// disabled for 469 (which can fix actor issues on the engine side)
}
/*-----------------------------------------------------------------------------
ReceivedRawPacket
-----------------------------------------------------------------------------*/
void UuDemoDriver::UuReceivedRawPacket(void* InData, INT Count)
{
BYTE* Data = (BYTE*)InData;
ServerConnection->InByteAcc += Count + ServerConnection->PacketOverhead;
ServerConnection->InPktAcc++;
if (Count > 0)
{
BYTE LastByte = Data[Count - 1];
if (LastByte)
{
INT BitSize = Count * 8 - 1;
while (!(LastByte & 0x80))
{
LastByte *= 2;
BitSize--;
}
FBitReader Reader(Data, BitSize);
UuReceivedPacket(Reader);
}
}
}
/*-----------------------------------------------------------------------------
ReceivedPacket
-----------------------------------------------------------------------------*/
void UuDemoDriver::UuReceivedPacket(FBitReader& Reader)
{
if (Reader.IsError())
return;
if (!ServerConnection->Channels[0] || !ServerConnection->Channels[0]->Closing)
ServerConnection->LastReceiveTime = Time;
const INT PacketId = MakeRelative(Reader.ReadInt(MAX_PACKETID), ServerConnection->InPacketId, MAX_PACKETID);
if (PacketId > ServerConnection->InPacketId)
{
ServerConnection->InLossAcc += PacketId - ServerConnection->InPacketId - 1;
ServerConnection->InPacketId = PacketId;
}
else ServerConnection->InOrdAcc++;
ServerConnection->SendAck(PacketId);
while (!Reader.AtEnd() && ServerConnection->State != USOCK_Closed)
{
UBOOL IsAck = Reader.ReadBit();
if (Reader.IsError())
return;
if (IsAck)
{
INT AckPacketId = MakeRelative(Reader.ReadInt(MAX_PACKETID), ServerConnection->OutAckPacketId, MAX_PACKETID);
if (Reader.IsError())
return;
if (AckPacketId > ServerConnection->OutAckPacketId)
{
for (INT NakPacketId = ServerConnection->OutAckPacketId + 1; NakPacketId < AckPacketId; NakPacketId++, ServerConnection->OutLossAcc++)
ServerConnection->ReceivedNak(NakPacketId);
ServerConnection->OutAckPacketId = AckPacketId;
}
for (INT i = ServerConnection->OpenChannels.Num() - 1; i >= 0; i--)
{
UChannel* Channel = ServerConnection->OpenChannels(i);
for (FOutBunch* Out = Channel->OutRec; Out; Out = Out->Next)
{
if (Out->PacketId == AckPacketId)
{
Out->ReceivedAck = 1;
if (Out->bOpen)
Channel->OpenAcked = 1;
}
}
if (Channel->OpenPacketId == AckPacketId)
Channel->OpenAcked = 1;
Channel->ReceivedAcks();
}
}
else
{
FInBunch Bunch(ServerConnection);
BYTE bControl = Reader.ReadBit();
Bunch.PacketId = PacketId;
Bunch.bOpen = bControl ? Reader.ReadBit() : 0;
Bunch.bClose = bControl ? Reader.ReadBit() : 0;
Bunch.bReliable = Reader.ReadBit();
Bunch.ChIndex = Reader.ReadInt(UNetConnection::MAX_CHANNELS);
Bunch.ChSequence = Bunch.bReliable ? MakeRelative(Reader.ReadInt(MAX_CHSEQUENCE), ServerConnection->InReliable[Bunch.ChIndex], MAX_CHSEQUENCE) : 0;
Bunch.ChType = (Bunch.bReliable || Bunch.bOpen) ? Reader.ReadInt(CHTYPE_MAX) : CHTYPE_None;
INT BunchDataBits = Reader.ReadInt(ServerConnection->MaxPacket * 8);
if (Reader.IsError())
return;
Bunch.SetData(Reader, BunchDataBits);
if (Reader.IsError())
return;
if (!ServerConnection->Channels[Bunch.ChIndex] && !ServerConnection->Channels[0] && (Bunch.ChIndex != 0 || Bunch.ChType != CHTYPE_Control))
return;
UChannel* Channel = ServerConnection->Channels[Bunch.ChIndex];
// stijn: demo manager hax. Do not create actor channels for bNetTemporary actors if we're just seeking
if (Seeking && !Bunch.bReliable /*&& !Channel*/)
continue;
if (Bunch.bReliable && Bunch.ChSequence <= ServerConnection->InReliable[Bunch.ChIndex])
continue;
if (!Bunch.bReliable && (!Bunch.bOpen || !Bunch.bClose) && (!Channel || Channel->OpenPacketId == INDEX_NONE))
continue;
if (!Channel)
{
if (!UChannel::IsKnownChannelType(Bunch.ChType))
return;
Channel = ServerConnection->CreateChannel((EChannelType)Bunch.ChType, 0, Bunch.ChIndex);
if (!Notify->NotifyAcceptingChannel(Channel))
{
FOutBunch CloseBunch(Channel, 1);
check(!CloseBunch.IsError());
check(CloseBunch.bClose);
CloseBunch.bReliable = 1;
Channel->SendBunch(&CloseBunch, 0);
ServerConnection->FlushNet();
delete Channel;
if (Bunch.ChIndex == 0)
ServerConnection->State = USOCK_Closed;
continue;
}
// anth: TODO: check for illegal actor channels here maybe?
}
if (Bunch.bOpen)
{
Channel->OpenAcked = 1;
Channel->OpenPacketId = PacketId;
}
Channel->ReceivedRawBunch(Bunch);
ServerConnection->InBunAcc++;
}
}
}
/*-----------------------------------------------------------------------------
GetLevel - Not used?
-----------------------------------------------------------------------------*/
ULevel* UuDemoDriver::GetLevel()
{
guard(UuDemoDriver::GetLevel);
check(Notify);
return Notify->NotifyGetLevel();
unguard;
}
/*-----------------------------------------------------------------------------
ReadTo - Reads to just before this time
-----------------------------------------------------------------------------*/
FTime UuDemoDriver::ReadTo(FTime GoalTime, UBOOL bPacketRead)
{
guard(UuDemoDriver::ReadTo);
int seekTo;
DWORD PacketBytes;
FTime OldTime;
FTime OffsetTime = GetLevel() ? GetLevel()->TimeSeconds : FTime(0.0);
FTime BaseTime = ServerPacketTime;
int oldFrame;
BYTE Data[520]; //512+8
check(ServerConnection);
Seeking = TRUE;
while (!FileAr->AtEnd() && !FileAr->IsError() )
{
oldFrame = ServerFrameNum;
OldTime = ServerPacketTime;
*FileAr << ServerFrameNum;
if (FileAr->AtEnd() || FileAr->IsError())
{
debugf(TEXT("udemo: seekto failed - requested %lf - now at %lf - atend %d - iserror %d"), GoalTime.GetDouble(), ServerPacketTime.GetDouble(), FileAr->AtEnd(), FileAr->IsError());
Seeking = FALSE;
return ServerPacketTime;
}
*FileAr << ServerPacketTime;
if (FileAr->AtEnd() || FileAr->IsError())
{
debugf(TEXT("udemo: seekto failed - requested %lf - now at %lf - atend %d - iserror %d"), GoalTime.GetDouble(), ServerPacketTime.GetDouble(), FileAr->AtEnd(), FileAr->IsError());
Seeking = FALSE;
return ServerPacketTime;
}
if(ServerPacketTime > GoalTime)
{
FTime OutTime = ServerPacketTime;
FileAr->Seek(FileAr->Tell() - sizeof(ServerFrameNum) - sizeof(ServerPacketTime));
if (bPacketRead){ //otherwise, readto is exact time!
ServerPacketTime = OldTime;
ServerFrameNum = oldFrame;
}
Time = ServerPacketTime; //synch everything on jumps!
FrameNum=ServerFrameNum;
// debugf(TEXT("udemo: seekto succeeded - requested %lf - now at %lf - atend %d - iserror %d"), GoalTime.GetDouble(), ServerPacketTime.GetDouble(), FileAr->AtEnd(), FileAr->IsError());
Seeking = FALSE;
return OutTime;
}
*FileAr << PacketBytes;
if (FileAr->AtEnd() || FileAr->IsError())
{
debugf(TEXT("udemo: seekto failed - requested %lf - now at %lf - atend %d - iserror %d"), GoalTime.GetDouble(), ServerPacketTime.GetDouble(), FileAr->AtEnd(), FileAr->IsError());
Seeking = FALSE;
return ServerPacketTime;
}
seekTo=FileAr->Tell() + PacketBytes;
if (seekTo>FileAr->TotalSize()) //stops crashes on truncated demos
{
debugf(TEXT("udemo: seekto failed - possible truncated demo - requested %lf - now at %lf - atend %d - iserror %d"), GoalTime.GetDouble(), ServerPacketTime.GetDouble(), FileAr->AtEnd(), FileAr->IsError());
Seeking = FALSE;
return ServerPacketTime;
}
// update TimeSeconds - can be used by some mods
if (GetLevel())
{
GetLevel()->TimeSeconds = OffsetTime + (ServerPacketTime - BaseTime)*RealDilation;
if (GetLevel()->GetLevelInfo())
GetLevel()->GetLevelInfo()->TimeSeconds = GetLevel()->TimeSeconds.GetFloat();
}
if (!bPacketRead)
FileAr->Seek(seekTo); //move ahead by packetbytes
else
{
TimeSync(ServerPacketTime, OldTime);
FileAr->Serialize( Data, PacketBytes );
FLOAT oldDilation = 0.0;
if (GetLevel() && GetLevel()->GetLevelInfo())
oldDilation = GetLevel()->GetLevelInfo()->TimeDilation;
ServerConnection->ReceivedRawPacket( Data, PacketBytes );
if (GetLevel() && GetLevel()->GetLevelInfo() && Abs(GetLevel()->GetLevelInfo()->TimeDilation - oldDilation) > 0.01)
{
OffsetTime = GetLevel()->TimeSeconds;
BaseTime = ServerPacketTime;
RealDilation = GetLevel()->GetLevelInfo()->TimeDilation;
if (!NoFrameCap)
GetLevel()->GetLevelInfo()->TimeDilation *= Speed;
}
}
}
debugf(TEXT("udemo: seekto failed - requested %lf - now at %lf - atend %d - iserror %d"), GoalTime.GetDouble(), ServerPacketTime.GetDouble(), FileAr->AtEnd(), FileAr->IsError());
Seeking = FALSE;
return ServerPacketTime;
unguard;
}
/*-----------------------------------------------------------------------------
getTime
-----------------------------------------------------------------------------*/
void UuDemoDriver::getTime()
{
guard(UuDemoDriver::getTime);
int seekTo;
int oldPos = FileAr->Tell();
DWORD PacketBytes;
while (!FileAr->AtEnd() && !FileAr->IsError() ){ //loop until done
*FileAr << TotalFrames;
if (FileAr->AtEnd() || FileAr->IsError())
break;
*FileAr << TotalTime;
// GLog->Logf(TEXT("time is %f"),ftime.GetFloat());
if (FileAr->AtEnd() || FileAr->IsError())
break;
*FileAr << PacketBytes;
if (FileAr->AtEnd() || FileAr->IsError())
break;
seekTo=FileAr->Tell() + PacketBytes;
if (seekTo>FileAr->TotalSize()) //stops crashes on truncated demos
break;
FileAr->Seek(seekTo); //move ahead by packetbytes
}
FileAr->Seek(oldPos);
unguard;
}
/*-----------------------------------------------------------------------------
InitConnect - Connect with extra options
-----------------------------------------------------------------------------*/
UBOOL UuDemoDriver::InitConnect( FNetworkNotify* InNotify, FURL& ConnectURL, FString& Error )
{
guard(UuDemoDriver::InitConnect);
if (ConnectURL==TEXT("")) //supa-hack!!!!!!!
return 0;
if( !UNetDriver::InitConnect( InNotify, ConnectURL, Error ) )
return 0;
if( !InitBase( 1, InNotify, ConnectURL, Error ) )
return 0;
Speed=1;
RealDilation=1;
// Playback, local machine is a client, and the demo stream acts "as if" it's the server.
ServerConnection = new UuDemoConnection( this, ConnectURL );
ServerConnection->CurrentNetSpeed = 0x7fffffff;
ServerConnection->State = USOCK_Pending;
// Start stream
FileAr = GFileManager->CreateFileReader( *DemoFilename );
if( !FileAr )
{
Error = FString::Printf( TEXT("Couldn't open demo file %s for reading"), *DemoFilename );//!!localize!!
return 0;
}
getTime(); //figure out the time
if (FileAr->IsError())
{
// maybe it's just truncated. Try to recover
delete FileAr;
FileAr = GFileManager->CreateFileReader(*DemoFilename);
if (!FileAr)
{
Error = FString::Printf(TEXT("Couldn't open demo file %s for reading"), *DemoFilename);//!!localize!!
return 0;
}
}
LoopURL = ConnectURL;
Want3rdP = ConnectURL.HasOption(TEXT("3rdperson"));
TimeBased = ConnectURL.HasOption(TEXT("timebased"));
NoFrameCap = ConnectURL.HasOption(TEXT("noframecap"));
if (NoFrameCap) //can't have both!!!!!
TimeBased = false;
Loop = ConnectURL.HasOption(TEXT("loop"));
MessagePlay = ConnectURL.HasOption(TEXT("messageread"));
if (MessagePlay)
LoopURL.Op.RemoveItem(TEXT("messageread")); //hack
return 1;
unguard;
}
/*-----------------------------------------------------------------------------
UuDemoConnection
-----------------------------------------------------------------------------*/
UuDemoConnection::UuDemoConnection(UNetDriver* InDriver, FURL& InURL)
: UDemoRecConnection(InDriver, InURL)
{
/*UuDemoPackageMap* DemoPackageMap = new(this) UuDemoPackageMap(this);
delete PackageMap;
PackageMap = DemoPackageMap;*/
}
/*-----------------------------------------------------------------------------
GetDemoDriver
-----------------------------------------------------------------------------*/
UuDemoDriver* UuDemoConnection::GetDemoDriver() //new driver reading
{
return (UuDemoDriver *)Driver;
}
/*-----------------------------------------------------------------------------
HandleClientPlayer
-----------------------------------------------------------------------------*/
void UuDemoConnection::HandleClientPlayer( APlayerPawn* Pawn )
{
guard(UAdvancedConnection::HandleClientPlayer);
UViewport* Viewport = NULL;
UClass* C = StaticLoadClass(AActor::StaticClass(), NULL, TEXT("Engine.DemoRecSpectator"), NULL, LOAD_NoFail, NULL);
if (C && Pawn->IsA(C) && !GetDriver()->ClientThirdPerson)
return;
if (GetDemoDriver()->ClientHandled)
{
if (!GetDriver()->ClientThirdPerson) //when not server demo!
GetDemoDriver()->SoundPlayer = Pawn;
GetDemoDriver()->Interface->eventLinkToPlayer(GetDemoDriver()->SoundPlayer,!GetDemoDriver()->Want3rdP&&GetDemoDriver()->SoundPlayer); //give pawn reference!
Pawn = GetDemoDriver()->Interface->DemoSpec;
State = USOCK_Open;
return;
}
GetDemoDriver()->ClientHandled = true;
guard(SpawnSpectator);
UClass* SpectatorClass = StaticLoadClass( APawn::StaticClass(), NULL, TEXT("udemo.DemoPlaybackSpec"), NULL, LOAD_NoFail, NULL );
check(SpectatorClass);
FVector Location(0,0,0);
FRotator Rotation(0,0,0);
guard(FindPlayerStart);
for( INT i=0; i<Pawn->XLevel->Actors.Num(); i++ )
{
if( Pawn->XLevel->Actors(i) && Pawn->XLevel->Actors(i)->IsA(APlayerStart::StaticClass()) )
{
Location = Pawn->XLevel->Actors(i)->Location;
Rotation = Pawn->XLevel->Actors(i)->Rotation;
break;
}
}
unguard;
guard(SpawnDemoSpectator);
GetDemoDriver()->SoundPlayer = NULL;
if (!GetDriver()->ClientThirdPerson) //when not server demo!
GetDemoDriver()->SoundPlayer = Pawn;
Pawn = CastChecked<APlayerPawn>(Pawn->XLevel->SpawnActor( SpectatorClass, NAME_None, NULL, NULL, Location, Rotation, NULL, 1, 0 ));
check(Pawn);
check(Pawn->XLevel->Engine->Client);
check(Pawn->XLevel->Engine->Client->Viewports.Num());
guard(AssignPlayer);
Viewport = Pawn->XLevel->Engine->Client->Viewports(0);
Viewport->Actor->Player = NULL;
Pawn->SetPlayer( Viewport );
check (Pawn->Player);
Viewport->Actor->Role = ROLE_Authority;
Viewport->Actor->ShowFlags = SHOW_Backdrop | SHOW_Actors | SHOW_PlayerCtrl | SHOW_RealTime;
Viewport->Actor->RendMap = REN_DynLight;
Pawn->bNetOwner = 1;
Pawn->Physics = PHYS_Flying;
Viewport->Input->ResetInput();
//generate the interface object:
guard(MakeInterface);
UClass* DemoDriverClass = StaticLoadClass( UObject::StaticClass(), NULL, TEXT("udemo.DemoInterface"), NULL, LOAD_NoFail, NULL );
GetDemoDriver()->Interface = (UDemoInterface*)ConstructObject<UObject>( DemoDriverClass );
check(GetDemoDriver()->Interface);
GetDemoDriver()->Interface->DemoDriver=GetDemoDriver();
GetDemoDriver()->Interface->DemoSpec=Pawn; //BE SURE THIS IS THE SPAWNED PAWN!!!!
if (!GetDemoDriver()->TimeBased)
{
if (GetDemoDriver()->NoFrameCap)
GetDemoDriver()->Interface->PlayBackMode=2;
else
GetDemoDriver()->Interface->PlayBackMode=1;
}
else
GetDemoDriver()->Interface->PlayBackMode=0;
GetDemoDriver()->Interface->bDoingMessagePlay = GetDemoDriver()->MessagePlay;
GetDemoDriver()->Interface->mySpeed=1;
GetDemoDriver()->Interface->eventLinkToPlayer(GetDemoDriver()->SoundPlayer,!GetDemoDriver()->Want3rdP&&GetDemoDriver()->SoundPlayer); //give pawn reference!
unguard;
unguard;
unguard;
unguard;
// Mark this connection as open.
State = USOCK_Open;
Viewport->Actor->Song = Pawn->Level->Song;
Viewport->Actor->SongSection = Pawn->Level->SongSection;
Viewport->Actor->CdTrack = Pawn->Level->CdTrack;
Viewport->Actor->Transition = MTRAN_Fade;
check(Pawn->XLevel->Engine->Client);
check(Pawn->XLevel->Engine->Client->Viewports.Num());
unguard;
}
/*-----------------------------------------------------------------------------
UuDemoRecPackageMap
-----------------------------------------------------------------------------*/
void UuDemoPackageMap::Compute()
{
guard(UuDemoPackageMap::Compute);
for (INT i = 0; i < List.Num(); i++)
check(List(i).Linker);
NameIndices.Empty(FName::GetMaxNames());
NameIndices.Add(FName::GetMaxNames());
for (INT i = 0; i < NameIndices.Num(); i++)
NameIndices(i) = -1;
LinkerMap.Empty();
MaxObjectIndex = 0;
MaxNameIndex = 0;
//FString Ver = UTexture::__Client->Viewports(0)->Actor->Level->EngineVersion;
//INT iVer = strtol(TCHAR_TO_ANSI(*Ver), NULL, 10);
{for (INT i = 0; i < List.Num(); i++)
{
FPackageInfo& Info = List(i);
Info.ObjectBase = MaxObjectIndex;
Info.NameBase = MaxNameIndex;
Info.ObjectCount = Info.Linker->ExportMap.Num();
Info.NameCount = Info.Linker->NameMap.Num();
TArray<FGenerationInfo>* Generations = &Linker->Summary.Generations;
Info.LocalGeneration = Generations->Num();
if (Info.RemoteGeneration == 0)
Info.RemoteGeneration = Info.LocalGeneration;
Info.RemoteGeneration = LookupDemoGeneration(Info);
if (Info.RemoteGeneration < Info.LocalGeneration)
{
Info.ObjectCount = Min(Info.ObjectCount, (*Generations)(Info.RemoteGeneration - 1).ExportCount);
Info.NameCount = Min(Info.NameCount, (*Generations)(Info.RemoteGeneration - 1).NameCount);
Info.LocalGeneration = Info.RemoteGeneration;
}
MaxObjectIndex += Info.ObjectCount;
MaxNameIndex += Info.NameCount;
for (INT j = 0; j < Min(Info.Linker->NameMap.Num(), Info.NameCount); j++)
if (NameIndices(Info.Linker->NameMap(j).GetIndex()) == -1)
NameIndices(Info.Linker->NameMap(j).GetIndex()) = Info.NameBase + j;
LinkerMap.Set(Info.Linker, i);
}}
unguard;
}
INT UuDemoPackageMap::LookupDemoGeneration(FPackageInfo& PackageInfo)
{
// Botpack
if (PackageInfo.Guid == FGuid(0x1c696576, 0x11d38f44, 0x100067b9, 0xf6f8975a))
return 14;
// Core
if (PackageInfo.Guid == FGuid(0x4770b884, 0x11d38e3e, 0x100067b9, 0xf6f8975a))
return 10;
// Editor
if (PackageInfo.Guid == FGuid(0x4770b886, 0x11d38e3e, 0x100067b9, 0xf6f8975a))
return 11;
// Engine
if (PackageInfo.Guid == FGuid(0xd18a7b92, 0x11d38f04, 0x100067b9, 0xf6f8975a))
return 17;
// Fire
if (PackageInfo.Guid == FGuid(0x4770b888, 0x11d38e3e, 0x100067b9, 0xf6f8975a))
return 10;
// IpDrv
if (PackageInfo.Guid == FGuid(0x4770b889, 0x11d38e3e, 0x100067b9, 0xf6f8975a))
return 10;
// IpServer
if (PackageInfo.Guid == FGuid(0x4770b88f, 0x11d38e3e, 0x100067b9, 0xf6f8975a))
return 11;
// UBrowser
if (PackageInfo.Guid == FGuid(0x4770b88b, 0x11d38e3e, 0x100067b9, 0xf6f8975a))
return 10;
// UTBrowser
if (PackageInfo.Guid == FGuid(0x4770b893, 0x11d38e3e, 0x100067b9, 0xf6f8975a))
return 10;
// UTMenu
if (PackageInfo.Guid == FGuid(0x1c696577, 0x11d38f44, 0x100067b9, 0xf6f8975a))
return 11;
// UTServerAdmin
if (PackageInfo.Guid == FGuid(0x4770b891, 0x11d38e3e, 0x100067b9, 0xf6f8975a))
return 10;
// UWeb
if (PackageInfo.Guid == FGuid(0x4770b88a, 0x11d38e3e, 0x100067b9, 0xf6f8975a))
return 10;
// UWindow
if (PackageInfo.Guid == FGuid(0x4770b887, 0x11d38e3e, 0x100067b9, 0xf6f8975a))
return 10;
// UnrealI
if (PackageInfo.Guid == FGuid(0x4770b88d, 0x11d38e3e, 0x100067b9, 0xf6f8975a))
return 1;
// UnrealShare
if (PackageInfo.Guid == FGuid(0x4770b88c, 0x11d38e3e, 0x100067b9, 0xf6f8975a))
return 1;
// De
if (PackageInfo.Guid == FGuid(0xfb1eb231, 0x4d8bf569, 0xae12c6bf, 0x1a08a2f7))
return 1;
// epiccustommodels
if (PackageInfo.Guid == FGuid(0x13f8255a, 0x11d3dba0, 0x1000cbb9, 0xf6f8975a))
return 2;
// multimesh
if (PackageInfo.Guid == FGuid(0x2db53b00, 0x11d3e900, 0x1000d3b9, 0xf6f8975a))
return 8;
// relics
if (PackageInfo.Guid == FGuid(0xd011f66e, 0x11d3e9b8, 0x1000d5b9, 0xf6f8975a))
return 9;
// relicsbindings
if (PackageInfo.Guid == FGuid(0x465ad1fe, 0x11d3df5c, 0x1000cdb9, 0xf6f8975a))
return 2;
return PackageInfo.RemoteGeneration;
}
/*-----------------------------------------------------------------------------
The End.
-----------------------------------------------------------------------------*/
|
b2f2970b0d593f4ba1c04099cbc3fa0786c94eb0 | 2edc8f86d8971d07f4cbf10072a44cf43170b17a | /pku/31/3123/3123.cc | 9a85ec1c5338bf7c22e50c02180159c5617f7641 | [] | no_license | nya3jp/icpc | b9527da381d6f9cead905b540541f03505eb79c3 | deb82dcdece5815e404f5ea33956d52a57e67158 | refs/heads/master | 2021-01-20T10:41:22.834961 | 2012-10-25T11:11:54 | 2012-10-25T11:19:37 | 4,337,683 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,165 | cc | 3123.cc | #include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <limits>
using namespace std;
#define REP(i,n) for(int i = 0; i < (int)(n); i++)
#define N 30
inline int lsb(int x) {
return x&-x;
}
inline int masked_inc(int x, int s) {
return (((x|~s)+1)&s);
}
map<string,int> ids;
int id(const string& s) {
if (ids.count(s) == 0)
ids.insert(make_pair(s, ids.size()));
return ids[s];
}
int adj[N][N];
const int INF = numeric_limits<int>::max()/4;
int main() {
for(;;) {
int n, m;
cin >> n >> m;
if (n == 0 && m == 0)
break;
ids.clear();
REP(i, n) {
string s;
cin >> s;
id(s);
}
REP(i, n) REP(j, n)
adj[i][j] = INF;
REP(i, n)
adj[i][i] = 0;
REP(i, m) {
string s1, s2;
int c;
cin >> s1 >> s2 >> c;
int k1 = id(s1), k2 = id(s2);
adj[k1][k2] <?= c;
adj[k2][k1] <?= c;
}
vector<int> targets;
REP(i, 8) {
string s;
cin >> s;
targets.push_back(id(s));
}
REP(j, n) REP(i, n) REP(k, n)
adj[i][k] <?= adj[i][j] + adj[j][k];
int dp[1<<8][N];
REP(i, 1<<8) REP(j, n)
dp[i][j] = INF;
REP(j, n)
dp[0][j] = 0;
REP(i, 8) REP(j, n)
dp[1<<i][j] = adj[targets[i]][j];
for(int p = 1; p < (1<<8); p++)
REP(l, n)
for(int q = lsb(p); q != 0; q = masked_inc(q, p))
REP(k, n)
dp[p][l] <?= dp[q][k] + dp[p^q][k] + adj[l][k];
int tree[1<<8];
REP(i, 1<<8)
tree[i] = INF;
REP(i, 1<<8) REP(j, n)
tree[i] <?= dp[i][j];
int res = INF;
res <?= tree[(3<<0)] + tree[(3<<2)] + tree[(3<<4)] + tree[(3<<6)];
res <?= tree[(3<<0)|(3<<2)] + tree[(3<<4)] + tree[(3<<6)];
res <?= tree[(3<<0)|(3<<4)] + tree[(3<<2)] + tree[(3<<6)];
res <?= tree[(3<<0)|(3<<6)] + tree[(3<<2)] + tree[(3<<4)];
res <?= tree[(3<<2)|(3<<4)] + tree[(3<<0)] + tree[(3<<6)];
res <?= tree[(3<<2)|(3<<6)] + tree[(3<<0)] + tree[(3<<4)];
res <?= tree[(3<<4)|(3<<6)] + tree[(3<<0)] + tree[(3<<2)];
res <?= tree[(3<<0)|(3<<2)] + tree[(3<<4)|(3<<6)];
res <?= tree[(3<<0)|(3<<4)] + tree[(3<<2)|(3<<6)];
res <?= tree[(3<<0)|(3<<6)] + tree[(3<<2)|(3<<4)];
res <?= tree[(3<<2)|(3<<4)] + tree[(3<<0)|(3<<6)];
res <?= tree[(3<<2)|(3<<6)] + tree[(3<<0)|(3<<4)];
res <?= tree[(3<<4)|(3<<6)] + tree[(3<<0)|(3<<2)];
res <?= tree[(3<<0)|(3<<2)|(3<<4)] + tree[(3<<6)];
res <?= tree[(3<<0)|(3<<2)|(3<<6)] + tree[(3<<4)];
res <?= tree[(3<<0)|(3<<4)|(3<<6)] + tree[(3<<2)];
res <?= tree[(3<<2)|(3<<4)|(3<<6)] + tree[(3<<0)];
res <?= tree[(1<<8)-1];
cout << res << endl;
}
return 0;
}
|
586b7bca3bc61cf786ce723415d85ebf8f668b80 | 0bcd128368e2de959ca648960ffd7944067fcf27 | /src/sksl/ir/SkSLSwizzle.cpp | 9ea4a5db0538cb505db0da675a856e3810b989f1 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | google/skia | ac6e39179cd33cf0c8a46d29c1a70bf78b4d74ee | bf6b239838d3eb56562fffd0856f4047867ae771 | refs/heads/main | 2023-08-31T21:03:04.620734 | 2023-08-31T18:24:15 | 2023-08-31T20:20:26 | 15,773,229 | 8,064 | 1,487 | BSD-3-Clause | 2023-09-11T13:42:07 | 2014-01-09T17:09:57 | C++ | UTF-8 | C++ | false | false | 23,423 | cpp | SkSLSwizzle.cpp | /*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/sksl/ir/SkSLSwizzle.h"
#include "include/core/SkSpan.h"
#include "include/private/base/SkTArray.h"
#include "src/sksl/SkSLAnalysis.h"
#include "src/sksl/SkSLConstantFolder.h"
#include "src/sksl/SkSLContext.h"
#include "src/sksl/SkSLErrorReporter.h"
#include "src/sksl/SkSLOperator.h"
#include "src/sksl/SkSLString.h"
#include "src/sksl/ir/SkSLConstructorCompound.h"
#include "src/sksl/ir/SkSLConstructorCompoundCast.h"
#include "src/sksl/ir/SkSLConstructorScalarCast.h"
#include "src/sksl/ir/SkSLConstructorSplat.h"
#include "src/sksl/ir/SkSLLiteral.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <optional>
using namespace skia_private;
namespace SkSL {
static bool validate_swizzle_domain(const ComponentArray& fields) {
enum SwizzleDomain {
kCoordinate,
kColor,
kUV,
kRectangle,
};
std::optional<SwizzleDomain> domain;
for (int8_t field : fields) {
SwizzleDomain fieldDomain;
switch (field) {
case SwizzleComponent::X:
case SwizzleComponent::Y:
case SwizzleComponent::Z:
case SwizzleComponent::W:
fieldDomain = kCoordinate;
break;
case SwizzleComponent::R:
case SwizzleComponent::G:
case SwizzleComponent::B:
case SwizzleComponent::A:
fieldDomain = kColor;
break;
case SwizzleComponent::S:
case SwizzleComponent::T:
case SwizzleComponent::P:
case SwizzleComponent::Q:
fieldDomain = kUV;
break;
case SwizzleComponent::UL:
case SwizzleComponent::UT:
case SwizzleComponent::UR:
case SwizzleComponent::UB:
fieldDomain = kRectangle;
break;
case SwizzleComponent::ZERO:
case SwizzleComponent::ONE:
continue;
default:
return false;
}
if (!domain.has_value()) {
domain = fieldDomain;
} else if (domain != fieldDomain) {
return false;
}
}
return true;
}
static char mask_char(int8_t component) {
switch (component) {
case SwizzleComponent::X: return 'x';
case SwizzleComponent::Y: return 'y';
case SwizzleComponent::Z: return 'z';
case SwizzleComponent::W: return 'w';
case SwizzleComponent::R: return 'r';
case SwizzleComponent::G: return 'g';
case SwizzleComponent::B: return 'b';
case SwizzleComponent::A: return 'a';
case SwizzleComponent::S: return 's';
case SwizzleComponent::T: return 't';
case SwizzleComponent::P: return 'p';
case SwizzleComponent::Q: return 'q';
case SwizzleComponent::UL: return 'L';
case SwizzleComponent::UT: return 'T';
case SwizzleComponent::UR: return 'R';
case SwizzleComponent::UB: return 'B';
case SwizzleComponent::ZERO: return '0';
case SwizzleComponent::ONE: return '1';
default: SkUNREACHABLE;
}
}
std::string Swizzle::MaskString(const ComponentArray& components) {
std::string result;
for (int8_t component : components) {
result += mask_char(component);
}
return result;
}
static std::unique_ptr<Expression> optimize_constructor_swizzle(const Context& context,
Position pos,
const ConstructorCompound& base,
ComponentArray components) {
auto baseArguments = base.argumentSpan();
std::unique_ptr<Expression> replacement;
const Type& exprType = base.type();
const Type& componentType = exprType.componentType();
int swizzleSize = components.size();
// Swizzles can duplicate some elements and discard others, e.g.
// `half4(1, 2, 3, 4).xxz` --> `half3(1, 1, 3)`. However, there are constraints:
// - Expressions with side effects need to occur exactly once, even if they would otherwise be
// swizzle-eliminated
// - Non-trivial expressions should not be repeated, but elimination is OK.
//
// Look up the argument for the constructor at each index. This is typically simple but for
// weird cases like `half4(bar.yz, half2(foo))`, it can be harder than it seems. This example
// would result in:
// argMap[0] = {.fArgIndex = 0, .fComponent = 0} (bar.yz .x)
// argMap[1] = {.fArgIndex = 0, .fComponent = 1} (bar.yz .y)
// argMap[2] = {.fArgIndex = 1, .fComponent = 0} (half2(foo) .x)
// argMap[3] = {.fArgIndex = 1, .fComponent = 1} (half2(foo) .y)
struct ConstructorArgMap {
int8_t fArgIndex;
int8_t fComponent;
};
int numConstructorArgs = base.type().columns();
ConstructorArgMap argMap[4] = {};
int writeIdx = 0;
for (int argIdx = 0; argIdx < (int)baseArguments.size(); ++argIdx) {
const Expression& arg = *baseArguments[argIdx];
const Type& argType = arg.type();
if (!argType.isScalar() && !argType.isVector()) {
return nullptr;
}
int argSlots = argType.slotCount();
for (int componentIdx = 0; componentIdx < argSlots; ++componentIdx) {
argMap[writeIdx].fArgIndex = argIdx;
argMap[writeIdx].fComponent = componentIdx;
++writeIdx;
}
}
SkASSERT(writeIdx == numConstructorArgs);
// Count up the number of times each constructor argument is used by the swizzle.
// `half4(bar.yz, half2(foo)).xwxy` -> { 3, 1 }
// - bar.yz is referenced 3 times, by `.x_xy`
// - half(foo) is referenced 1 time, by `._w__`
int8_t exprUsed[4] = {};
for (int8_t c : components) {
exprUsed[argMap[c].fArgIndex]++;
}
for (int index = 0; index < numConstructorArgs; ++index) {
int8_t constructorArgIndex = argMap[index].fArgIndex;
const Expression& baseArg = *baseArguments[constructorArgIndex];
// Check that non-trivial expressions are not swizzled in more than once.
if (exprUsed[constructorArgIndex] > 1 && !Analysis::IsTrivialExpression(baseArg)) {
return nullptr;
}
// Check that side-effect-bearing expressions are swizzled in exactly once.
if (exprUsed[constructorArgIndex] != 1 && Analysis::HasSideEffects(baseArg)) {
return nullptr;
}
}
struct ReorderedArgument {
int8_t fArgIndex;
ComponentArray fComponents;
};
STArray<4, ReorderedArgument> reorderedArgs;
for (int8_t c : components) {
const ConstructorArgMap& argument = argMap[c];
const Expression& baseArg = *baseArguments[argument.fArgIndex];
if (baseArg.type().isScalar()) {
// This argument is a scalar; add it to the list as-is.
SkASSERT(argument.fComponent == 0);
reorderedArgs.push_back({argument.fArgIndex,
ComponentArray{}});
} else {
// This argument is a component from a vector.
SkASSERT(baseArg.type().isVector());
SkASSERT(argument.fComponent < baseArg.type().columns());
if (reorderedArgs.empty() ||
reorderedArgs.back().fArgIndex != argument.fArgIndex) {
// This can't be combined with the previous argument. Add a new one.
reorderedArgs.push_back({argument.fArgIndex,
ComponentArray{argument.fComponent}});
} else {
// Since we know this argument uses components, it should already have at least one
// component set.
SkASSERT(!reorderedArgs.back().fComponents.empty());
// Build up the current argument with one more component.
reorderedArgs.back().fComponents.push_back(argument.fComponent);
}
}
}
// Convert our reordered argument list to an actual array of expressions, with the new order and
// any new inner swizzles that need to be applied.
ExpressionArray newArgs;
newArgs.reserve_exact(swizzleSize);
for (const ReorderedArgument& reorderedArg : reorderedArgs) {
std::unique_ptr<Expression> newArg = baseArguments[reorderedArg.fArgIndex]->clone();
if (reorderedArg.fComponents.empty()) {
newArgs.push_back(std::move(newArg));
} else {
newArgs.push_back(Swizzle::Make(context, pos, std::move(newArg),
reorderedArg.fComponents));
}
}
// Wrap the new argument list in a compound constructor.
return ConstructorCompound::Make(context,
pos,
componentType.toCompound(context, swizzleSize, /*rows=*/1),
std::move(newArgs));
}
std::unique_ptr<Expression> Swizzle::Convert(const Context& context,
Position pos,
Position maskPos,
std::unique_ptr<Expression> base,
std::string_view maskString) {
ComponentArray components;
for (size_t i = 0; i < maskString.length(); ++i) {
char field = maskString[i];
switch (field) {
case '0': components.push_back(SwizzleComponent::ZERO); break;
case '1': components.push_back(SwizzleComponent::ONE); break;
case 'x': components.push_back(SwizzleComponent::X); break;
case 'r': components.push_back(SwizzleComponent::R); break;
case 's': components.push_back(SwizzleComponent::S); break;
case 'L': components.push_back(SwizzleComponent::UL); break;
case 'y': components.push_back(SwizzleComponent::Y); break;
case 'g': components.push_back(SwizzleComponent::G); break;
case 't': components.push_back(SwizzleComponent::T); break;
case 'T': components.push_back(SwizzleComponent::UT); break;
case 'z': components.push_back(SwizzleComponent::Z); break;
case 'b': components.push_back(SwizzleComponent::B); break;
case 'p': components.push_back(SwizzleComponent::P); break;
case 'R': components.push_back(SwizzleComponent::UR); break;
case 'w': components.push_back(SwizzleComponent::W); break;
case 'a': components.push_back(SwizzleComponent::A); break;
case 'q': components.push_back(SwizzleComponent::Q); break;
case 'B': components.push_back(SwizzleComponent::UB); break;
default:
context.fErrors->error(Position::Range(maskPos.startOffset() + i,
maskPos.startOffset() + i + 1),
String::printf("invalid swizzle component '%c'", field));
return nullptr;
}
}
return Convert(context, pos, maskPos, std::move(base), std::move(components));
}
// Swizzles are complicated due to constant components. The most difficult case is a mask like
// '.x1w0'. A naive approach might turn that into 'float4(base.x, 1, base.w, 0)', but that evaluates
// 'base' twice. We instead group the swizzle mask ('xw') and constants ('1, 0') together and use a
// secondary swizzle to put them back into the right order, so in this case we end up with
// 'float4(base.xw, 1, 0).xzyw'.
std::unique_ptr<Expression> Swizzle::Convert(const Context& context,
Position pos,
Position maskPos,
std::unique_ptr<Expression> base,
ComponentArray inComponents) {
if (inComponents.size() > 4) {
context.fErrors->error(Position::Range(maskPos.startOffset() + 4,
maskPos.endOffset()),
"too many components in swizzle mask");
return nullptr;
}
if (!validate_swizzle_domain(inComponents)) {
context.fErrors->error(maskPos, "invalid swizzle mask '" + MaskString(inComponents) + "'");
return nullptr;
}
const Type& baseType = base->type().scalarTypeForLiteral();
if (!baseType.isVector() && !baseType.isScalar()) {
context.fErrors->error(pos, "cannot swizzle value of type '" +
baseType.displayName() + "'");
return nullptr;
}
ComponentArray maskComponents;
bool foundXYZW = false;
for (int i = 0; i < inComponents.size(); ++i) {
switch (inComponents[i]) {
case SwizzleComponent::ZERO:
case SwizzleComponent::ONE:
// Skip over constant fields for now.
break;
case SwizzleComponent::X:
case SwizzleComponent::R:
case SwizzleComponent::S:
case SwizzleComponent::UL:
foundXYZW = true;
maskComponents.push_back(SwizzleComponent::X);
break;
case SwizzleComponent::Y:
case SwizzleComponent::G:
case SwizzleComponent::T:
case SwizzleComponent::UT:
foundXYZW = true;
if (baseType.columns() >= 2) {
maskComponents.push_back(SwizzleComponent::Y);
break;
}
[[fallthrough]];
case SwizzleComponent::Z:
case SwizzleComponent::B:
case SwizzleComponent::P:
case SwizzleComponent::UR:
foundXYZW = true;
if (baseType.columns() >= 3) {
maskComponents.push_back(SwizzleComponent::Z);
break;
}
[[fallthrough]];
case SwizzleComponent::W:
case SwizzleComponent::A:
case SwizzleComponent::Q:
case SwizzleComponent::UB:
foundXYZW = true;
if (baseType.columns() >= 4) {
maskComponents.push_back(SwizzleComponent::W);
break;
}
[[fallthrough]];
default:
// The swizzle component references a field that doesn't exist in the base type.
context.fErrors->error(Position::Range(maskPos.startOffset() + i,
maskPos.startOffset() + i + 1),
String::printf("invalid swizzle component '%c'",
mask_char(inComponents[i])));
return nullptr;
}
}
if (!foundXYZW) {
context.fErrors->error(maskPos, "swizzle must refer to base expression");
return nullptr;
}
// Coerce literals in expressions such as `(12345).xxx` to their actual type.
base = baseType.coerceExpression(std::move(base), context);
if (!base) {
return nullptr;
}
// First, we need a vector expression that is the non-constant portion of the swizzle, packed:
// scalar.xxx -> type3(scalar)
// scalar.x0x0 -> type2(scalar)
// vector.zyx -> vector.zyx
// vector.x0y0 -> vector.xy
std::unique_ptr<Expression> expr = Swizzle::Make(context, pos, std::move(base), maskComponents);
// If we have processed the entire swizzle, we're done.
if (maskComponents.size() == inComponents.size()) {
return expr;
}
// Now we create a constructor that has the correct number of elements for the final swizzle,
// with all fields at the start. It's not finished yet; constants we need will be added below.
// scalar.x0x0 -> type4(type2(x), ...)
// vector.y111 -> type4(vector.y, ...)
// vector.z10x -> type4(vector.zx, ...)
//
// The constructor will have at most three arguments: { base expr, constant 0, constant 1 }
ExpressionArray constructorArgs;
constructorArgs.reserve_exact(3);
constructorArgs.push_back(std::move(expr));
// Apply another swizzle to shuffle the constants into the correct place. Any constant values we
// need are also tacked on to the end of the constructor.
// scalar.x0x0 -> type4(type2(x), 0).xyxy
// vector.y111 -> type2(vector.y, 1).xyyy
// vector.z10x -> type4(vector.zx, 1, 0).xzwy
const Type* scalarType = &baseType.componentType();
ComponentArray swizzleComponents;
int maskFieldIdx = 0;
int constantFieldIdx = maskComponents.size();
int constantZeroIdx = -1, constantOneIdx = -1;
for (int i = 0; i < inComponents.size(); i++) {
switch (inComponents[i]) {
case SwizzleComponent::ZERO:
if (constantZeroIdx == -1) {
// Synthesize a '0' argument at the end of the constructor.
constructorArgs.push_back(Literal::Make(pos, /*value=*/0, scalarType));
constantZeroIdx = constantFieldIdx++;
}
swizzleComponents.push_back(constantZeroIdx);
break;
case SwizzleComponent::ONE:
if (constantOneIdx == -1) {
// Synthesize a '1' argument at the end of the constructor.
constructorArgs.push_back(Literal::Make(pos, /*value=*/1, scalarType));
constantOneIdx = constantFieldIdx++;
}
swizzleComponents.push_back(constantOneIdx);
break;
default:
// The non-constant fields are already in the expected order.
swizzleComponents.push_back(maskFieldIdx++);
break;
}
}
expr = ConstructorCompound::Make(context, pos,
scalarType->toCompound(context, constantFieldIdx, /*rows=*/1),
std::move(constructorArgs));
// Create (and potentially optimize-away) the resulting swizzle-expression.
return Swizzle::Make(context, pos, std::move(expr), swizzleComponents);
}
std::unique_ptr<Expression> Swizzle::Make(const Context& context,
Position pos,
std::unique_ptr<Expression> expr,
ComponentArray components) {
const Type& exprType = expr->type();
SkASSERTF(exprType.isVector() || exprType.isScalar(),
"cannot swizzle type '%s'", exprType.description().c_str());
SkASSERT(components.size() >= 1 && components.size() <= 4);
// Confirm that the component array only contains X/Y/Z/W. (Call MakeWith01 if you want support
// for ZERO and ONE. Once initial IR generation is complete, no swizzles should have zeros or
// ones in them.)
SkASSERT(std::all_of(components.begin(), components.end(), [](int8_t component) {
return component >= SwizzleComponent::X &&
component <= SwizzleComponent::W;
}));
// SkSL supports splatting a scalar via `scalar.xxxx`, but not all versions of GLSL allow this.
// Replace swizzles with equivalent splat constructors (`scalar.xxx` --> `half3(value)`).
if (exprType.isScalar()) {
return ConstructorSplat::Make(context, pos,
exprType.toCompound(context, components.size(), /*rows=*/1),
std::move(expr));
}
// Detect identity swizzles like `color.rgba` and optimize it away.
if (components.size() == exprType.columns()) {
bool identity = true;
for (int i = 0; i < components.size(); ++i) {
if (components[i] != i) {
identity = false;
break;
}
}
if (identity) {
expr->fPosition = pos;
return expr;
}
}
// Optimize swizzles of swizzles, e.g. replace `foo.argb.rggg` with `foo.arrr`.
if (expr->is<Swizzle>()) {
Swizzle& base = expr->as<Swizzle>();
ComponentArray combined;
for (int8_t c : components) {
combined.push_back(base.components()[c]);
}
// It may actually be possible to further simplify this swizzle. Go again.
// (e.g. `color.abgr.abgr` --> `color.rgba` --> `color`.)
return Swizzle::Make(context, pos, std::move(base.base()), combined);
}
// If we are swizzling a constant expression, we can use its value instead here (so that
// swizzles like `colorWhite.x` can be simplified to `1`).
const Expression* value = ConstantFolder::GetConstantValueForVariable(*expr);
// `half4(scalar).zyy` can be optimized to `half3(scalar)`, and `half3(scalar).y` can be
// optimized to just `scalar`. The swizzle components don't actually matter, as every field
// in a splat constructor holds the same value.
if (value->is<ConstructorSplat>()) {
const ConstructorSplat& splat = value->as<ConstructorSplat>();
return ConstructorSplat::Make(
context, pos,
splat.type().componentType().toCompound(context, components.size(), /*rows=*/1),
splat.argument()->clone());
}
// Swizzles on casts, like `half4(myFloat4).zyy`, can optimize to `half3(myFloat4.zyy)`.
if (value->is<ConstructorCompoundCast>()) {
const ConstructorCompoundCast& cast = value->as<ConstructorCompoundCast>();
const Type& castType = cast.type().componentType().toCompound(context, components.size(),
/*rows=*/1);
std::unique_ptr<Expression> swizzled = Swizzle::Make(context, pos, cast.argument()->clone(),
std::move(components));
return (castType.columns() > 1)
? ConstructorCompoundCast::Make(context, pos, castType, std::move(swizzled))
: ConstructorScalarCast::Make(context, pos, castType, std::move(swizzled));
}
// Swizzles on compound constructors, like `half4(1, 2, 3, 4).yw`, can become `half2(2, 4)`.
if (value->is<ConstructorCompound>()) {
const ConstructorCompound& ctor = value->as<ConstructorCompound>();
if (auto replacement = optimize_constructor_swizzle(context, pos, ctor, components)) {
return replacement;
}
}
// The swizzle could not be simplified, so apply the requested swizzle to the base expression.
return std::make_unique<Swizzle>(context, pos, std::move(expr), components);
}
std::string Swizzle::description(OperatorPrecedence) const {
return this->base()->description(OperatorPrecedence::kPostfix) + "." +
MaskString(this->components());
}
} // namespace SkSL
|
8d6307ecc5c969362104324c10754b4149ee62b8 | 4aae1c8f2c6ea397994f830a3464629e196a7a8b | /Stella_X/Stella_X/buttons.ino | ee31efde5518df9c1319ebff53af4d24ceb2e5d9 | [] | no_license | xlcteam/Stelly | a57a0ef758dc0fccae768835986445bb3ca43f41 | 64c770067b96e62d752ac1962f965163444c7184 | refs/heads/master | 2023-04-29T11:26:50.260108 | 2019-06-28T09:47:11 | 2019-06-29T09:55:48 | 18,343,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,319 | ino | buttons.ino | Button btns[BUTTONS_COUNT] =
{ Button(BTN1_PIN), Button(BTN2_PIN), Button(BTN3_PIN), Button(BTN4_PIN) };
inline uint8_t btn_state(uint8_t index)
{
return btns[index].read();
}
void setup_buttons()
{
btns[0].set_onPush(btn1_onPush);
btns[0].set_onRelease(btn1_onRelease);
btns[1].set_onPush(btn2_onPush);
btns[2].set_onPush(btn3_onPush);
btns[3].set_onPush(btn4_onPush);
btns[3].set_pushed(btn4_pushed);
}
void update_buttons()
{
static uint32_t time = millis();
if (millis() - time > BUTTONS_DELAY) {
for (uint8_t i = 0; i < BUTTONS_COUNT; i++) {
btns[i].update();
}
time = millis();
}
}
/* VIC FUNCTIONS */
void vic_btn_state(void)
{
uint8_t index;
if (vic_args("%hhu", &index) == 1) {
vic_printf("%u\n", btn_state(index));
}
}
void vic_all_btns_state(void)
{
for (uint8_t i = 0; i < BUTTONS_COUNT; i++) {
vic_printf("%u", btn_state(i));
if (i < BUTTONS_COUNT - 1) {
vic_out(' ');
}
}
vic_out('\n');
}
/* BUTTON ACTIONS */
uint32_t btn1_time;
void btn1_onPush(void)
{
btn1_time = millis();
}
void btn1_onRelease(void)
{
if (millis() - btn1_time > 1000) {
if (task_id == TASK_TEST) {
task_id = TASK_NO;
IDLE();
} else {
task_id = TASK_TEST;
test_start();
}
return;
}
switch (task_id) {
case TASK_NO:
task_id = TASK_DISPLAY;
actual_screen = 1;
led_set(0, 0);
break;
case TASK_DISPLAY:
task_id = TASK_MOTION;
motion_start();
break;
case TASK_MOTION:
task_id = TASK_NO;
IDLE();
break;
default:
break;
}
}
void btn2_onPush(void)
{
switch (task_id) {
case TASK_NO:
kicker_dribbler();
//dribbler_switch_wk();
break;
case TASK_DISPLAY:
actual_screen = actual_screen == 4 ? 1 : actual_screen + 1;
break;
case TASK_TEST:
test_dbg = !test_dbg;
break;
case TASK_MOTION:
motion_dbg = !motion_dbg;
break;
default:
break;
}
}
void btn3_onPush(void)
{
switch (task_id) {
case TASK_NO:
line_use_int = !line_use_int;
break;
case TASK_DISPLAY:
if (actual_screen == 4) {
light_pwm = (light_pwm + 1) % 256;
}
break;
case TASK_TEST:
break;
case TASK_MOTION:
break;
default:
break;
}
}
void btn4_pushed(void)
{
if (task_id == TASK_DISPLAY && actual_screen == 4) {
light_pwm = (light_pwm + 1) % 256;
}
}
void btn4_onPush(void)
{
switch (task_id) {
case TASK_NO:
use_pixy = (use_pixy + 1) % 3;
break;
case TASK_DISPLAY:
if (actual_screen == 1) {
compass_set_north();
}
break;
case TASK_TEST:
compass_set_north();
break;
case TASK_MOTION:
compass_set_north();
break;
default:
break;
}
}
|
18d0f1c562bea3b590b91014f3de1c6ddcd18888 | 98c500bb0606acc48fb9bf41e8a406d80998c65c | /src/Colors.h | fefa12e47c0137b230ad8bd1a07a7e6b9bd68c14 | [] | no_license | Keldorado/complexParticles | a7a350cd6417308d0bbd4df39d2ead62dcba2fd1 | c516cd1111c6593b3b5100b08844475386146593 | refs/heads/master | 2021-01-01T19:02:29.262958 | 2015-05-29T04:19:39 | 2015-05-29T04:19:39 | 34,422,412 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 400 | h | Colors.h | //
// theColors.h
// animation2
//
// Created by Austin Kelley on 4/21/15.
//
//
#ifndef __animation2__theColors__
#define __animation2__theColors__
#include <stdio.h>
#include "ofMain.h"
class Colors{ //class has to be named the same as the .h file
public:
void setup();
ofColor myColors;
float change;
};
#endif /* defined(__animation2__theColors__) */
|
1aa09ba6d51dcbc5cb1a57618b7952c327677695 | 71ba6b4ce75806783d72a3eb3686bdfadf130cdf | /codechef/practice/beginner/BSTOPS/src.cpp | c70e981bfa1d112e6d4dec325c6f471b40f7516a | [] | no_license | koustubh-desai/codechef | 4b9edadf545c9877adc172be75a769e17f39996e | 0b3896556a5e3cfe5e2005e9826a8e15fe2445e7 | refs/heads/master | 2021-07-18T10:37:11.902993 | 2020-06-22T04:27:05 | 2020-06-22T04:27:05 | 185,400,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,443 | cpp | src.cpp | #include <iostream>
#include <sstream>
#include <vector>
#include <stdio.h>
#include <fstream>
#include <iomanip>
#include <tuple>
#define rep(i,a,b) for(int i=a;i<b;i++)
#define max(a,b) a>b?a:b
using namespace std;
struct Node{
int value,position;
Node *left = NULL, *right = NULL;
Node(int val, int pos){
this->value = val;
this->position = pos;
}
};
/*void traverseForFun(Node *a,int place){
if(a == NULL){
cout<<" what the heck !!! Found none at "<<place<<endl;
return;
}
if(a->left != NULL) traverseForFun(a->left,place<<1);
cout<<" Fun "<<a->value<<" at "<<place<<endl;
if(a->right != NULL) traverseForFun(a->right,(place<<1)+1);
}*/
Node* findRightMost(Node *a, int *valueOfTarget, int *found, int place){
if( a != NULL){
//In else if it has no children. Then a is our dude. b =a
if(a->right != NULL){
a->right= findRightMost(a->right, valueOfTarget, found, (place<<1)+1);
return a;
}
else{
//a->right is NULL
*found = place;
*valueOfTarget = a->value;
if(a->left != NULL) {
Node *tbr = a->left;
delete a;
return tbr;
};
return NULL;
}
}
return a;
}
Node* findLeftMost(Node *a, int *valueOfTarget, int *found, int place){
if( a != NULL){
//In else if See if it has no children. Then a is our dude. b =a
if(a->left != NULL){
a->left= findLeftMost(a->left, valueOfTarget, found, place<<1);
return a;
}
else{
//a->left is NULL
*found = place;
*valueOfTarget = a->value;
if(a->right != NULL) {
Node *tbr = a->right;
delete a;
return tbr;
}
return NULL;
}
}
return a;
}
Node* traverseToDelete(Node *node,int place,int val){
if(node==NULL) return node;
if(val > node->value) node->right = traverseToDelete(node->right, (place<<1)+1, val);
else if(val < node->value) node->left = traverseToDelete(node->left,place<<1, val);
else if(node->value == val){
cout<<node->position<<endl;
//1. no children
if(node->left == NULL && node->right == NULL){
free(node);
return NULL;
}
//2. got two children
if(node->left != NULL && node->right != NULL){
int valueOfTarget;
int found = 0;
node->right = findLeftMost(node->right, &valueOfTarget, &found,(place<<1)+1);
//if(!found) node->left = findRightMost(node->left, &valueOfTarget, &found,place<<1);
node->value = valueOfTarget;
return node;
}
//3. got one child
else{
Node *toBeReturned= (node->left != NULL)?node->left:node->right;
free(node);
return toBeReturned;
}
}
return node;
}
Node* delete_node(Node *root,int val, bool flag){
}
Node* traverseToInsert(Node *node, int place, int val){
if(node == NULL){
node = new Node(val,place);
cout<<place<<endl;
}
else if(val > node->value) node->right = traverseToInsert(node->right,(place<<1)+1, val);
else if(val < node->value) node->left = traverseToInsert(node->left, place<<1, val);
return node;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
/*std::ifstream in("test.txt");
std::streambuf*cinbuf = std::cin.rdbuf(); // save old buff
std::cin.rdbuf(in.rdbuf()); //redirect std::cin to be in .txt!*/
std::string line;
Node *head = NULL;
int N,T,temp;
char Instr;
cin>>T;
while(T--){
cin>>Instr;
cin>>N;
head = (Instr == 'i')?traverseToInsert(head,1,N):traverseToDelete(head,1,N);
}
return 0;
}
|
61466f30ba8cd26391d2bc252d4e54ee8e9024bd | feed86095f5e39ba7544dea6ff812a82b9823e76 | /ep28.cpp | 0517120f75bab17bb00194c54698a9ecc5ec1d5a | [] | no_license | MendyD/Haizei | 1fb29e78dc9c5b66fda251d3f067e95ac8ecada1 | 30e963628797f2634535be48e050c9ca92859edd | refs/heads/master | 2021-06-19T05:29:35.556380 | 2021-02-07T03:12:22 | 2021-02-07T03:12:22 | 161,894,830 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 338 | cpp | ep28.cpp | /*************************************************************************
> File Name: ep28.cpp
> Author: Mendy
> Mail: dolai_c@163.com
> Course:Number spiral diagonals
> Created Time: 五 11/23 20:46:55 2018
************************************************************************/
#include<stdio.h>
int main(){
return 0;
}
|
cc1a3a6d0cf3ab9720d386c3f335179f8f2381c1 | e119dc53a6648f864d2269c1fd98d4607a7c6a7a | /InheritanceExample/Account.cpp | 758972c0ad18839d84fc1cbf044646dc55be600f | [] | no_license | spa542/RandomCpp | b7941ceed5b0f4cc1438f9a31b04d2a53d33902e | 6f4fcad87d1ca9ccb3fd79449a4c26d147d4fba0 | refs/heads/master | 2023-02-06T05:23:48.997667 | 2020-12-29T20:29:58 | 2020-12-29T20:29:58 | 278,714,102 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,311 | cpp | Account.cpp | #include"Account.h"
Account::Account() : balance{0.0}, account_holder{"Unknown"}, num_of_withdraws{0},
num_of_deposits{0} {
}
Account::Account(double initBalance, std::string name) : balance{initBalance},
account_holder{name}, num_of_withdraws{0}, num_of_deposits{0} {
}
Account::Account(const Account& other) : balance{other.balance},
account_holder{other.account_holder}, num_of_withdraws{other.num_of_withdraws},
num_of_deposits{other.num_of_deposits} {
}
Account::~Account() {
}
void Account::deposit(double amount) {
balance += amount;
std::cout << amount << " added to account." << std::endl;
num_of_deposits++;
}
void Account::withdraw(double amount) {
if (amount > balance) {
std::cout << "You do not have that much money, please try again." << std::endl;
return;
}
balance -= amount;
std::cout << amount << " withdrawn from your account." << std::endl;
num_of_withdraws++;
}
void Account::print() {
std::cout << "Account Holder Name: " << account_holder << std::endl;
std::cout << "Current Balance: " << balance << std::endl;
std::cout << "Number of withdraws on this account: " << num_of_withdraws << std::endl;
std::cout << "Number of deposits on this account: " << num_of_deposits << std::endl;
}
|
f58b0409e70f69dfb3d9babca3b9c9ac14beb727 | 01338e89d76ae4e5b62073254293ef12322c5e48 | /talat_obiekty1.cpp | a42d011498d19ce09e4bf8f7994da03419617c78 | [] | no_license | Jswietoslawska/talat | 954b98524669c505788713eabad60b84ca86b6b4 | e3fd3fe0e3a87b676e25368858680cbc6cff5709 | refs/heads/master | 2020-03-12T17:58:36.575113 | 2018-04-23T20:05:46 | 2018-04-23T20:05:46 | 130,750,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,430 | cpp | talat_obiekty1.cpp | #include <iostream>
#include "talat_obiekty2.h"
#include "obsluga_gry.h""
#include <Windows.h>
#include <ctime>
#include <cstdlib>
#include <cstdio>
using namespace std;
plansza::plansza(kolor barwa1, kolor barwa2):
gracz1(barwa1), gracz2(barwa2), zamrozona(1)
{
for (int i = 0; i < ROZMIAR; i++)
{
for (int j = 0; j < ROZMIAR; j++)
{
pole_piona[i][j] = NULL;
}
}
}
pionek::pionek(wierzcholki wierz, wysokosc wys, kolor barwa):
dl(-1), szer(-1), wierz_piona(wierz), wys_piona(wys), kolor_piona(barwa)
{
dl = -1;
szer = -1;
wierz_piona = wierz;
wys_piona = wys;
}
gracz::gracz(plansza*plansz1, plansza* plansz2):
plansza1(plansz1), plansza2(plansz2)
{
if ((plansza1->getkolor1() == plansza2->getkolor1()) || (plansza1->getkolor1() == plansza2->getkolor2()))
{
kolor_gracza = plansza1->getkolor1();
}
else if ((plansza1->getkolor2() == plansza2->getkolor1()) || (plansza1->getkolor2() == plansza2->getkolor2()))
{
kolor_gracza = plansza1->getkolor2();
}
else
{
printf("Ups. Cos poszlo nie tak.\n"); //OBSLUGA WYJATKOW
}
punkty = 0;
piony[0] = new pionek(TROJKAT, MALY, kolor_gracza);
piony[1] = new pionek(TROJKAT, SREDNI, kolor_gracza);
piony[2] = new pionek(TROJKAT, DUZY, kolor_gracza);
piony[3] = new pionek(KWADRAT, MALY, kolor_gracza);
piony[4] = new pionek(KWADRAT, SREDNI, kolor_gracza);
piony[5] = new pionek(KWADRAT, DUZY, kolor_gracza);
piony[6] = new pionek(SZESCIOKAT, MALY, kolor_gracza);
piony[7] = new pionek(SZESCIOKAT, SREDNI, kolor_gracza);
piony[8] = new pionek(SZESCIOKAT, DUZY, kolor_gracza);
}
gracz::~gracz()
{
int i;
for (i = 0; i < WIEZE; i++)
{
delete piony[i];
}
}
plansza::~plansza()
{
}
int gracz::ustaw(szerokosc szero, pionek*pion, plansza*plan)
{
if (kolor_gracza == plan->getkolor2()) //kolor na dole
{
pion->setwspolrz(0, szero - 1);
plan->setpole_piona(0, szero - 1, pion);
plan->wyswietl_plansze();
return 0;
}
else if (kolor_gracza == plan->getkolor1()) //kolor na gorze
{
pion->setwspolrz(4, szero - 1);
plan->setpole_piona(4, szero - 1, pion);
plan->wyswietl_plansze();
return 0;
}
else
{
cout << endl << "Cos poszlo nie tak... To nie Twoja plansza!" << endl;
return 5;
}
}
int gracz::ruch_piona(pionek*pion, ruch rusza)
{
plansza*plan;
int i, j;
//sprawdzanie na ktorej planszy stoi pionek
for (i = 0; i < ROZMIAR; i++)
{
for (j = 0; j < ROZMIAR; j++)
{
if (plansza2->getpole_piona(i, j) == pion)
plan = plansza2;
if (plansza1->getpole_piona(i, j) == pion)
plan = plansza1;
}
}
cout << endl << "Po ruchu:" << endl;
dlugosc dlug = pion->getdlugosc();
szerokosc szero = pion->getszerokosc();
if (kolor_gracza == plan->getkolor2()) //kolor na dole
{
if (rusza == 1)
{
pion->setwspolrz(dlug + 1, szero - 1);
plan->setpole_piona(dlug + 1, szero - 1, pion);
plan->setpole_piona(dlug, szero, NULL);
plan->wyswietl_plansze();
return 0;
}
else if (rusza == 2)
{
pion->setwspolrz(dlug + 1, szero);
plan->setpole_piona(dlug + 1, szero, pion);
plan->setpole_piona(dlug, szero, NULL);
plan->wyswietl_plansze();
return 0;
}
else if (rusza == 3)
{
pion->setwspolrz(dlug + 1, szero + 1);
plan->setpole_piona(dlug + 1, szero + 1, pion);
plan->setpole_piona(dlug, szero, NULL);
plan->wyswietl_plansze();
return 0;
}
else
{
cout << endl << "Cos poszlo nie tak... Ten ruch nie byl dozwolony!" << endl;
return 5;
}
}
else if (kolor_gracza == plan->getkolor1()) //kolor na gorze
{
if (rusza == 1)
{
pion->setwspolrz(dlug - 1, szero - 1);
plan->setpole_piona(dlug - 1, szero - 1, pion);
plan->setpole_piona(dlug, szero, NULL);
plan->wyswietl_plansze();
return 0;
}
else if (rusza == 2)
{
pion->setwspolrz(dlug - 1, szero);
plan->setpole_piona(dlug - 1, szero, pion);
plan->setpole_piona(dlug, szero, NULL);
plan->wyswietl_plansze();
return 0;
}
else if (rusza == 3)
{
pion->setwspolrz(dlug - 1, szero + 1);
plan->setpole_piona(dlug - 1, szero + 1, pion);
plan->setpole_piona(dlug, szero, NULL);
plan->wyswietl_plansze();
return 0;
}
else
{
cout << endl << "Cos poszlo nie tak... Ten ruch nie byl dozwolony!" << endl;
return 5;
}
}
else
{
cout << endl << "Cos poszlo nie tak... To nie Twoja plansza!" << endl;
return 5;
}
}
int gracz::bicie(pionek*pion, ruch rusza, plansza* plan)
{
dlugosc dlug = pion->getdlugosc();
szerokosc szero = pion->getszerokosc();
if (kolor_gracza == plan->getkolor2())//kolor z dolu
{
if (rusza == 1 && plan->getpole_piona(dlug + 1, szero - 1) == NULL)
return 1;
if (rusza == 2 && plan->getpole_piona(dlug + 1, szero) == NULL)
return 1;
if (rusza == 3 && plan->getpole_piona(dlug + 1, szero + 1) == NULL)
return 1;
for (int i = 0; i < WIEZE; i++) //zabezpieczenie przed zbijaniem wlasnych pionow
{
if (rusza == 1 && plan->getpole_piona(dlug + 1, szero - 1) == piony[i])
return 2;
if (rusza == 2 && plan->getpole_piona(dlug + 1, szero) == piony[i])
return 2;
if (rusza == 3 && plan->getpole_piona(dlug + 1, szero + 1) == piony[i])
return 2;
}
//zbijanie przez wyzsze o oczko
if (rusza == 1 && plan->getpole_piona(dlug + 1, szero - 1)->getwys() + 1 == pion->getwys())
{
plan->getpole_piona(dlug + 1, szero - 1)->setwspolrz(-1, -1);
pion->setwspolrz(dlug + 1, szero - 1);
plan->setpole_piona(dlug + 1, szero - 1, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
if (rusza == 2 && plan->getpole_piona(dlug + 1, szero)->getwys() + 1 == pion->getwys())
{
plan->getpole_piona(dlug + 1, szero)->setwspolrz(-1, -1);
pion->setwspolrz(dlug + 1, szero);
plan->setpole_piona(dlug + 1, szero, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl <<"\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
if (rusza == 3 && plan->getpole_piona(dlug + 1, szero + 1)->getwys() + 1 == pion->getwys())
{
plan->getpole_piona(dlug + 1, szero + 1)->setwspolrz(-1, -1);
pion->setwspolrz(dlug + 1, szero + 1);
plan->setpole_piona(dlug + 1, szero + 1, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
//zbijanie przez piony z wieksza iloscia bokow
if (rusza == 1 && plan->getpole_piona(dlug + 1, szero -1)->getwys() == pion->getwys()&& plan->getpole_piona(dlug + 1, szero - 1)->getwierz() < pion->getwierz())
{
plan->getpole_piona(dlug + 1, szero - 1)->setwspolrz(-1, -1);
pion->setwspolrz(dlug + 1, szero - 1);
plan->setpole_piona(dlug + 1, szero - 1, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
if (rusza == 2 && plan->getpole_piona(dlug + 1, szero)->getwierz() < pion->getwierz()&& plan->getpole_piona(dlug + 1, szero)->getwys()== pion->getwys())
{
plan->getpole_piona(dlug + 1, szero)->setwspolrz(-1, -1);
pion->setwspolrz(dlug + 1, szero);
plan->setpole_piona(dlug + 1, szero, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
if (rusza == 3 && plan->getpole_piona(dlug + 1, szero + 1)->getwierz()< pion->getwierz()&& plan->getpole_piona(dlug + 1, szero + 1)->getwys() == pion->getwys())
{
plan->getpole_piona(dlug + 1, szero + 1)->setwspolrz(-1, -1);
pion->setwspolrz(dlug + 1, szero + 1);
plan->setpole_piona(dlug + 1, szero + 1, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
//zasada Dawida i Goliata
if (rusza == 1 && plan->getpole_piona(dlug + 1, szero - 1)->getwys() ==3&& pion->getwys()==1 && plan->getpole_piona(dlug + 1, szero - 1)->getwierz() ==6&& pion->getwierz()==3)
{
plan->getpole_piona(dlug + 1, szero - 1)->setwspolrz(-1, -1);
pion->setwspolrz(dlug + 1, szero - 1);
plan->setpole_piona(dlug + 1, szero - 1, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
if (rusza == 2 && plan->getpole_piona(dlug + 1, szero)->getwierz() ==6&& pion->getwierz()==3 && plan->getpole_piona(dlug + 1, szero)->getwys() ==3&& pion->getwys()==1)
{
plan->getpole_piona(dlug + 1, szero)->setwspolrz(-1, -1);
pion->setwspolrz(dlug + 1, szero);
plan->setpole_piona(dlug + 1, szero, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
if (rusza == 3 && plan->getpole_piona(dlug + 1, szero + 1)->getwierz()==6&& pion->getwierz()==3 && plan->getpole_piona(dlug + 1, szero + 1)->getwys() ==3&& pion->getwys()==1)
{
plan->getpole_piona(dlug + 1, szero + 1)->setwspolrz(-1, -1);
pion->setwspolrz(dlug + 1, szero + 1);
plan->setpole_piona(dlug + 1, szero + 1, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
}
else if (kolor_gracza == plan->getkolor1())//kolor na gorze
{
if (rusza == 1 && plan->getpole_piona(dlug - 1, szero - 1) == NULL)
return 1;
if (rusza == 2 && plan->getpole_piona(dlug - 1, szero) == NULL)
return 1;
if (rusza == 3 && plan->getpole_piona(dlug - 1, szero + 1) == NULL)
return 1;
for (int i = 0; i < WIEZE; i++) //zabezpieczenie przed zbijaniem wlasnych pionow
{
if (rusza == 1 && plan->getpole_piona(dlug - 1, szero - 1) == piony[i])
return 2;
if (rusza == 2 && plan->getpole_piona(dlug - 1, szero) == piony[i])
return 2;
if (rusza == 3 && plan->getpole_piona(dlug - 1, szero + 1) == piony[i])
return 2;
}
//zbijanie przez wyzsze o oczko
if (rusza == 1 && plan->getpole_piona(dlug - 1, szero - 1)->getwys() + 1 == pion->getwys())
{
plan->getpole_piona(dlug - 1, szero - 1)->setwspolrz(-1, -1);
pion->setwspolrz(dlug - 1, szero - 1);
plan->setpole_piona(dlug - 1, szero - 1, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
if (rusza == 2 && plan->getpole_piona(dlug - 1, szero)->getwys() + 1 == pion->getwys())
{
plan->getpole_piona(dlug - 1, szero)->setwspolrz(-1, -1);
pion->setwspolrz(dlug - 1, szero);
plan->setpole_piona(dlug - 1, szero, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
if (rusza == 3 && plan->getpole_piona(dlug - 1, szero + 1)->getwys() + 1 == pion->getwys())
{
plan->getpole_piona(dlug - 1, szero + 1)->setwspolrz(-1, -1);
pion->setwspolrz(dlug - 1, szero + 1);
plan->setpole_piona(dlug - 1, szero+1, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
//zbijanie przez piony z wieksza iloscia bokow
if (rusza == 1 && plan->getpole_piona(dlug - 1, szero - 1)->getwys() == pion->getwys() && plan->getpole_piona(dlug - 1, szero - 1)->getwierz() < pion->getwierz())
{
plan->getpole_piona(dlug - 1, szero - 1)->setwspolrz(-1, -1);
pion->setwspolrz(dlug - 1, szero - 1);
plan->setpole_piona(dlug - 1, szero - 1, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
if (rusza == 2 && plan->getpole_piona(dlug - 1, szero)->getwierz() < pion->getwierz() && plan->getpole_piona(dlug - 1, szero)->getwys() == pion->getwys())
{
plan->getpole_piona(dlug - 1, szero )->setwspolrz(-1, -1);
pion->setwspolrz(dlug - 1, szero);
plan->setpole_piona(dlug - 1, szero, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
if (rusza == 3 && plan->getpole_piona(dlug - 1, szero + 1)->getwierz()< pion->getwierz() && plan->getpole_piona(dlug - 1, szero + 1)->getwys() == pion->getwys())
{
plan->getpole_piona(dlug - 1, szero + 1)->setwspolrz(-1, -1);
pion->setwspolrz(dlug - 1, szero + 1);
plan->setpole_piona(dlug - 1, szero + 1, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
//zasada Dawida i Goliata
if (rusza == 1 && plan->getpole_piona(dlug - 1, szero - 1)->getwys() == 3 && pion->getwys() == 1 && plan->getpole_piona(dlug - 1, szero - 1)->getwierz() == 6 && pion->getwierz() == 3)
{
plan->getpole_piona(dlug - 1, szero - 1)->setwspolrz(-1, -1);
pion->setwspolrz(dlug - 1, szero - 1);
plan->setpole_piona(dlug - 1, szero - 1, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
if (rusza == 2 && plan->getpole_piona(dlug - 1, szero)->getwierz() == 6 && pion->getwierz() == 3 && plan->getpole_piona(dlug - 1, szero)->getwys() == 3 && pion->getwys() == 1)
{
plan->getpole_piona(dlug - 1, szero)->setwspolrz(-1, -1);
pion->setwspolrz(dlug - 1, szero);
plan->setpole_piona(dlug - 1, szero, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
if (rusza == 3 && plan->getpole_piona(dlug - 1, szero + 1)->getwierz() == 6 && pion->getwierz() == 3 && plan->getpole_piona(dlug - 1, szero + 1)->getwys() == 3 && pion->getwys() == 1)
{
plan->getpole_piona(dlug - 1, szero + 1)->setwspolrz(-1, -1);
pion->setwspolrz(dlug - 1, szero + 1);
plan->setpole_piona(dlug - 1, szero + 1, pion);
plan->setpole_piona(dlug, szero, NULL);
this->setpunkty(5);
cout << endl << "\tZbiles pionek!" << endl;
plan->wyswietl_plansze();
return 0;
}
}
else
{
cout << endl << "Cos poszlo nie tak... To nie Twoja plansza!" << endl;
return 5;
}
}
int plansza::wyswietl_plansze()
{
HANDLE kolor;
kolor = GetStdHandle(STD_OUTPUT_HANDLE);
if (zamrozona == 0)
return 2;
char*kolor1;
char*kolor2;
if (this->getkolor1() == BIALY)
{
kolor1 = "BIALY";
}
else if(this->getkolor1() == CZARNY)
{
kolor1 = "CZARNY";
}
else if(this->getkolor1() == SZARY)
{
kolor1 = "SZARY";
}
else
{
cout << endl << "Ups... Co to za kolor?" << endl;
return 1;
}
if (this->getkolor2() == BIALY)
{
kolor2 = "BIALY";
}
else if (this->getkolor2() == CZARNY)
{
kolor2 = "CZARNY";
}
else if (this->getkolor2() == SZARY)
{
kolor2 = "SZARY";
}
else
{
cout << endl << "Ups... Co to za kolor?" << endl;
return 1;
}
cout << endl;
for (int i = ROZMIAR-1; i >=0; i--)
{
for (int j =0; j<ROZMIAR; j++)
{
char znak='_';
if (pole_piona[i][j] != NULL)
{
if (pole_piona[i][j]->getwierz() == 3)
znak = 'V';
if (pole_piona[i][j]->getwierz() == 4)
znak = 'X';
if (pole_piona[i][j]->getwierz() == 6)
znak = 'O';
}
else
znak = '_';
//bialy
putchar('|');
if (pole_piona[i][j] != NULL&&pole_piona[i][j]->getkolor() == BIALY)
{
if (pole_piona[i][j]->getwys() == 1)
SetConsoleTextAttribute(kolor, 0x07);
else if (pole_piona[i][j]->getwys() == 2)
SetConsoleTextAttribute(kolor, 0x08);
else
SetConsoleTextAttribute(kolor, 0x06);
cout << znak;
SetConsoleTextAttribute(kolor, 7);
}
else if (pole_piona[i][j] != NULL&&pole_piona[i][j]->getkolor() == SZARY)
{
if (pole_piona[i][j]->getwys() == 1)
SetConsoleTextAttribute(kolor, 0x37);
else if (pole_piona[i][j]->getwys() == 2)
SetConsoleTextAttribute(kolor, 0x38);
else
SetConsoleTextAttribute(kolor, 0x36);
cout << znak;
SetConsoleTextAttribute(kolor, 7);
}
else if (pole_piona[i][j] != NULL&&pole_piona[i][j]->getkolor() == CZARNY)
{
if (pole_piona[i][j]->getwys() == 1)
SetConsoleTextAttribute(kolor, 0x03);
else if (pole_piona[i][j]->getwys() == 2)
SetConsoleTextAttribute(kolor, 0x09);
else
SetConsoleTextAttribute(kolor, 0x01);
cout << znak;
SetConsoleTextAttribute(kolor, 7);
}
else
cout << znak;
}
if (i == 0)
{
cout << "| " << kolor2 << endl;
}
else if (i == 4)
{
cout << "| " << kolor1 << endl;
}
else
cout << "|" << endl;
}
}
int plansza::czy_puste_pole(dlugosc a, szerokosc b)
{
if (pole_piona[a][b] != NULL)
return 1;
else
return 0;
};
int plansza::zamrozenie()
{
int j,i;
bool flaga = 0;
for (i = 0; i<ROZMIAR; i++)
{
for (j = 0; j < ROZMIAR; j++)
{
if (pole_piona[i][j] == NULL)
continue;
if (mozliwosc_ruchu(pole_piona[i][j]) == 1)
flaga = 1;
}
}
if (flaga == 0)
{
zamrozona = 0;
return 0;
}
for ( i=0;i<ROZMIAR;i++)
{
for (j = 0; j < ROZMIAR; j++)
{
if (pole_piona[i][j] == NULL)
continue;
if (mozliwosc_bicia(pole_piona[i][j]) == 1)
return 1;
}
}
zamrozona = 0;
return 0;
}
int plansza::mozliwosc_bicia(pionek*pion)
{
dlugosc dl =pion->getdlugosc();
szerokosc szer = pion->getszerokosc();
kolor barwa = pion->getkolor();
wierzcholki wierz = pion->getwierz();
wysokosc wys = pion->getwys();
if (barwa == gracz2) //kolor na dole
{
int j;
for (int i = 0; i < ROZMIAR;i++ )
{
for (j = 0; j <=i; j++)
{
if (dl + 1 + i >= ROZMIAR)
return 0;
if (pole_piona[dl + 1 + i][szer] != NULL&&pole_piona[dl + 1+i][szer]->getkolor() != barwa)
{
if (pole_piona[dl + 1+i][szer]->getwys() + 1 == wys || (pole_piona[dl + 1+i][szer]->getwys() == wys&&pole_piona[dl + 1+i][szer]->getwierz() < wierz))
return 1;
if (pole_piona[dl + 1+i][szer]->getwys() == 3 && pole_piona[dl + 1+i][szer]->getwierz() == 6 && wys == 1 && wierz == 3)
return 1;
}
if (szer - 1 -j>= 0 && pole_piona[dl + 1 + i][szer - 1-j] != NULL&&pole_piona[dl + 1+i][szer - 1-j]->getkolor() != barwa)
{
if (pole_piona[dl + 1+i][szer - 1-j]->getwys() + 1 == wys || (pole_piona[dl + 1+i][szer - 1-j]->getwys() == wys&&pole_piona[dl + 1+i][szer - 1-j]->getwierz() < wierz))
return 1;
if (pole_piona[dl + 1+i][szer - 1-j]->getwys() == 3 && pole_piona[dl + 1+i][szer - 1-j]->getwierz() == 6 && wys == 1 && wierz == 3)
return 1;
}
if (szer + 1 +j < ROZMIAR && pole_piona[dl + 1 + i][szer + 1+j] != NULL&&pole_piona[dl + 1+i][szer + 1+j]->getkolor() != barwa)
{
if (pole_piona[dl + 1+i][szer + 1+j]->getwys() + 1 == wys || (pole_piona[dl + 1+i][szer + 1+j]->getwys() == wys&&pole_piona[dl + 1+i][szer + 1+j]->getwierz() < wierz))
return 1;
if (pole_piona[dl + 1+i][szer + 1+j]->getwys() == 3 && pole_piona[dl + 1+i][szer + 1+j]->getwierz() == 6 && wys == 1 && wierz == 3)
return 1;
}
}
}
return 0;
}
else if (barwa == gracz1) //kolor na gorze
{
int j;
for (int i = 0; i < ROZMIAR; i++)
{
for (j = 0; j <=i; j++)
{
if (dl - 1 - i < 0)
return 0;
if (pole_piona[dl - 1-i][szer] != NULL&&pole_piona[dl - 1-i][szer]->getkolor() != barwa)
{
if (pole_piona[dl - 1-i][szer]->getwys() + 1 == wys || (pole_piona[dl - 1-i][szer]->getwys() == wys&&pole_piona[dl - 1-i][szer]->getwierz() < wierz))
return 1;
if (pole_piona[dl - 1-i][szer]->getwys() == 3 && pole_piona[dl - 1-i][szer]->getwierz() == 6 && wys == 1 && wierz == 3)
return 1;
}
if (szer - 1-j >= 0 && pole_piona[dl - 1-i][szer - 1-j] != NULL&&pole_piona[dl - 1-i][szer - 1-j]->getkolor() != barwa)
{
if (pole_piona[dl - 1-i][szer - 1-j]->getwys() + 1 == wys || (pole_piona[dl - 1-i][szer - 1-j]->getwys() == wys&&pole_piona[dl - 1-i][szer - 1-j]->getwierz() < wierz))
return 1;
if (pole_piona[dl - 1-i][szer - 1-j]->getwys() == 3 && pole_piona[dl - 1-i][szer - 1-j]->getwierz() == 6 && wys == 1 && wierz == 3)
return 1;
}
if (szer + 1+j < ROZMIAR && pole_piona[dl - 1-i][szer + 1+j] != NULL&&pole_piona[dl - 1-i][szer + 1+j]->getkolor() != barwa)
{
if (pole_piona[dl - 1-i][szer + 1+j]->getwys() + 1 == wys || (pole_piona[dl - 1-i][szer + 1+j]->getwys() == wys&&pole_piona[dl - 1-i][szer + 1+j]->getwierz() < wierz))
return 1;
if (pole_piona[dl - 1-i][szer + 1+j]->getwys() == 3 && pole_piona[dl - 1-i][szer + 1+j]->getwierz() == 6 && wys == 1 && wierz == 3)
return 1;
}
}
}
return 0;
}
}
int gracz_czlowiek::ustaw(szerokosc szero, pionek*pion, plansza*plan)
{
if (pion->getdlugosc() != -1)
{
return 2;
}
if (szero <= 0 || szero > ROZMIAR)
{
return 1;
}
if (kolor_gracza == plan->getkolor2()&& (plan->czy_puste_pole(0, szero - 1) == 1)) //kolor na dole
{
return 3;
}
else if (kolor_gracza == plan->getkolor1()&& (plan->czy_puste_pole(4, szero - 1) == 1)) //kolor na gorze
{
return 3;
}
else
{
gracz::ustaw(szero, pion, plan);
return 0;
}
}
int gracz_komputer::ustawianie()
{
srand(time(0));
//losowanie piona
int los = rand() % 9;
while(piony[los]->getszerokosc()!=-1)
los = rand() % 9;
pionek * pion = piony[los];
//losowanie planszy
los = rand() % 2;
plansza*plan;
if (los == 1)
plan = plansza1;
else
plan = plansza2;
int i;
//sprawdzenie czy na planszy sa wolne miejsca
if (kolor_gracza == plan->getkolor2()) //kolor na dole
{
for (i = 0; i < ROZMIAR;)
{
if (plan->czy_puste_pole(0, i) == 1)
i++;
else
break;
}
if (i == ROZMIAR&&plan == plansza1)
plan = plansza2;
else if (i == ROZMIAR&&plan == plansza2)
plan = plansza1;
else;
}
else if (kolor_gracza == plan->getkolor1()) //kolor na gorze
{
for (i = 0; i < ROZMIAR;)
{
if (plan->czy_puste_pole(4, i) == 1)
i++;
else
break;
}
if (i == ROZMIAR&&plan == plansza1)
plan = plansza2;
else if (i == ROZMIAR&&plan == plansza2)
plan = plansza1;
else;
}
//losowanie szerokosci
szerokosc szero = rand() % 5 + 1;
for (i = 0; kolor_gracza == plan->getkolor2() && plan->czy_puste_pole(0, szero - 1) == 1 && i < ROZMIAR;i++) //kolor na dole
{
szero = rand() % 5 + 1;
}
for (i = 0; kolor_gracza == plan->getkolor1() && plan->czy_puste_pole(4, szero - 1) == 1 && i < ROZMIAR; i++) //kolor na gorze
{
szero = rand() % 5 + 1;
}
//ustawianie piona
gracz::ustaw(szero, pion, plan);
return 0;
}
int gracz_komputer::ruch_gracza()
{
if (plansza1->getzamrozona() == 0 && plansza2->getzamrozona() == 0)
return 1;
ruch rusza;
int i, j;
plansza *plan=NULL;
pionek*pion;
int los;
while (plan == NULL)
{
//losowanie piona
los = rand() % 9;
while (piony[los]->getszerokosc() == -1)
los = rand() % 9;
pion = piony[los];
//sprawdzanie na ktorej planszy stoi pionek
for (i = 0; i < ROZMIAR; i++)
{
for (j = 0; j < ROZMIAR; j++)
{
if (plansza1->getpole_piona(i, j) == piony[los])
{
if (plansza1->getzamrozona() != 0)
plan = plansza1;
}
}
}
if (plan == NULL)
{
for (i = 0; i < ROZMIAR; i++)
{
for (j = 0; j < ROZMIAR; j++)
{
if (plansza2->getpole_piona(i, j) == piony[los])
{
if (plansza2->getzamrozona() != 0)
plan = plansza2;
}
}
}
}
if (plan == NULL)
continue;
dlugosc dlug = pion->getdlugosc();
szerokosc szero = pion->getszerokosc();
int rusz;
bool flaga = 1;
while (flaga)
{
flaga = 0;
//losowanie ruchu
rusz = rand() % 3 + 1;
if (rusz == 1)
rusza = LEWO_SKOS;
if (rusz == 2)
rusza = PRZOD;
if (rusz == 3)
rusza = PRAWO_SKOS;
if (kolor_gracza == plan->getkolor2()) //kolor na dole
{
//mozliwosc ruchu
if (dlug + 1 >= ROZMIAR)
{
plan = NULL;
break;
}
if (rusza == 1 && (szero - 1 < 0))
flaga = 1;
if (rusza == 3 && (szero + 1 >= ROZMIAR))
flaga = 1;
//bicie
if (flaga == 1)
continue;
if (this->bicie(pion, rusza, plan) == 0)
return 0;
if (rusza == 1 && plan->czy_puste_pole(dlug + 1, szero - 1) == 1)
plan = NULL;
if (plan == NULL)
break;
if (rusza == 2 && plan->czy_puste_pole(dlug + 1, szero) == 1)
plan = NULL;
if (plan == NULL)
break;
if (rusza == 3 && plan->czy_puste_pole(dlug + 1, szero + 1) == 1)
plan = NULL;
if (plan == NULL)
break;
}
else if (kolor_gracza == plan->getkolor1()) //kolor na gorze
{
//mozliwosc ruchu
if (dlug - 1 < 0)
plan = NULL;
if (plan == NULL)
break;
if (rusza == 1 && (szero - 1 < 0))
flaga = 1;
if (rusza == 3 && (dlug - 1 < 0 || szero + 1 >= ROZMIAR))
flaga = 1;
//bicie
if (flaga == 1)
continue;
if (this->bicie(pion, rusza, plan) == 0)
return 0;
if (rusza == 1 && plan->czy_puste_pole(dlug - 1, szero - 1) == 1)
plan = NULL;
if(plan==NULL)
break;
if (rusza == 2 && plan->czy_puste_pole(dlug - 1, szero) == 1)
plan = NULL;
if (plan == NULL)
break;
if (rusza == 3 && plan->czy_puste_pole(dlug - 1, szero + 1) == 1)
plan = NULL;
if (plan == NULL)
break;
}
else
{
cout << endl << "Cos poszlo nie tak... To nie Twoja plansza!" << endl;
return 5;
}
}
}
gracz::ruch_piona(pion, rusza);
return 0;
}
int gracz_czlowiek::ruch_piona(pionek*pion, ruch rusza)
{
plansza*plan=NULL;
int i, j;
if (pion->getdlugosc() == -1)
{
return 2;
}
//sprawdzanie na ktorej planszy stoi pionek
for (i = 0; i < ROZMIAR; i++)
{
for (j = 0; j < ROZMIAR; j++)
{
if (plansza2->getpole_piona(i, j) == pion)
plan = plansza2;
if (plansza1->getpole_piona(i, j) == pion)
plan = plansza1;
}
}
plan->zamrozenie();
if (plan->zamrozona == 0)
return 4;
dlugosc dlug = pion->getdlugosc();
szerokosc szero = pion->getszerokosc();
if (kolor_gracza == plan->getkolor2()) //kolor na dole
{
//mozliwosc ruchu
if (rusza == 1 && (dlug + 1 >= ROZMIAR || szero - 1 < 0))
return 1;
if (rusza == 2 && dlug + 1 >= ROZMIAR)
return 1;
if (rusza == 3 && (dlug + 1 >= ROZMIAR || szero + 1 >= ROZMIAR))
return 1;
//bicie
if (this->bicie(pion, rusza, plan) == 0)
return 0;
if (rusza == 1 && plan->czy_puste_pole(dlug + 1, szero - 1) == 1)
return 3;
if (rusza == 2 && plan->czy_puste_pole(dlug + 1, szero) == 1)
return 3;
if (rusza == 3 && plan->czy_puste_pole(dlug + 1, szero + 1) == 1)
return 3;
}
else if (kolor_gracza == plan->getkolor1()) //kolor na gorze
{
//mozliwosc ruchu
if (rusza == 1 && (dlug - 1 < 0 || szero - 1 < 0))
return 1;
if (rusza == 2 && dlug - 1<0)
return 1;
if (rusza == 3 && (dlug - 1 <0 || szero + 1 >= ROZMIAR))
return 1;
//bicie
if (this->bicie(pion, rusza, plan) == 0)
return 0;
if (rusza == 1 && plan->czy_puste_pole(dlug - 1, szero - 1) == 1)
return 3;
if (rusza == 2 && plan->czy_puste_pole(dlug - 1, szero) == 1)
return 3;
if (rusza == 3 && plan->czy_puste_pole(dlug - 1, szero + 1) == 1)
return 3;
}
else
{
cout << endl << "Cos poszlo nie tak... To nie Twoja plansza!" << endl;
return 5;
}
gracz::ruch_piona(pion, rusza);
return 0;
}
int gracz_czlowiek::ruch_gracza()
{
bool flaga = 1;
wysokosc wys;
wierzcholki ile_wierz;
int pion;
int mjsc;
while (flaga)
{
flaga = 0;
cout << endl << "PLANSZA 1" <<endl;
if (plansza1->wyswietl_plansze() == 2)
{
cout << endl << "Plansza zamrozona." << endl;
}
cout << endl << "PLANSZA 2" << endl;
if (plansza2->wyswietl_plansze() == 2)
{
cout << endl << "Plansza zamrozona." << endl;
}
cout << "Podaj wysokosc piona: 1 - maly, 2 - sredni, 3 - duzy"<< endl;
while (scanf("%d", &wys) != 1 || wys < 1 || wys>3 || getchar() != '\n')
{
cout << "Nieporawna wysokosc... Wybierz 1, 2 albo 3!\n";
while (getchar() != '\n');
}
cout << "Podaj ilosc wierzcholkow piona: 3, 4 albo 6." << endl;
while (scanf("%d", &ile_wierz) != 1 || (ile_wierz != 3 && ile_wierz != 4 && ile_wierz != 6) || getchar() != '\n')
{
cout << "Nieporawna ilosc wierzcholkow... Wybierz 3, 4 albo 6!"<< endl;
while (getchar() != '\n');
}
cout << "Podaj ruch. 1-lewoskos, 2-prosto, 3-prawoskos" << endl;
while (scanf("%d", &mjsc) != 1 || mjsc < 1 || mjsc>3 || getchar() != '\n')
{
cout << "Wybierz wartosc od 1 do 3!\n" << endl;
while (getchar() != '\n');
}
int sprawdzenie;
pion = wybor_piona(ile_wierz, wys);
ruch rusza;
if (mjsc == 1)
rusza = LEWO_SKOS;
if (mjsc == 2)
rusza = PRZOD;
if (mjsc == 3)
rusza = PRAWO_SKOS;
if ((sprawdzenie = (this->ruch_piona(piony[pion], rusza))) == 0)
{
return 0;
}
else if (sprawdzenie == 1)
{
cout << endl << "Nie mozna ustawic piona poza plansza! Podaj nowe wartosci:" << endl;
flaga = 1;
}
else if (sprawdzenie == 2)
{
cout << endl << "Ten pionek zostal juz zbity! Podaj inny:" << endl;
flaga = 1;
}
else if (sprawdzenie == 3)
{
cout << endl << "To pole jest juz zajete. Podaj nowe wartosci:" << endl;
flaga = 1;
}
else if (sprawdzenie == 4)
{
cout << endl << "Plansza zamrozona. Wybierz inna." << endl;
flaga = 1;
}
else if (sprawdzenie == 5)
{
cout << endl << "Podaj nowe wartosci:" << endl;
flaga = 1;
}
}
}
int gracz_czlowiek::ustawianie()
{
bool flaga = 1;
wysokosc wys;
wierzcholki ile_wierz;
int pion;
int mjsc;
int plansz;
this->wyswietl_plansze_gracza();
while (flaga)
{
flaga = 0;
cout << "Podaj wysokosc piona: 1 - maly, 2 - sredni, 3 - duzy" << endl;
while (scanf("%d", &wys) != 1 || wys < 1 || wys>3 || getchar() != '\n')
{
cout << "Nieporawna wysokosc... Wybierz 1, 2 albo 3!" << endl;
while (getchar() != '\n');
}
cout << "Podaj ilosc wierzcholkow piona: 3, 4 albo 6." << endl;
while (scanf("%d", &ile_wierz) != 1 || (ile_wierz != 3 && ile_wierz != 4 && ile_wierz != 6) || getchar() != '\n')
{
cout << "Nieporawna ilosc wierzcholkow... Wybierz 3, 4 albo 6!" << endl;
while (getchar() != '\n');
}
cout << "Podaj miejsce na planszy. 1-5" << endl;
while (scanf("%d", &mjsc) != 1 || mjsc < 1 || mjsc>5 || getchar() != '\n')
{
cout << "Wybierz wartosc od 1 do 5!" << endl;
while (getchar() != '\n');
}
cout << "Podaj plansze, 1 lub 2." << endl;
while (scanf("%d", &plansz) != 1 || (plansz != 1 && plansz != 2) || getchar() != '\n')
{
cout << "Wybierz wartosc 1 lub 2!" << endl;
while (getchar() != '\n');
}
int sprawdzenie;
pion = wybor_piona(ile_wierz, wys);
if (plansz == 1)
{
sprawdzenie = (this->ustaw(mjsc, piony[pion], plansza1));
}
if (plansz == 2)
{
sprawdzenie = (this->ustaw(mjsc, piony[pion], plansza2));
}
if (sprawdzenie == 0)
{
return 0;
}
else if (sprawdzenie == 1)
{
cout << endl << "Nie mozna ustawic piona poza plansza! Podaj nowe wartosci:" << endl;
flaga = 1;
}
else if (sprawdzenie == 2)
{
cout << endl << "Ten pionek byl juz ustawiany! Podaj wartosci dla innego piona:" << endl;
flaga = 1;
}
else if (sprawdzenie == 3)
{
cout << endl << "To pole jest juz zajete. Podaj nowe wartosci:" << endl;
flaga = 1;
}
else if (sprawdzenie == 5)
{
cout << endl << "Podaj nowe wartosci:" << endl;
flaga = 1;
}
}
}
void gracz_czlowiek::pobierz_nick(int nr)
{
char imie[50];
cout << "Nick gracza " << nr << ":" << endl;
while (scanf("%s", imie) != 1|| strcmp(imie, "komputer") == 0)
{
cout << "Podaj nazwe! Pamietaj, ze musi byc ona rozna od \"komputer\""<<endl;
while (getchar() != '\n');
}
setnick(imie);
}
void gracz_komputer::pobierz_nick(int nr)
{
setnick("komputer");
}
int plansza::mozliwosc_ruchu(pionek*pion)
{
dlugosc dl= pion->getdlugosc();
szerokosc szer = pion->getszerokosc();
kolor barwa = pion->getkolor();
if (barwa == gracz2) //kolor na dole
{
if (dl + 1 >= ROZMIAR)
return 0;
//sprawdzenie czy nie ma bicia
if (zbije(pion, pole_piona[dl + 1][szer]) == 1)
{
return 1;
}
if (szer + 1 < ROZMIAR&&zbije(pion, pole_piona[dl + 1][szer + 1])==1)
{
return 1;
}
if (szer - 1 >= 0 && zbije(pion, pole_piona[dl + 1][szer - 1]) == 1)
{
return 1;
}
if (szer + 1 >= ROZMIAR&&czy_puste_pole(dl + 1, szer - 1) && czy_puste_pole(dl + 1, szer))
{
return 0;
}
else if (szer - 1 < 0 && czy_puste_pole(dl + 1, szer + 1) && czy_puste_pole(dl + 1, szer))
{
return 0;
}
else if (szer - 1 >= 0 && szer + 1 < ROZMIAR&&czy_puste_pole(dl + 1, szer + 1) && czy_puste_pole(dl + 1, szer) && czy_puste_pole(dl + 1, szer - 1))
{
return 0;
}
else
{
return 1;
}
}
else if (barwa == gracz1) //kolor na gorze
{
if (dl - 1 < 0)
return 0;
//sprawdzenie czy nie ma bicia
if (zbije(pion, pole_piona[dl - 1][szer]) == 1)
{
return 1;
}
if (szer + 1 < ROZMIAR&&zbije(pion, pole_piona[dl - 1][szer + 1]) == 1)
{
return 1;
}
if (szer - 1 >= 0 && zbije(pion, pole_piona[dl - 1][szer - 1]) == 1)
{
return 1;
}
if (szer + 1 >= ROZMIAR&&czy_puste_pole(dl - 1, szer - 1) && czy_puste_pole(dl - 1, szer))
{
return 0;
}
else if (szer - 1 < 0 && czy_puste_pole(dl - 1, szer + 1) && czy_puste_pole(dl - 1, szer))
{
return 0;
}
else if (szer - 1 >= 0 && szer + 1 < ROZMIAR&&czy_puste_pole(dl - 1, szer + 1) && czy_puste_pole(dl - 1, szer) && czy_puste_pole(dl - 1, szer - 1))
{
return 0;
}
else
{
return 1;
}
}
else
{
cout << "Czy ten pion stoi na wlasciwej planszy?" << endl;
return -1;
}
}
int plansza::zbije(pionek*pion, pionek*zbijany)
{
if (zbijany == NULL)
{
return -1;
}
kolor barwa1 = pion->getkolor();
wierzcholki wierz1 = pion->getwierz();
wysokosc wys1 = pion->getwys();
kolor barwa2 = zbijany->getkolor();
wierzcholki wierz2 = zbijany->getwierz();
wysokosc wys2 = zbijany->getwys();
if (barwa1 == barwa2)
{
return 0;
}
if (wys2 + 1 == wys1)
{
return 1;
}
else if (wys1 == wys2&&wierz2 < wierz1)
{
return 1;
}
else if (wys1 == 3 && wierz1 == 6 && wys2 == 1 && wierz2 == 3)
{
return 1;
}
else
{
return 0;
}
} |
631a6900370b545d03152f7b291f3102bc1c4e7e | 48fa140ee8a01bb9f03ee9e96961f3d40f1c65cc | /src/Interpolation.cpp | 8f90f60e8ed62a911ffc669d1641e8ddedbaf772 | [] | no_license | DJWalker42/laserRacoon | 5273517721374eb3941827dc94b429e0786e7e2b | 9817bcbeea50853b4d225905ca1efd5529a38748 | refs/heads/master | 2023-05-02T13:15:50.479215 | 2023-04-13T10:00:38 | 2023-04-13T10:00:38 | 55,231,189 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,375 | cpp | Interpolation.cpp | #include <cfloat>
#include "Interpolation.h"
namespace phys{
/********************************************************
* Constructors
********************************************************/
Interpolator::Interpolator() : m_data(),
m_errorEstimate(0.0),
m_sortSwitch(true),
m_tolX(DBL_EPSILON)
{ /*no data to check*/}
Interpolator::Interpolator( const stdVec_d& x_vals,
const stdVec_d& y_vals,
bool sort,
double tolx) :
m_data(x_vals, y_vals),
m_errorEstimate(0.0),
m_sortSwitch(sort),
m_tolX(tolx)
{
assert(m_data.x.size() == m_data.y.size());
if (m_sortSwitch)
chk_sorting();
}
Interpolator::Interpolator( const data& d,
bool sort,
double tolx) :
m_data(d),
m_errorEstimate(0.0),
m_sortSwitch(sort),
m_tolX(tolx)
{
assert(m_data.x.size() == m_data.y.size());
if (m_sortSwitch)
chk_sorting();
}
/***************************************************************
* Interface functions
***************************************************************/
void Interpolator::chk_sorting()
{
size_t i = 0;
size_t max = m_data.x.size();
while (++i < max && m_data.x[i] > m_data.x[i - 1])
; //no body
if (i < max) sort_ascending();
}
void Interpolator::change_data(const data& data_to_set)
{
m_data = data_to_set;
if (m_sortSwitch)
chk_sorting();
}
stdVec_d Interpolator::interpolate(const stdVec_d& x)
{
stdVec_d retval;
for(size_t i = 0; i < x.size(); ++i)
{
retval.push_back(this->interpolate(x[i]));
}
return retval;
}
void Interpolator::sort_ascending()
{
data temp(m_data);
//this sorts m_data x values.
std::sort(m_data.x.begin(), m_data.x.end());
//need to apply to y values.
for (size_t i = 0; i < temp.x.size(); ++i)
{
size_t j = 0;
while( j < m_data.x.size() && temp.x[i] != m_data.x[j] )
++j; //put update in the body to ensure we know which condition breaks the loop
if( j < m_data.x.size() )
temp.y[j] = m_data.y[i];
//else no match - which is impossible as temp is a copy of m_data
}
//assign sorted data back to m_data.
m_data.y = temp.y;
}
size_t Interpolator::find_base_idx(double x) const
{
// find the closest point m_data.x[idx] < x, idx = 0 even if x < m_x[0]
stdVec_d::const_iterator it;
it = std::lower_bound(m_data.x.begin(), m_data.x.end(), x);
return std::max(static_cast<int>(it - m_data.x.begin() - 1), 0);
}
/********************************************************************************
* Derived Class implementations
********************************************************************************/
double Linear::interpolate(double x)
{
size_t i0 = find_base_idx(x);
/* quick return if x equal or near to your data x value */
if (fabs(x - m_data.x[i0]) < m_tolX) return m_data.y[i0];
/* catch possible right hand extrapolation outcome */
if(i0 == m_data.x.size() - 1) --i0;
/* for left hand extrapolation outcome i0 will be zero which is not a problem */
double c1 = (x - m_data.x[i0+1])/(m_data.x[i0] - m_data.x[i0+1]);
double c2 = (x - m_data.x[i0])/(m_data.x[i0+1] - m_data.x[i0]);
return (c1*m_data.y[i0] + c2*m_data.y[i0+1]);
}
double Lagrange::interpolate(double x)
{
size_t i0 = find_base_idx(x);
/* quick return if x equal or near to your data x value */
if (fabs(x - m_data.x[i0]) < m_tolX) return m_data.y[i0];
size_t m = m_data.x.size();
double retval = 0.0;
stdVec_d lambda(m, 1.0);
for(size_t k = 0; k < m; ++k)
{
for(size_t l = 0; l < m; ++l)
{
if(k != l) lambda[k] *=
(x - m_data.x[l])/(m_data.x[k] - m_data.x[l]);
}
retval += lambda[k]*m_data.y[k];
}
return retval;
}
double Aitken::interpolate(double x)
{
size_t m = m_data.x.size();
size_t i0 = find_base_idx(x);
/* quick return if x equal or near to your data x value */
if (fabs(x - m_data.x[i0]) < m_tolX) return m_data.y[i0];
double x1, x2, f1 = 0.0, f2 = 0.0;
data temp(m_data);
for(size_t i = 1; i < m; ++i)
{
for(size_t j = 0; j < m - i; ++j)
{
x1 = temp.x[j];
x2 = temp.x[j+i];
f1 = temp.y[j];
f2 = temp.y[j+1];
temp.y[j] = f2*(x - x1)/(x2 - x1) + f1*(x - x2)/(x1 - x2);
}
}
double retval = temp.y[0];
m_errorEstimate = (fabs(retval - f1)+fabs(retval - f2))/2.0;
return retval;
}
double UpDown::interpolate(double x)
{
const size_t n_max = 21; //i.e. max polynomial order of 20
size_t m = m_data.x.size();
assert(m <= n_max);
size_t i0 = find_base_idx(x);
/* quick return if x equal or near to your data x value */
if (fabs(x - m_data.x[i0]) < m_tolX) return m_data.y[i0];
double dx = fabs(x - m_data.x[i0]);
double dxt = (i0 < m_data.x.size() - 1)? fabs(x - m_data.x[i0+1]) : dx;
if(dxt < dx){++i0;}
size_t j0 = i0;
// set up correction matrices and explicitly assign to zero.
double dp[n_max][n_max];
double dm[n_max][n_max];
for(int i = 0; i < n_max; ++i){
for(int j = 0; j < n_max; ++j){
dp[i][j] = 0.0;
dm[i][j] = 0.0;
}
}
//Compute the correction matrices
for(size_t i = 0; i < m; ++i)
{
dp[i][i] = m_data.y[i];
dm[i][i] = m_data.y[i];
}
for(size_t i = 1; i < m; ++i)
{
for(size_t j = 0; j < m - i; ++j)
{
size_t k = i + j;
dx = (dp[j][k-1] - dm[j+1][k])/(m_data.x[k] - m_data.x[j]);
dp[j][k] = dx*(m_data.x[k] - x);
dm[j][k] = dx*(m_data.x[j] - x);
}
}
//update the approximation
double retval = m_data.y[i0];
size_t it = (x < m_data.x[i0]) ? 1 : 0;
for(size_t i = 1; i < m; ++i)
{
if( it == 1 || j0 == m - 1)
{
i0 -= 1;
m_errorEstimate = dp[i0][j0];
retval += m_errorEstimate;
it = (j0 == m - 1) ? 1 : 0;
}else if( it == 0 || i0 == 0 )
{
j0 += 1;
m_errorEstimate = dm[i0][j0];
retval += m_errorEstimate;
it = (i0 == 0) ? 0 : 1;
}
}
m_errorEstimate = fabs(m_errorEstimate);
return retval;
}
/*************************************************************************
* Cubic Spline Implementation in "Spline.cpp"
*************************************************************************/
} //namespace
|
be0b5e6e16c3936f35b333e55c21c356c7f6e796 | bc9259380da43f23f18ddbd4fef2a736e9d3829b | /logic/src/Node.h | b7e98b8f9ca29a13a47bfa905985ca53d30904f7 | [] | no_license | alecjohanson/robot | fa2677c734a26ac3a924e05e0f072e3b76bd84c9 | 5642843cace7c8f8333fbfc0198c6da31e78834e | refs/heads/master | 2016-09-10T20:18:08.220545 | 2013-12-11T23:10:06 | 2013-12-11T23:10:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 381 | h | Node.h | #ifndef NODE_H_
#define NODE_H_
#include <vector>
class Node {
public:
Node();
virtual ~Node();
void setName(int name);
void setType(int type[6]);
void setOrientation(int orientation);
void addParent (int parent);
int* getNodeType();
private:
int name;
std::vector<int> parents;
int type[6];
int orientation;
};
#endif /* NODE_H_ */
|
bdf6e1b2e2bdca1a4aaf010b3208f803a98ae402 | 001ef27a0d74f6796829ada1a62c5a4e56249b3f | /MiracleTakeALook/MiracleTakeALook/Rabbit.cpp | 24083e675d6855e6e18367b4e32f1394dd0e309b | [] | no_license | 00GOEUN/MTLGAME | 93cd13439a263ac9441ab9f09098f6edabb3229b | 811808ce9ba10f71faf4217bfdf182b1358b753f | refs/heads/main | 2023-07-01T16:34:24.215078 | 2021-08-13T04:30:35 | 2021-08-13T04:30:35 | 389,685,211 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 2,427 | cpp | Rabbit.cpp | #include "Rabbit.h"
#include "DoubleBuffer.h"
#include "RabbitBullet.h"
Rabbit::Rabbit()
{
}
Rabbit::~Rabbit()
{
Release();
}
void Rabbit::Initialize()
{
Hp = 50;
for (int i = 0; i < 128; i++)
m_Bullet[i] = NULL;
Texture[0][0] = (char*)" ∩_∩";
Texture[0][1] = (char*)" ( oㅅo)";
Texture[0][2] = (char*)" o( u u)";
Texture[0][3] = (char*)" U U";
Texture[1][0] = (char*)" ∩_∩";
Texture[1][1] = (char*)"(oㅅo )";
Texture[1][2] = (char*)" (u u )o";
Texture[1][3] = (char*)" U U";
m_strKey = "Rabbit";
// Enemy2
// ∩_∩
// ( oㅅo)
// o( u u)
// U U
TransInfo.Position = Vector3(0.0f, 0.0f);
TransInfo.Scale = Vector3((float)strlen(Texture[0][1]), 4.0f); // Rabbit의 x: 넓이 y: 높이
Speed = 0.2f; // 속도 0.2로 초기화
Horizontal = DIR_RIGHT;
Active = false; // 움직임?
Time = (ULONG)GetTickCount64();
BulletTime = 2500;
}
int Rabbit::Update()
{
int Result = 0;
for (int i = 0; i < 128; i++)
{
Result = 0;
if (m_Bullet[i] != NULL)
Result = m_Bullet[i]->Update();
if (Result)
{
delete m_Bullet[i];
m_Bullet[i] = NULL;
}
}
// x축에 -속도를 빼줌
//TransInfo.Position.x -= Speed;
// x가 3.5보다 크거나 같을 경우
if (Horizontal == DIR_LEFT)
{
TransInfo.Position.x -= Speed;
if (PosX[1] > TransInfo.Position.x)
Horizontal = !Horizontal;
}
else
{
TransInfo.Position.x += Speed;
if (PosX[0] < TransInfo.Position.x)
Horizontal = !Horizontal;
}
if (Time + BulletTime < GetTickCount64())
{
Time = (ULONG)GetTickCount64();
for (int i = 0; i < 128; ++i)
{
if (m_Bullet[i] == NULL)
{
m_Bullet[i] = new RabbitBullet;
m_Bullet[i]->Initialize();
m_Bullet[i]->SetPosition(
TransInfo.Position.x,
TransInfo.Position.y + 1);
m_Bullet[i]->SetHorizontal(Horizontal);
break;
}
}
}
//if (TransInfo.Position.x <= 10.5f)
//{
// Active = false;
// return -1; // 왜 -1 리턴?
//}
//
return 0;
}
void Rabbit::Render()
{
for (int i = 0; i < 128; i++)
{
if (m_Bullet[i] != NULL)
m_Bullet[i]->Render();
}
for (int i = 0; i < 4; ++i)
{
DoubleBuffer::GetInstance()->WriteBuffer(
int(TransInfo.Position.x),
int(TransInfo.Position.y + i),
Texture[Horizontal][i], 4);
}
}
void Rabbit::Release()
{
for (int i = 0; i < 128; i++)
{
if (m_Bullet[i] != NULL)
{
delete m_Bullet[i];
m_Bullet[i] = NULL;
}
}
}
|
6ff9019f7aebcf5631074e8e25ea669757be3dd2 | 76a224129921a59fa54fc8837cf97075efc57825 | /leetcode_algorithm_00057.h | ebc243174b43c459358a512e67786e3014393473 | [] | no_license | popcorn1429/leetcode_algorithm | 67cdd29be0d428f09db6c9be8765e7befa9a124b | a13e20acdd7039f53dc75a2542d3f9e8e1558021 | refs/heads/master | 2021-07-09T02:25:46.113959 | 2020-06-14T16:32:14 | 2020-06-14T16:32:14 | 129,052,016 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,314 | h | leetcode_algorithm_00057.h | /*
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
*/
#ifndef _leetcode_algorithm_00057_h_
#define _leetcode_algorithm_00057_h_
#include "basic_headers.h"
#ifndef min
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif
#ifndef max
#define max(a,b) (((a) < (b)) ? (b) : (a))
#endif
struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
class Solution {
public:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
vector<Interval> result;
bool inserted = false;
for (const Interval &interval : intervals) {
// interval << newInterval
if (interval.end < newInterval.start) {
result.push_back(interval);
continue;
}
// interval X newInterval
if (overlap(interval, newInterval)) {
if (!inserted) {
result.push_back(Interval(min(interval.start, newInterval.start), max(interval.end, newInterval.end)));
inserted = true;
}
else {
result.back().end = max(interval.end, newInterval.end);
}
continue;
}
// interval >> newInterval
if (newInterval.end < interval.start) {
if (!inserted) {
result.push_back(newInterval);
inserted = true;
}
result.push_back(interval);
}
}
if (!inserted) {
result.push_back(newInterval);
}
return result;
}
bool overlap(const Interval &a, const Interval &b) const {
return !(a.end < b.start || b.end < a.start);
}
};
#endif /*_leetcode_algorithm_00057_h_*/
|
5f5ce2cbf8abf882164892c5775d46eacf456bd5 | 751dffa1e2acfd42de4a33ce415b7bdddaeb9b46 | /game/Three.cpp | 589b0cb5946cada3f118f980eb1aaa7f5d6bdb45 | [] | no_license | kulcua/game | 65e40ee97803c7e8939bb7393cb64c32065e0d4a | 309c9d9cb86ef912dbecabda9a27b1662e52b54c | refs/heads/master | 2023-06-24T06:33:55.250646 | 2021-07-29T08:46:03 | 2021-07-29T08:46:03 | 293,836,165 | 0 | 0 | null | 2021-07-28T16:12:04 | 2020-09-08T14:32:02 | C++ | UTF-8 | C++ | false | false | 530 | cpp | Three.cpp | #include "Three.h"
#include "Utils.h"
#include "Game.h"
Three::Three(Curtain* curtain)
{
SetAnimation(THREE_ANI_ID);
vy = -0.2f;
this->curtain = curtain;
die = true;
}
void Three::Render()
{
animation_set->at(0)->Render(x, y, nx, ny);
//RenderBoundingBox();
}
void Three::Update(DWORD dt, vector<LPGAMEOBJECT>* coObjects)
{
CGameObject::Update(dt);
if (vy == 0) {
isStop = true;
}
vy = curtain->vy;
y += dy;
}
void Three::GetBoundingBox(float& l, float& t, float& r, float& b)
{
l = x;
t = y;
r = x;
b = y;
}
|
b51a1e97976de588fd153319a7677d31686a9e9b | 60f777e2d6a3370efb2c7fd6ef299aa54a249a7b | /code/clusterexplorer/includes/ClassTools.hpp | cd829a792c9c63e3dc817db69001f91815fcfba9 | [] | no_license | MrApplejuice/spacedocking-analysis | 3b3f943c2fbcb1510c4158e24d1bbc2a7a8e9eeb | cacdedab5b4e05ea76b00b3423df4cbfa8f6be1d | refs/heads/master | 2021-01-22T03:29:41.444886 | 2014-06-21T22:50:13 | 2014-06-21T22:50:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,078 | hpp | ClassTools.hpp | #ifndef CLASSTOOLS_HPP_
#define CLASSTOOLS_HPP_
#define CONCATENATE_DETAIL(x, y) x##y
#define CONCATENATE(x, y) CONCATENATE_DETAIL(x, y)
#define MAKE_UNIQUE(x) CONCATENATE(x, __COUNTER__)
#define FLEXIBLE_GEN_GETTER(type, name, variable, funcmod) \
virtual type get ## name() funcmod { \
return variable; \
}
#define GEN_GETTER(type, name, variable) FLEXIBLE_GEN_GETTER(type, name, variable, const)
#define FLEXIBLE_GEN_ABSTRACT_GETTER(type, name, funcmod) \
virtual type get ## name() funcmod = 0
#define GEN_ABSTRACT_GETTER(type, name) FLEXIBLE_GEN_ABSTRACT_GETTER(type, name, const)
#define GEN_SETTER_DETAIL(type, name, variable, uniq) \
virtual void set ## name(type uniq) { \
variable = uniq; \
}
#define GEN_SETTER(type, name, variable) GEN_SETTER_DETAIL(type, name, variable, MAKE_UNIQUE(__setterArgument__))
#define GEN_ABSTRACT_SETTER(type, name) \
virtual void set ## name(type uniq) = 0
#define GEN_GETTER_AND_SETTER(type, name, variable) \
GEN_GETTER(type, name, variable) \
GEN_SETTER(type, name, variable)
#endif // CLASSTOOLS_HPP_
|
f161c0062ef2b196ac67a3c3dfb1b41aa28a7d4b | d8c89543c5720bedde7824971de923ad2b7887ee | /Project2/market_helper.h | 0186aafa7d826a3d206262595694bf99c3dc0441 | [] | no_license | matwilwe/CodeSamples | 88241b550dafe78d7db836d35c76c167582c3180 | 4ded522ec59669175e71bf80d39d7efe4310fdf9 | refs/heads/master | 2021-01-11T05:46:55.017411 | 2016-09-28T00:13:26 | 2016-09-28T00:13:26 | 69,408,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 739 | h | market_helper.h | #ifndef MARKET_HELPER_H
#define MARKET_HELPER_H
#include <cctype>
#include <string>
#include <utility>
#include "order.h"
#include <vector>
//Effects: returns true if the string contains only alphanumeric characters or underscores
bool check_string(const std::string &check);
//Effects: returns the index in the vector that contains the string current_client.
unsigned int check_insider(const std::vector<std::string> &insiders, const std::string ¤t_client);
//Effects: returns a pair of const iterators with the greatest difference in buy and sell price,
//given a vector of orders.
std::pair<std::vector<order*>::const_iterator, std::vector<order*>::const_iterator> time_traveler(const std::vector<order*> &ttt_arr);
#endif
|
ebc9dc81dc0e1a065efa27a8abf52da91a26fa25 | 2885e54c807bd70b8eb0cd2bc3ffd5ce51bd66cc | /2007-PIR-Drone Trirotor acrobate/Site trirotor acrobate/Informatique/CNES/club-10.0/utils/ComparateurFichier.h | d75e34ac57d1d8469dcf2fd0f6ec301a790b9bbf | [
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | crubier/my-personal-projects | 622b09ce6d9c846b905fe135892a178c1a0c554b | 8cd26b212b0c61f3d5bbe2de82d49891f3f3602a | refs/heads/master | 2021-09-12T23:09:14.097634 | 2018-04-22T07:45:42 | 2018-04-22T07:45:42 | 130,488,289 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 7,082 | h | ComparateurFichier.h | ///////////////////////////////////////////////////////////////////////////////
//$<AM-V1.0>
//
//$Type
// DEF
//
//$Projet
// Bibam
//$Application
// Club
//$Nom
//> ComparateurFichier.h
//$Resume
// fichier d'en-tête de la classe ComparateurFichier
//
//$Description
// Module de déclaration de la classe
//
//$Contenu
//> class ComparateurFichier
//$Historique
// $Log: ComparateurFichier.h,v $
// Revision 1.7 2000/10/25 10:05:15 club
// correction du nom du chemin vers le fichier d'en-tête ClubConfig.h
//
// Revision 1.6 2000/10/25 09:00:38 club
// modification du répertoire pour l'include ClubConfig.h
//
// Revision 1.5 2000/10/24 14:16:04 club
// utilisation de tests de configuration pour les includes.
//
// Revision 1.4 2000/09/07 08:42:02 club
// utilisation de string de la STL au lieu de ChaineSimple conformément
// aux évolutions réalisées sur les classes de l'interface publique de club.
//
// Revision 1.3 2000/08/04 09:45:46 club
// calcul et affichage du décalage maximal rencontré.
//
// Revision 1.2 2000/07/28 13:07:14 club
// modification de la signature du constructeur pour permettre la prise
// en compte de l'option pour ignorer des lignes du fichier de référence.
//
// Revision 1.1 2000/07/26 09:48:06 club
// Suite à la destruction du répertoire club/utils/club, déplacement
// des fichiers .h dans le répertoire club/utils.
//
// Revision 1.3 2000/07/26 07:30:56 club
// modification profonde de la classe pour permettre l'implantation
// de l'algorithme "Longest Common Subsequence" dans l'analyse des
// fichiers : ajout de l'attribut tabLCS_, modification du constructeur,
// création d'un destructeur et suppression de la méthode repositionner ...
//
// Revision 1.2 2000/07/07 09:51:20 club
// suppression de laméthode initialise et de l'attribut lignesDifferentes_.
// Remplacement de leur utilité algorithmique dans le repositionnement
// par numPremieresLignesEgales.
//
// Revision 1.1 2000/07/03 09:27:36 club
// création d'une classe permettant de comparer deux fichiers tout en
// acceptant une imprécision numérique.
// cette classe est utilisé par l'utilitaire difference
//
//$Version
// $Id: ComparateurFichier.h,v 1.7 2000/10/25 10:05:15 club Exp $
//
//$Auteur
// O. Queyrut CSSI
// Copyright (C) 2000 CNES
//
//$<>
///////////////////////////////////////////////////////////////////////////////
#ifndef __club_ComparateurFichier_h
#define __club_ComparateurFichier_h
#include <club/ClubConfig.h>
#include <ClubConfigNoInstall.h>
#if CLUB_HAVE_NAMESPACES
using namespace std;
#endif
#ifdef HAVE_STL
#include <string>
#endif
#include "StatDifference.h"
#include "ComparateurLigne.h"
#include "club/ClubErreurs.h"
#include "club/TamponTexte.h"
#include "club/Traducteur.h"
///////////////////////////////////////////////////////////////////////////////
//$<AM-V1.0>
//
//$Nom
//> class ComparateurFichier
//$Resume
// classe permettant de comparer un fichier résultat avec
// un fichier référence
//
//$Description
// Cette classe permet de comparer deux fichiers en acceptant une
// imprecision numérique sur les réels. Elle permet de formater
// un message de différence concernant chaque ligne et elle met à jour
// des statistiques sur les différences. Il est possible de recaler
// les tampons si certaines lignes sont propres à un seul d'entre eux.
// L'algorithme utilisé pour connaître quelles sont les lignes communes,
// propres à un fichier ou propres à l'autre est appelé "Longest Common
// Subsequence". Cet algorithme est fourni à l'adresse suivante valide
// au 24/07/2000 :
// http://www.ics.uci.edu/~eppstein/161/960229.html
//
//$Usage
//> construction :
// à partir de deux noms de fichiers, d'une valeur indiquant la
// précision numérique souhaitée, du décalage maximal toléré et
// du nombre de lignes au début et à la fin du fichier res qu'il faut
// ignorer. Le constructeur crée des tampons texte contenant
// le texte des fichiers
//> utilisation :
//> void analyserFichier ()
// analyse les deux fichiers ligne par ligne et permet si nécessaire
// de sauter des lignes propres à un seul des deux fichiers.
//> int decalageRencontreMax ()
// retourne la valeur maximale du décalage rencontré
//$Auteur
// O. Queyrut CSSI
// Copyright (C) 2000 CNES
//
//$<>
///////////////////////////////////////////////////////////////////////////////
class ComparateurFichier
{
public :
// constructeur
ComparateurFichier (const string& fichierRes, const string& fichierRef,
double precision, int decalageMax, int suppLignesResDebut,
int suppLignesResFin, int suppLignesRefDebut,
int suppLignesRefFin) throw (ClubErreurs, bad_alloc);
// destructeur
~ComparateurFichier ();
// comparaisons des tampons tamponRes_ et tamponRef_
void analyserFichier (StatDifference& stats) throw (ClubErreurs);
int decalageRencontreMax () const { return decalageRencontreMax_; }
private :
void analyserLignesEgalesDebut (int& debutRes, const int finRes,
int& debutRef, const int finRef,
StatDifference& stats);
void analyserLignesEgalesFin (const int debutRes, int& finRes,
const int debutRef, int& finRef,
StatDifference& stats);
// cette méthode privée permet de remplir le tableau tabLCS_ par l'algorithme
// "Longest Common Subsequent" de complexité O(nbLignesRes*nbLignesRef)
void initialiser (const int debutRes, const int finRes,
const int debutRef, const int finRef);
// noms du fichier résultat et du fichier référence que l'on compare
string nomFichierRes_;
string nomFichierRef_;
// tampon texte contenant le texte du fichier resultat
TamponTexte tamponRes_;
// tampon texte contenant le texte du fichier référence
TamponTexte tamponRef_;
// précision des calculs souhaitée (pour la comparaison des valeurs numériques)
double precision_;
// valeur du décalage maximal toléré pour le repositionnement des analyseurs
int decalageMax_;
int decalageRencontreMax_;
// nombre de lignes à ne pas analyser au début et à la fin du tampon résultat
int suppLignesResDebut_;
int suppLignesResFin_;
// nombre de lignes à ne pas analyser au début et à la fin du tampon référence
int suppLignesRefDebut_;
int suppLignesRefFin_;
// tableau de taille à 2 dimensions utilisés pour stockés les résultats
// du calcul de la "Longest Common Subsequence"
int** tabLCS_;
};
#endif
|
e555ed78c4290f1f282f3092d20da1ba95aefb13 | c656a019513845ac6bc21915b3ffdce5af989a7a | /source/Library.Shared/HashMap.h | 715045aae629c3ad551d43a187fd4bdb6e1f1b5a | [] | no_license | peterdfinn/FIEA_Game_Engine | ca2b6f4ac0b0fb366f5cffe689e791698d47e935 | 4775469d4772789370896bcbcec9ce93d18f0c99 | refs/heads/master | 2020-03-17T04:23:23.056804 | 2018-05-16T16:20:04 | 2018-05-16T16:20:04 | 133,272,893 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,255 | h | HashMap.h | #pragma once
#include <utility>
#include "Vector.h"
#include "SList.h"
#include "CompareFunctor.h"
#include "HashFunctor.h"
namespace LibraryShared
{
/// <summary>
/// This class implements a hash table with keys of type TKey and buckets that
/// contain elements of type TData.
/// </summary>
template <typename TKey, typename TData, typename TFunctor = HashFunctor<TKey>, typename TCompare = CompareFunctor<TKey>>
class HashMap final
{
public:
using PairType = std::pair<TKey, TData>;
using ChainIterator = typename SList<PairType>::Iterator;
using HashMapT = HashMap<TKey, TData, TFunctor, TCompare>;
/// <summary>
/// This class is an iterator through the buckets.
/// </summary>
class Iterator final
{
friend class HashMap;
public:
/// <summary>
/// This is the default constructor for HashMap::Iterator. It sets
/// mOwner to nullptr and both indices to 0.
/// </summary>
Iterator();
/// <summary>
/// This is the destructor for Iterator. It has been set to the
/// default.
/// </summary>
~Iterator() = default;
/// <summary>
/// This is the copy constructor for Iterator. It has been set to
/// the default.
/// </summary>
/// <param name="other">- A reference to the Iterator to be copied.
/// </param>
Iterator(const Iterator& other);
/// <summary>
/// This is the move constructor for Iterator. It has been set to
/// the default.
/// </summary>
/// <param name="other">- A reference to the Iterator to be moved.
/// </param>
Iterator(Iterator&& other);
/// <summary>
/// This is an overloading of the prefix increment operator. It
/// throws an exception if already pointed past the last entry in
/// the last non-empty bucket in the list.
/// </summary>
/// <returns>A reference to this newly incremented Iterator.
/// </returns>
Iterator& operator++();
/// <summary>
/// This is an overloading of the postfix increment operator. See
/// prefix increment operator documentation.
/// </summary>
/// <param name="">- Dummy parameter to distinguish postfix from
/// prefix versions of this operator.</param>
/// <returns>A copy of the newly incremented Iterator.</returns>
Iterator operator++(int);
/// <summary>
/// This is an overloading of the dereference operator. It returns
/// a reference to the key-value pair to which this Iterator
/// refers.
/// </summary>
/// <returns>A reference to the key-value pair to which this
/// Iterator refers.</returns>
PairType& operator*();
/// <summary>
/// This is an overloading of the dereference operator that returns
/// a pointer to the key-value pair to which this Iterator refers.
/// </summary>
/// <returns>A pointer to the key-value pair to which this Iterator
/// refers.</returns>
PairType* operator->();
/// <summary>
/// This overloading of the equality operator returns true if the
/// two Iterators' owners are the same, if their indices into the
/// vector of buckets are equal, and if their iterators within said
/// bucket are equal.
/// </summary>
/// <param name="other">- A reference to the Iterator to be
/// compared with this one.</param>
/// <returns>True if both Iterators refer to the same key-value
/// pair in the same bucket within the same HashMap; false
/// otherwise.</returns>
bool operator==(const Iterator& other) const;
/// <summary>
/// This overloading of the inquality operator returns false if the
/// two Iterators' owners are the same, if their indices into the
/// vector of buckets are equal, and if their iterators within said
/// bucket are equal.
/// </summary>
/// <param name="other">- A reference to the Iterator to be
/// compared with this one.</param>
/// <returns>False if both Iterators refer to the same key-value
/// pair in the same bucket within the same HashMap; true
/// otherwise.</returns>
bool operator!=(const Iterator& other) const;
/// <summary>
/// The overloading of the copy assignment operator has been set to
/// set to the default.
/// </summary>
/// <param name="other">- A reference to the Iterator to be copied.
/// </param>
/// <returns>A reference to this Iterator.</returns>
Iterator& operator=(const Iterator& other) = default;
/// <summary>
/// The overloading of the move assignment operator has been set to
/// the default.
/// </summary>
/// <param name="other">- A reference to the Iterator to be moved.
/// </param>
/// <returns>A reference to this Iterator.</returns>
Iterator& operator=(Iterator&& other);
private:
/// <summary>
/// This is a pointer to the HashMap that contains this Iterator.
/// </summary>
HashMap* mOwner;
/// <summary>
/// This is the index into the list of buckets.
/// </summary>
uint32_t mBucketIndex;
/// <summary>
/// This is an iterator through the linked list contained within a
/// bucket.
/// </summary>
ChainIterator mIteratorWithinBucket;
/// <summary>
/// This is the standard constructor for HashMap::Iterator. It sets
/// this Iterator to point at the element pointed to by
/// 'iteratorWithinBucket' in bucket number 'bucketIndex' in the
/// HashMap '*owner'.
/// </summary>
/// <param name="owner">- A pointer to the HashMap that contains
/// this Iterator.</param>
/// <param name="bucketIndex">- The index into the list of buckets
/// at which to point this Iterator.</param>
/// <param name="iteratorWithinBucket">- An iterator that refers to
/// the entry in the bucket to which this iterator should refer.
/// </param>
Iterator(HashMap* owner, uint32_t bucketIndex = 0u,
ChainIterator iteratorWithinBucket = ChainIterator());
};
/// <summary>
/// This is the standard constructor for HashMap. It creates a number
/// of buckets and puts an empty linked list in each one.
/// </summary>
/// <param name="numberOfBuckets">- The number of buckets this new hash
/// map should contain.</param>
HashMap(uint32_t numberOfBuckets = 7u);
/// <summary>
/// This is the copy constructor for HashMap.
/// </summary>
/// <param name="other">- A reference to the HashMap to copy.</param>
HashMap(const HashMap& other);
/// <summary>
/// This is the move constrcutor for HashMap.
/// </summary>
/// <param name="other">- A reference to the HashMap to move.</param>
HashMap(HashMap&& other);
/// <summary>
/// This is the destructor for HashMap. It destructs its one and only
/// data member, mBuckets.
/// </summary>
~HashMap() = default;
/// <summary>
/// This is the copy assignment operator for HashMap.
/// </summary>
/// <param name="other">- The HashMap to copy into this one.</param>
/// <returns>A reference to this HashMap, post-copy.</returns>
HashMap& operator=(const HashMap& other);
/// <summary>
/// This is the move assignment operator for HashMap.
/// </summary>
/// <param name="other">- The HashMap to move into this one.</param>
/// <returns>A reference to this HashMap, post-move.</returns>
HashMap& operator=(HashMap&& other);
/// <summary>
/// This method tests two HashMaps for memberwise equality. It returns
/// true if and only if both HashMaps have the same number of entries
/// and all entries in this HashMap can also be found in the other
/// HashMap.
/// </summary>
/// <param name="other">- A reference to the HashMap to be compared to
/// this one.</param>
/// <returns>True if the HashMaps contain exactly the same entries as
/// each other; false otherwise.</returns>
bool operator==(const HashMap& other) const;
/// <summary>
/// This method iterates through this HashMap until it finds a
/// key-value pair with a key equal to 'key' and returns an Iterator
/// that refers to it. If no such pair is found, the end iterator is
/// returned instead.
/// </summary>
/// <param name="key">- The key for which to search.</param>
/// <returns>An iterator that refers to the first key-value pair found
/// that has a key equal to 'key', or the end iterator if no such pair
/// exists in the HashMap.</returns>
Iterator Find(const TKey& key) const;
/// <summary>
/// This method inserts a pair into the HashMap, if it doesn't already
/// exist. In either case, it returns an Iterator that refers to the
/// entry in the HashMap with the key in pair 'toInsert'.
/// </summary>
/// <param name="toInsert">- The key-value pair to insert.</param>
/// <returns>An Iterator that refers to the entry in the HashMap with
/// pair 'toInsert'.</returns>
Iterator Insert(const PairType& toInsert);
/// <summary>
/// This method inserts a pair into the HashMap, if it doesn't already
/// exist. In either case, it returns an Iterator that refers to the
/// entry in the HashMap with pair 'toInsert'. Additionally, unlike the
/// other method named 'Insert', this one outputs a bool indicating
/// whether the pair this method attempted to insert already existed in
/// the HashMap.
/// </summary>
/// <param name="toInsert">- The key-value pair to insert.</param>
/// <param name="alreadyPresent">- An output parameter indicating
/// whether 'toInsert' already existed in the HashMap prior to this
/// method call.</param>
/// <returns>An Iterator that refers to the entry in the HashMap with
/// pair 'toInsert'.</returns>
Iterator Insert(const PairType& toInsert, bool& alreadyPresent);
/// <summary>
/// This method returns a reference to the data entry in the HashMap
/// with key 'key'. If no such pair exists, an exception is thrown.
/// There is also an overloading of this method that is const that
/// behaves analogously to this one.
/// </summary>
/// <param name="index">- The key for which to get the data.</param>
/// <returns>A reference to the data that was found.</returns>
TData& At(const TKey& key);
/// <summary>
/// See non-const version of this method.
/// </summary>
/// <param name="key">- The key for which to get the data.</param>
/// <returns>A reference to the data that was found.</returns>
const TData& At(const TKey& key) const;
/// <summary>
/// This overloading of the index operator finds a key-value pair in
/// the HashMap that has key 'key'. If no such pair exists, then one
/// is created.
/// </summary>
/// <param name="key">- The key for which to get the data.</param>
/// <returns>A reference to the data that was found (or created).
/// </returns>
TData& operator[](const TKey& key);
/// <summary>
/// This method removes the key-value pair with key 'key' from the
/// HashMap, if one exists.
/// </summary>
/// <param name="key">- The key to remove from the HashMap.</param>
/// <returns>True if a pair was successfully found and removed; false
/// otherwise.</returns>
bool Remove(const TKey& key);
/// <summary>
/// This method removes all pairs from the HashMap.
/// </summary>
void Clear();
/// <summary>
/// This method returns the number of key-value pairs currently in this
/// HashMap.
/// </summary>
/// <returns>The number of key-value pairs in this HashMap.</returns>
uint32_t Size() const;
/// <summary>
/// This method returns a bool indicating whether there is a key-value
/// pair with key 'key' in this HashMap.
/// </summary>
/// <param name="key">- The key for which to search.</param>
/// <returns>True if there is a pair with key 'key' in this HashMap;
/// false otherwise.</returns>
bool ContainsKey(const TKey& key) const;
/// <summary>
/// This method returns an Iterator that refers to a key-value pair in
/// the first non-empty bucket of this HashMap.
/// </summary>
/// <returns>An iterator that refers to the beginning of this HashMap.
/// </returns>
Iterator begin() const;
/// <summary>
/// This method returns an Iterator that is meant to represent one
/// entry past the last entry in this HashMap.
/// </summary>
/// <returns>An Iterator that represents one entry past the last entry
/// in this HashMap.</returns>
Iterator end() const;
private:
/// <summary>
/// This is how the buckets of my hash map are implemented.
/// </summary>
Vector<SList<PairType>> mBuckets;
/// <summary>
/// This is a private overloading of the Find method. It iterates
/// through the HashMap until it finds a key-value pair with a key
/// equal to 'key' and returns an Iterator that refers to it. If no
/// such pair is found, the end iterator is returned instead. Unlike
/// the public version of this method, this version outputs the hash
/// computed via the reference parameter 'hash'.
/// </summary>
/// <param name="key">- The key to be searched for.</param>
/// <param name="hash">- A variable in which the result of hashing key
/// to an index will be stored.</param>
/// <returns>An iterator that refers to the first key-value pair found
/// that has a key equal to 'key', or the end iterator if there is no
/// such pair in the HashMap.</returns>
Iterator Find(const TKey& key, uint32_t& hash) const;
};
}
#include "HashMap.inl" |
adefc6de9d70f53c5ef9d2e32ba22eff8a5448a6 | 0b0cf9e1e4ff13fd485599f5b3a97e8c4891aa4e | /cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_SMI.hpp | b6ce4d097893430156b86ae0cc237874f37fef9d | [
"Apache-2.0"
] | permissive | juvenz/ydk-cpp | 92b537488c30b4ba7f47fc04f0f61ab0986764a9 | 214b4e49c4338b778306c9cd1d2f4514fe84c63c | refs/heads/master | 2020-07-02T06:30:40.258180 | 2019-05-31T22:20:28 | 2019-05-31T22:20:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,424 | hpp | CISCO_SMI.hpp | #ifndef _CISCO_SMI_
#define _CISCO_SMI_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
#include "ydk_ietf/ietf_yang_smiv2.hpp"
namespace cisco_ios_xe {
namespace CISCO_SMI {
class CiscoProducts : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoProducts();
~CiscoProducts();
}; // CiscoProducts
class Local : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
Local();
~Local();
}; // Local
class Temporary : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
Temporary();
~Temporary();
}; // Temporary
class Pakmon : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
Pakmon();
~Pakmon();
}; // Pakmon
class Workgroup : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
Workgroup();
~Workgroup();
}; // Workgroup
class OtherEnterprises : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
OtherEnterprises();
~OtherEnterprises();
}; // OtherEnterprises
class CiscoSB : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoSB();
~CiscoSB();
}; // CiscoSB
class CiscoSMB : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoSMB();
~CiscoSMB();
}; // CiscoSMB
class CiscoAgentCapability : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoAgentCapability();
~CiscoAgentCapability();
}; // CiscoAgentCapability
class CiscoConfig : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoConfig();
~CiscoConfig();
}; // CiscoConfig
class CiscoMgmt : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoMgmt();
~CiscoMgmt();
}; // CiscoMgmt
class CiscoExperiment : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoExperiment();
~CiscoExperiment();
}; // CiscoExperiment
class CiscoAdmin : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoAdmin();
~CiscoAdmin();
}; // CiscoAdmin
class CiscoProxy : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoProxy();
~CiscoProxy();
}; // CiscoProxy
class CiscoRptrGroupObjectID : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoRptrGroupObjectID();
~CiscoRptrGroupObjectID();
}; // CiscoRptrGroupObjectID
class CiscoUnknownRptrGroup : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoUnknownRptrGroup();
~CiscoUnknownRptrGroup();
}; // CiscoUnknownRptrGroup
class Cisco2505RptrGroup : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
Cisco2505RptrGroup();
~Cisco2505RptrGroup();
}; // Cisco2505RptrGroup
class Cisco2507RptrGroup : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
Cisco2507RptrGroup();
~Cisco2507RptrGroup();
}; // Cisco2507RptrGroup
class Cisco2516RptrGroup : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
Cisco2516RptrGroup();
~Cisco2516RptrGroup();
}; // Cisco2516RptrGroup
class CiscoWsx5020RptrGroup : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoWsx5020RptrGroup();
~CiscoWsx5020RptrGroup();
}; // CiscoWsx5020RptrGroup
class CiscoChipSets : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoChipSets();
~CiscoChipSets();
}; // CiscoChipSets
class CiscoChipSetSaint1 : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoChipSetSaint1();
~CiscoChipSetSaint1();
}; // CiscoChipSetSaint1
class CiscoChipSetSaint2 : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoChipSetSaint2();
~CiscoChipSetSaint2();
}; // CiscoChipSetSaint2
class CiscoChipSetSaint3 : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoChipSetSaint3();
~CiscoChipSetSaint3();
}; // CiscoChipSetSaint3
class CiscoChipSetSaint4 : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoChipSetSaint4();
~CiscoChipSetSaint4();
}; // CiscoChipSetSaint4
class CiscoModules : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoModules();
~CiscoModules();
}; // CiscoModules
class Lightstream : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
Lightstream();
~Lightstream();
}; // Lightstream
class Ciscoworks : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
Ciscoworks();
~Ciscoworks();
}; // Ciscoworks
class Newport : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
Newport();
~Newport();
}; // Newport
class CiscoPartnerProducts : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoPartnerProducts();
~CiscoPartnerProducts();
}; // CiscoPartnerProducts
class CiscoPolicy : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoPolicy();
~CiscoPolicy();
}; // CiscoPolicy
class CiscoPIB : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoPIB();
~CiscoPIB();
}; // CiscoPIB
class CiscoPolicyAuto : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoPolicyAuto();
~CiscoPolicyAuto();
}; // CiscoPolicyAuto
class CiscoPibToMib : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoPibToMib();
~CiscoPibToMib();
}; // CiscoPibToMib
class CiscoDomains : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoDomains();
~CiscoDomains();
}; // CiscoDomains
class CiscoTDomainUdpIpv4 : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoTDomainUdpIpv4();
~CiscoTDomainUdpIpv4();
}; // CiscoTDomainUdpIpv4
class CiscoTDomainUdpIpv6 : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoTDomainUdpIpv6();
~CiscoTDomainUdpIpv6();
}; // CiscoTDomainUdpIpv6
class CiscoTDomainTcpIpv4 : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoTDomainTcpIpv4();
~CiscoTDomainTcpIpv4();
}; // CiscoTDomainTcpIpv4
class CiscoTDomainTcpIpv6 : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoTDomainTcpIpv6();
~CiscoTDomainTcpIpv6();
}; // CiscoTDomainTcpIpv6
class CiscoTDomainLocal : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoTDomainLocal();
~CiscoTDomainLocal();
}; // CiscoTDomainLocal
class CiscoTDomainClns : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoTDomainClns();
~CiscoTDomainClns();
}; // CiscoTDomainClns
class CiscoTDomainCons : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoTDomainCons();
~CiscoTDomainCons();
}; // CiscoTDomainCons
class CiscoTDomainDdp : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoTDomainDdp();
~CiscoTDomainDdp();
}; // CiscoTDomainDdp
class CiscoTDomainIpx : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoTDomainIpx();
~CiscoTDomainIpx();
}; // CiscoTDomainIpx
class CiscoTDomainSctpIpv4 : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoTDomainSctpIpv4();
~CiscoTDomainSctpIpv4();
}; // CiscoTDomainSctpIpv4
class CiscoTDomainSctpIpv6 : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoTDomainSctpIpv6();
~CiscoTDomainSctpIpv6();
}; // CiscoTDomainSctpIpv6
class CiscoCIB : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoCIB();
~CiscoCIB();
}; // CiscoCIB
class CiscoCibMmiGroup : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoCibMmiGroup();
~CiscoCibMmiGroup();
}; // CiscoCibMmiGroup
class CiscoCibProvGroup : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoCibProvGroup();
~CiscoCibProvGroup();
}; // CiscoCibProvGroup
class CiscoPKI : public ietf::ietf_yang_smiv2::ObjectIdentity, virtual ydk::Identity
{
public:
CiscoPKI();
~CiscoPKI();
}; // CiscoPKI
}
}
#endif /* _CISCO_SMI_ */
|
375b851076ca3ac4093eeea07ac407d1f5bfacba | defbfa749de9f5e09d11d3f2e6f79ab9ea6cc56e | /trie/main.cpp | 56ae11a4f0e87b1e29ec9406385df3a60b3e1f21 | [] | no_license | tangzhirong/Massive-string-search-C-language | 3d64f88b76caf224dbea934c578d2e9800f1ca19 | 9f85614feac7dcf241fe8647a0175b347c15a15b | refs/heads/master | 2021-01-10T02:49:53.588757 | 2016-03-14T04:26:21 | 2016-03-14T04:26:21 | 53,825,513 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 473 | cpp | main.cpp |
#include<stdio.h>
#include<stdlib.h>
#include "trie.h"
int main(int argc,char *argv[])
{
FILE * fp_strpool;
FILE * fp_checkedstr;
FILE * fp_result;
if (argc != 4)
{
printf("argv error\n");
return 0;
}
fp_strpool = fopen(argv[1], "r");
fp_checkedstr = fopen(argv[2], "r");
fp_result = fopen(argv[3], "w");
trie_update_check(fp_strpool, fp_checkedstr, fp_result);
fclose(fp_strpool);
fclose(fp_checkedstr);
fclose(fp_result);
return 0;
}
|
c98eaabea517e274c618180ea280b9226de5934a | 0bc131ca13514fe84fa1e450de44776774751a92 | /Sandbox/src/sandbox_app.cpp | 0f7c4d3687a9ed15c4ce7f779a35d7538d73b54a | [
"Apache-2.0"
] | permissive | TalosGame/Meteor | ed17823b6b963281a855560e064c32c8874bad0a | 9c63c4333bf261f6c08635b3e9058228f39de6cc | refs/heads/master | 2020-09-06T23:04:03.277790 | 2020-04-10T00:34:59 | 2020-04-10T00:34:59 | 220,583,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,723 | cpp | sandbox_app.cpp | /*!
* FileName: sandbox_app.cpp
* Copyright: TalosGame Studio Co., Ltd
* Data: 2019/11/09 13:20
* Author: miller
* Desc:
*/
#include <meteor.h>
#include <meteor/core/entry_point.h>
#include "platform/opengl/opengl_shader.h"
#include "game_layer.h"
class TestLayer : public mtr::Layer
{
public:
TestLayer() : camera_controller_(1280.0f / 720.0f)
{
float vertices[3 * 7] = {
-0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f
};
uint32 indices[3] = { 0, 1, 2 };
vertex_array_ = mtr::VertexArray::Create();
mtr::Ref<mtr::VertexBuffer> vertex_buffer;
vertex_buffer = mtr::VertexBuffer::Create(vertices, sizeof(vertices));
{
mtr::BufferLayout layout = {
{mtr::ShaderDataType::Float3, "a_Position"},
{mtr::ShaderDataType::Float4, "a_Color"}
};
vertex_buffer->set_layout(layout);
}
mtr::Ref<mtr::IndexBuffer> index_buffer;
index_buffer = mtr::IndexBuffer::Create(indices, sizeof(indices) / sizeof(uint32));
vertex_array_->AddVertexBuffer(vertex_buffer);
vertex_array_->SetIndexBuffer(index_buffer);
float square_vertices[5 * 4] = {
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.0f, 0.0f, 1.0f
};
uint32 square_indices[6] = { 0, 1, 2, 2, 3, 0 };
square_va_ = mtr::VertexArray::Create();
mtr::Ref<mtr::VertexBuffer> square_vb;
square_vb = mtr::VertexBuffer::Create(square_vertices, sizeof(square_vertices));
{
mtr::BufferLayout layout = {
{mtr::ShaderDataType::Float3, "a_Position"},
{mtr::ShaderDataType::Float2, "a_TexCoord"}
};
square_vb->set_layout(layout);
}
mtr::Ref<mtr::IndexBuffer> square_ib;
square_ib = mtr::IndexBuffer::Create(square_indices, sizeof(square_indices) / sizeof(uint32));
square_va_->AddVertexBuffer(square_vb);
square_va_->SetIndexBuffer(square_ib);
std::string vertex_src = R"(
#version 330 core
layout(location = 0) in vec3 a_Position;
layout(location = 1) in vec4 a_Color;
out vec3 v_Position;
out vec4 v_Color;
uniform mat4 u_ViewProjection;
uniform mat4 u_ModelMatrix;
void main()
{
v_Position = a_Position;
v_Color = a_Color;
gl_Position = u_ViewProjection * u_ModelMatrix * vec4(a_Position, 1.0f);
}
)";
std::string fragment_src = R"(
#version 330 core
layout(location = 0) out vec4 color;
in vec3 v_Position;
in vec4 v_Color;
void main()
{
color = vec4(v_Position * 0.5f + 0.5f, 1.0f);
color = v_Color;
}
)";
shader_ = mtr::Shader::Create(vertex_src, fragment_src);
logo_texture_ = mtr::Texture2D::Create("res/Checkerboard.png");
auto tex_shader_ = mtr::ShaderManager::Load("res/shaders/texture.glsl");
std::dynamic_pointer_cast<mtr::OpenGLShader>(tex_shader_)->Bind();
std::dynamic_pointer_cast<mtr::OpenGLShader>(tex_shader_)->UploadUniformInt("u_Texture", 0);
}
~TestLayer() = default;
virtual void Update(mtr::Time dt) override
{
camera_controller_.OnUpdate(dt);
if (mtr::Input::IsKeyPressed(MTR_KEY_J))
obj_postion_.x -= camera_move_speed_ * dt;
else if (mtr::Input::IsKeyPressed(MTR_KEY_L))
obj_postion_.x += camera_move_speed_ * dt;
if (mtr::Input::IsKeyPressed(MTR_KEY_I))
obj_postion_.y += camera_move_speed_ * dt;
else if (mtr::Input::IsKeyPressed(MTR_KEY_K))
obj_postion_.y -= camera_move_speed_ * dt;
mtr::RendererCommand::SetClearColor({ 0.1f, 0.1f, 0.1f, 1.0f });
mtr::RendererCommand::Clear();
mtr::Renderer::BeginScene(camera_controller_.camera());
{
glm::mat4 scale = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f));
glm::mat4 transfrom = glm::translate(glm::mat4(1.0f), obj_postion_) * scale;
//mtr::Renderer::Submit(shader_, vertex_array_, transfrom);
auto texture_shader = mtr::ShaderManager::Get("texture");
logo_texture_->Bind();
mtr::Renderer::Submit(texture_shader, square_va_, transfrom);
}
mtr::Renderer::EndScene();
}
virtual void OnEvent(mtr::Event& e) override
{
camera_controller_.OnEvent(e);
}
private:
mtr::Camera2DController camera_controller_;
mtr::Ref<mtr::VertexArray> vertex_array_;
mtr::Ref<mtr::Shader> shader_;
mtr::Ref<mtr::VertexArray> square_va_;
mtr::Ref<mtr::Texture2D> logo_texture_;
glm::vec3 square_color_ = { 0.2f, 0.3f, 0.8f };
glm::vec3 obj_postion_ = { 0.0f, 0.0f, 0.0f };
float camera_move_speed_ = 1.0f;
float camera_rotation_speed_ = 30.0f;
};
class Sandbox : public mtr::Application
{
public:
Sandbox()
{
//PushLayer(new TestLayer());
PushLayer(new GameLayer());
}
~Sandbox()
{
}
private:
};
mtr::Application* mtr::CreateApplication()
{
return new Sandbox();
}
|
a70aa2bc43db8d968bb8f4219ca36379ec466a65 | 6f224b734744e38062a100c42d737b433292fb47 | /clang-tools-extra/test/clang-tidy/checkers/readability/simplify-boolean-expr-case.cpp | 2b3bf2e46d4c29c6f918cdfc7e936e64a14ec3db | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
] | permissive | smeenai/llvm-project | 1af036024dcc175c29c9bd2901358ad9b0e6610e | 764287f1ad69469cc264bb094e8fcdcfdd0fcdfb | refs/heads/main | 2023-09-01T04:26:38.516584 | 2023-08-29T21:11:41 | 2023-08-31T22:16:12 | 216,062,316 | 0 | 0 | Apache-2.0 | 2019-10-18T16:12:03 | 2019-10-18T16:12:03 | null | UTF-8 | C++ | false | false | 16,207 | cpp | simplify-boolean-expr-case.cpp | // RUN: %check_clang_tidy %s readability-simplify-boolean-expr %t
bool switch_stmt(int i, int j, bool b) {
switch (i) {
case 0:
if (b == true)
j = 10;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(b\)}}
// CHECK-FIXES-NEXT: {{j = 10;}}
case 1:
if (b == false)
j = -20;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(!b\)}}
// CHECK-FIXES-NEXT: {{j = -20;}}
case 2:
if (b && true)
j = 10;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(b\)}}
// CHECK-FIXES-NEXT: {{j = 10;}}
case 3:
if (b && false)
j = -20;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(false\)}}
// CHECK-FIXES-NEXT: {{j = -20;}}
case 4:
if (b || true)
j = 10;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(true\)}}
// CHECK-FIXES-NEXT: {{j = 10;}}
// CHECK-FIXES-NEXT: {{break;}}
case 5:
if (b || false)
j = -20;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(b\)}}
// CHECK-FIXES-NEXT: {{j = -20;}}
case 6:
return i > 0 ? true : false;
// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: {{.*}} in ternary expression result
// CHECK-FIXES: {{return i > 0;}}
case 7:
return i > 0 ? false : true;
// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: {{.*}} in ternary expression result
// CHECK-FIXES: {{return i <= 0;}}
case 8:
if (true)
j = 10;
else
j = -20;
break;
// CHECK-MESSAGES: :[[@LINE-5]]:9: warning: {{.*}} in if statement condition
// CHECK-FIXES: {{j = 10;$}}
// CHECK-FIXES-NEXT: {{break;$}}
case 9:
if (false)
j = -20;
else
j = 10;
break;
// CHECK-MESSAGES: :[[@LINE-5]]:9: warning: {{.*}} in if statement condition
// CHECK-FIXES: {{j = 10;}}
// CHECK-FIXES-NEXT: {{break;}}
case 10:
if (j > 10)
return true;
else
return false;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} in conditional return statement
// CHECK-FIXES: {{return j > 10;}}
case 11:
if (j > 10)
return false;
else
return true;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} in conditional return statement
// CHECK-FIXES: {{return j <= 10;}}
case 12:
if (j > 10)
b = true;
else
b = false;
return b;
// CHECK-MESSAGES: :[[@LINE-4]]:11: warning: {{.*}} in conditional assignment
// CHECK-FIXES: {{b = j > 10;}}
// CHECK-FIXES-NEXT: {{return b;}}
case 13:
if (j > 10)
b = false;
else
b = true;
return b;
// CHECK-MESSAGES: :[[@LINE-4]]:11: warning: {{.*}} in conditional assignment
// CHECK-FIXES: {{b = j <= 10;}}
// CHECK-FIXES-NEXT: {{return b;}}
case 14:
if (j > 10)
return true;
return false;
// CHECK-MESSAGES: :[[@LINE-2]]:14: warning: {{.*}} in conditional return
// FIXES: {{return j > 10;}}
case 15:
if (j > 10)
return false;
return true;
// CHECK-MESSAGES: :[[@LINE-2]]:14: warning: {{.*}} in conditional return
// FIXES: {{return j <= 10;}}
case 16:
if (j > 10)
return true;
return true;
return false;
case 17:
if (j > 10)
return false;
return false;
return true;
case 100: {
if (b == true)
j = 10;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(b\)}}
// CHECK-FIXES-NEXT: {{j = 10;}}
}
case 101: {
if (b == false)
j = -20;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(!b\)}}
// CHECK-FIXES-NEXT: {{j = -20;}}
}
case 102: {
if (b && true)
j = 10;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(b\)}}
// CHECK-FIXES-NEXT: {{j = 10;}}
}
case 103: {
if (b && false)
j = -20;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(false\)}}
// CHECK-FIXES-NEXT: {{j = -20;}}
}
case 104: {
if (b || true)
j = 10;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(true\)}}
// CHECK-FIXES-NEXT: {{j = 10;}}
// CHECK-FIXES-NEXT: {{break;}}
}
case 105: {
if (b || false)
j = -20;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(b\)}}
// CHECK-FIXES-NEXT: {{j = -20;}}
}
case 106: {
return i > 0 ? true : false;
// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: {{.*}} in ternary expression result
// CHECK-FIXES: {{return i > 0;}}
}
case 107: {
return i > 0 ? false : true;
// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: {{.*}} in ternary expression result
// CHECK-FIXES: {{return i <= 0;}}
}
case 108: {
if (true)
j = 10;
else
j = -20;
break;
// CHECK-MESSAGES: :[[@LINE-5]]:9: warning: {{.*}} in if statement condition
// CHECK-FIXES: {{j = 10;$}}
// CHECK-FIXES-NEXT: {{break;$}}
}
case 109: {
if (false)
j = -20;
else
j = 10;
break;
// CHECK-MESSAGES: :[[@LINE-5]]:9: warning: {{.*}} in if statement condition
// CHECK-FIXES: {{j = 10;}}
// CHECK-FIXES-NEXT: {{break;}}
}
case 110: {
if (j > 10)
return true;
else
return false;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} in conditional return statement
// CHECK-FIXES: {{return j > 10;}}
}
case 111: {
if (j > 10)
return false;
else
return true;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} in conditional return statement
// CHECK-FIXES: {{return j <= 10;}}
}
case 112: {
if (j > 10)
b = true;
else
b = false;
return b;
// CHECK-MESSAGES: :[[@LINE-4]]:11: warning: {{.*}} in conditional assignment
// CHECK-FIXES: {{b = j > 10;}}
// CHECK-FIXES-NEXT: {{return b;}}
}
case 113: {
if (j > 10)
b = false;
else
b = true;
return b;
// CHECK-MESSAGES: :[[@LINE-4]]:11: warning: {{.*}} in conditional assignment
// CHECK-FIXES: {{b = j <= 10;}}
// CHECK-FIXES-NEXT: {{return b;}}
}
case 114: {
if (j > 10)
return true;
return false;
// CHECK-MESSAGES: :[[@LINE-2]]:14: warning: {{.*}} in conditional return
// CHECK-FIXES: {{return j > 10;}}
}
case 115: {
if (j > 10)
return false;
return true;
// CHECK-MESSAGES: :[[@LINE-2]]:14: warning: {{.*}} in conditional return
// CHECK-FIXES: {{return j <= 10;}}
}
case 116: {
return false;
if (j > 10)
return true;
}
case 117: {
return true;
if (j > 10)
return false;
}
}
return j > 0;
}
bool default_stmt0(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (b == true)
j = 10;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(b\)}}
// CHECK-FIXES-NEXT: {{j = 10;}}
}
return false;
}
bool default_stmt1(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (b == false)
j = -20;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(!b\)}}
// CHECK-FIXES-NEXT: {{j = -20;}}
}
return false;
}
bool default_stmt2(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (b && true)
j = 10;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(b\)}}
// CHECK-FIXES-NEXT: {{j = 10;}}
}
return false;
}
bool default_stmt3(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (b && false)
j = -20;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(false\)}}
// CHECK-FIXES-NEXT: {{j = -20;}}
}
return false;
}
bool default_stmt4(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (b || true)
j = 10;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(true\)}}
// CHECK-FIXES-NEXT: {{j = 10;}}
// CHECK-FIXES-NEXT: {{break;}}
}
return false;
}
bool default_stmt5(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (b || false)
j = -20;
break;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(b\)}}
// CHECK-FIXES-NEXT: {{j = -20;}}
}
return false;
}
bool default_stmt6(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
return i > 0 ? true : false;
// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: {{.*}} in ternary expression result
// CHECK-FIXES: {{return i > 0;}}
}
return false;
}
bool default_stmt7(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
return i > 0 ? false : true;
// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: {{.*}} in ternary expression result
// CHECK-FIXES: {{return i <= 0;}}
}
return false;
}
bool default_stmt8(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (true)
j = 10;
else
j = -20;
break;
// CHECK-MESSAGES: :[[@LINE-5]]:9: warning: {{.*}} in if statement condition
// CHECK-FIXES: {{j = 10;$}}
// CHECK-FIXES-NEXT: {{break;$}}
}
return false;
}
bool default_stmt9(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (false)
j = -20;
else
j = 10;
break;
// CHECK-MESSAGES: :[[@LINE-5]]:9: warning: {{.*}} in if statement condition
// CHECK-FIXES: {{j = 10;}}
// CHECK-FIXES-NEXT: {{break;}}
}
return false;
}
bool default_stmt10(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (j > 10)
return true;
else
return false;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} in conditional return statement
// CHECK-FIXES: {{return j > 10;}}
}
return false;
}
bool default_stmt11(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (j > 10)
return false;
else
return true;
// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: {{.*}} in conditional return statement
// CHECK-FIXES: {{return j <= 10;}}
}
return false;
}
bool default_stmt12(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (j > 10)
b = true;
else
b = false;
return b;
// CHECK-MESSAGES: :[[@LINE-4]]:11: warning: {{.*}} in conditional assignment
// CHECK-FIXES: {{b = j > 10;}}
// CHECK-FIXES-NEXT: {{return b;}}
}
return false;
}
bool default_stmt13(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (j > 10)
b = false;
else
b = true;
return b;
// CHECK-MESSAGES: :[[@LINE-4]]:11: warning: {{.*}} in conditional assignment
// CHECK-FIXES: {{b = j <= 10;}}
// CHECK-FIXES-NEXT: {{return b;}}
}
return false;
}
bool default_stmt14(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (j > 10)
return true;
return false;
// CHECK-MESSAGES: :[[@LINE-2]]:14: warning: {{.*}} in conditional return
// FIXES: {{return j > 10;}}
}
return false;
}
bool default_stmt15(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (j > 10)
return false;
return true;
// CHECK-MESSAGES: :[[@LINE-2]]:14: warning: {{.*}} in conditional return
// FIXES: {{return j <= 10;}}
}
return false;
}
bool default_stmt16(int i, int j, bool b) {
switch (i) {
case 0:
return false;
default:
if (j > 10)
return true;
}
return false;
}
bool default_stmt17(int i, int j, bool b) {
switch (i) {
case 0:
return true;
default:
if (j > 10)
return false;
}
return false;
}
bool label_stmt0(int i, int j, bool b) {
label:
if (b == true)
j = 10;
// CHECK-MESSAGES: :[[@LINE-2]]:12: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(b\)}}
// CHECK-FIXES-NEXT: {{j = 10;}}
return false;
}
bool label_stmt1(int i, int j, bool b) {
label:
if (b == false)
j = -20;
// CHECK-MESSAGES: :[[@LINE-2]]:12: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(!b\)}}
// CHECK-FIXES-NEXT: {{j = -20;}}
return false;
}
bool label_stmt2(int i, int j, bool b) {
label:
if (b && true)
j = 10;
// CHECK-MESSAGES: :[[@LINE-2]]:12: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(b\)}}
// CHECK-FIXES-NEXT: {{j = 10;}}
return false;
}
bool label_stmt3(int i, int j, bool b) {
label:
if (b && false)
j = -20;
// CHECK-MESSAGES: :[[@LINE-2]]:12: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(false\)}}
// CHECK-FIXES-NEXT: {{j = -20;}}
return false;
}
bool label_stmt4(int i, int j, bool b) {
label:
if (b || true)
j = 10;
// CHECK-MESSAGES: :[[@LINE-2]]:12: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(true\)}}
// CHECK-FIXES-NEXT: {{j = 10;}}
return false;
}
bool label_stmt5(int i, int j, bool b) {
label:
if (b || false)
j = -20;
// CHECK-MESSAGES: :[[@LINE-2]]:12: warning: {{.*}} to boolean operator
// CHECK-FIXES: {{if \(b\)}}
// CHECK-FIXES-NEXT: {{j = -20;}}
return false;
}
bool label_stmt6(int i, int j, bool b) {
label:
return i > 0 ? true : false;
// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: {{.*}} in ternary expression result
// CHECK-FIXES: {{return i > 0;}}
}
bool label_stmt7(int i, int j, bool b) {
label:
return i > 0 ? false : true;
// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: {{.*}} in ternary expression result
// CHECK-FIXES: {{return i <= 0;}}
}
bool label_stmt8(int i, int j, bool b) {
label:
if (true)
j = 10;
else
j = -20;
// CHECK-MESSAGES: :[[@LINE-4]]:7: warning: {{.*}} in if statement condition
// CHECK-FIXES: {{j = 10;$}}
return false;
}
bool label_stmt9(int i, int j, bool b) {
label:
if (false)
j = -20;
else
j = 10;
// CHECK-MESSAGES: :[[@LINE-4]]:7: warning: {{.*}} in if statement condition
// CHECK-FIXES: {{j = 10;}}
return false;
}
bool label_stmt10(int i, int j, bool b) {
label:
if (j > 10)
return true;
else
return false;
// CHECK-MESSAGES: :[[@LINE-3]]:12: warning: {{.*}} in conditional return statement
// CHECK-FIXES: {{return j > 10;}}
}
bool label_stmt11(int i, int j, bool b) {
label:
if (j > 10)
return false;
else
return true;
// CHECK-MESSAGES: :[[@LINE-3]]:12: warning: {{.*}} in conditional return statement
// CHECK-FIXES: {{return j <= 10;}}
}
bool label_stmt12(int i, int j, bool b) {
label:
if (j > 10)
b = true;
else
b = false;
return b;
// CHECK-MESSAGES: :[[@LINE-4]]:9: warning: {{.*}} in conditional assignment
// CHECK-FIXES: {{b = j > 10;}}
// CHECK-FIXES-NEXT: {{return b;}}
}
bool label_stmt13(int i, int j, bool b) {
label:
if (j > 10)
b = false;
else
b = true;
return b;
// CHECK-MESSAGES: :[[@LINE-4]]:9: warning: {{.*}} in conditional assignment
// CHECK-FIXES: {{b = j <= 10;}}
// CHECK-FIXES-NEXT: {{return b;}}
}
bool label_stmt14(int i, int j, bool b) {
label:
if (j > 10)
return true;
return false;
// CHECK-MESSAGES: :[[@LINE-2]]:12: warning: {{.*}} in conditional return
// FIXES: {{return j > 10;}}
}
bool label_stmt15(int i, int j, bool b) {
label:
if (j > 10)
return false;
return true;
// CHECK-MESSAGES: :[[@LINE-2]]:12: warning: {{.*}} in conditional return
// FIXES: {{return j <= 10;}}
}
|
84c4b0ee4bbe2ec4d60a32242b35e6a06dfea8bd | f413f0700b7fa20eef3071d0cac76b877803df9f | /bullpen_sketch/view.cpp | d1654685e4d05667673e73f5be56bca0eddbdfa6 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | estriz27/bullpen | d4d94d2ab90b18a8872dd299cf2ecd113c223f0c | 11ee415d7f2b2b211a2c9e34a173e016f298b85c | refs/heads/master | 2020-04-06T07:05:04.917720 | 2016-09-16T06:05:47 | 2016-09-16T06:05:47 | 63,977,670 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,545 | cpp | view.cpp | #include "view.hpp"
View::View(const int port):server(port){
lcd.begin(16,2);
server.begin();
lcd.setRGB(0,0,255);
lcd.setCursor(0,1);
lcd.print("Employee Log");
}
void View::update(String name, bool isIn,std::vector<Person> inList, std::vector<Person> outList){
updateLCD(name, isIn);
updateHTML(inList, outList);
}
void View::updateLCD(String name, bool isIn){
lcd.clear();
lcd.print(name);
if(isIn){
lcd.setRGB(BLColorG[0],BLColorG[1],BLColorG[2]);
}
else{
lcd.setRGB(BLColorR[0],BLColorR[1],BLColorR[2]);
}
}
void View::updateHTML(std::vector<Person> inList, std::vector<Person> outList){
// listen for incoming clients
WiFiClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the response
client.println("Refresh: 2"); // refresh the page automatically every 2 sec
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<title>Employee Log using Grove Indoor Environment Kit using Intel Edison</title>");
client.println("<font face=\"Arial\" color=\"#0071c5\"/>");
client.println("<style>");
client.println("table, th, td{");
client.println("border: 1px solid #333;");
client.println("}");
client.println("</style>");
client.println("<h1 align=\"center\">Employee Log</h1>");
client.print("<br />");
client.println("<div class = \"container\">");
client.println("<table align= \"center\">");
client.println("<tr>");
client.println("<th>IN</th>");
client.println("<th>OUT</th>");
client.println("<tr>");
int larger = outList.size();
if (inList.size()>outList.size()){
larger = inList.size();
}
for(int i=0; i < larger; i++){
client.println("<tr>");
client.print("<td>");
if(i<inList.size()){
client.print(inList[i].getName());
}
client.println("</td>");
client.print("<td>");
if(i<outList.size()){
client.print(outList[i].getName());
}
client.println("<td>");
client.println("</tr>");
}
client.println("</table>");
client.println("</div>");
client.println("</html>");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
} else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
|
fd261aec458231f14948018fa09afb9b38994b53 | 14180efda011ccfc31ea411a41436576e489d0dc | /dijkstra.cpp | 603193b2fe8974eb36f8032076bb34ac4c77702c | [
"MIT"
] | permissive | RicardoGtz/dijkstra_cpp | 87211a08993513a0c5622c9c3f2f7c565f541c0c | 803b7f3d026bf416305b15df02a5c1ce648a9313 | refs/heads/master | 2020-04-05T20:11:24.673751 | 2018-11-20T04:38:33 | 2018-11-20T04:38:33 | 157,168,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,752 | cpp | dijkstra.cpp | #include <iostream>
#include<stdio.h>
#include <cfloat>
#include<stdlib.h>
#include <time.h>
using namespace std;
bool allVisited();
//Creamos la matriz que representa el grafo
double **graph=NULL;
double *minDist=NULL;
int *parents=NULL;
int *visited=NULL;
int num=0;
//Nodo Inicial
int iniNode=0;
int main(int argc, char const *argv[]) {
//Creamos un puntero de tipo FILE
FILE *fp;
//Abrimos el archivo a leer
if((fp = fopen ("graphs/bcs.txt", "r" ))==NULL){
printf("No se pudo leer el archivo\n");
return 0;
}
//leemos los datos
fscanf(fp, "%d" ,&num);
//Incializa los arreglos
graph = (double**)malloc(num*sizeof(double*));
minDist=(double*)malloc(num*sizeof(double));
parents=(int *)malloc(num*sizeof(int));
visited=(int *)malloc(num*sizeof(int));
// Crea las columnas
for(int i=0;i<num;i++){
graph[i] = (double*)malloc(num*sizeof(double));
for(int j=0;j<num;j++){
// Inicializa la matriz en infinito (Max double)
graph[i][j]=DBL_MAX;
}
// Inicializa el vector en infinito (Max double)
minDist[i]=DBL_MAX;
parents[i]=i;
visited[i]=0;
}
int a,b;
double d;
//Leemos las aristas de cada vertice
while(feof(fp)==0){
fscanf(fp,"%d\t%d\t%lf",&a,&b,&d);
graph[a-1][b-1]=d;
graph[b-1][a-1]=d;
}
/*
//Imprimimos el grafo
for(int i = 0; i < num; i++){
for (int j = 0; j < num; ++j){
if(graph[i][j]!=DBL_MAX)
printf("%.2f\t",graph[i][j]);
else
printf("INF\t");
}
printf("\n");
}*/
clock_t ti, tf;
ti = clock();//Comienza a medir el tiempo
//Algoritmo Dijkstra
//1.Selecciona el nodo Inicial como nodo actual
int act=iniNode;
//2.Asigna como padre del nodo inicial en -1
parents[act]=-1;
//3.Asigna la distancia minima desde el nodo inicial al
// nodo inicial como 0
minDist[act]=0;
//4.Mientras aun hay nodos por visitar, hacer
while(!allVisited()){
//printf("Actual %d\n",act);
for(int i=0;i<num;i++){
if(graph[act][i]<DBL_MAX){
if((graph[act][i]+minDist[act])<minDist[i]){
minDist[i]=graph[act][i]+minDist[act];
parents[i]=act;
}
}
}
visited[act]=1;
double min=DBL_MAX;
int index=0;
for(int i=0;i<num;i++){
if(visited[i]!=1 && minDist[i]<min){
min=minDist[i];
index=i;
}
}
/*
//Imprecion de iteracion
printf("[");
for(int i=0;i<num-1;i++)
if(minDist[i]==DBL_MAX)
printf("INF, ");
else
printf("%.2f, ",minDist[i]);
if(minDist[num-1]==DBL_MAX)
printf("INF] Distancia minima\n");
else
printf("%.2f] Distancia minima\n",minDist[num-1]);
printf("[");
for(int i=0;i<num-1;i++)
printf("%d, ",parents[i]);
printf("%d] Padres\n",parents[num-1]);
printf("[");
for(int i=0;i<num-1;i++)
printf("%d, ",visited[i]);
printf("%d] Padres\n",visited[num-1]);
*/
act=index;
}
tf = clock();//Termina de medir el tiempo
//Imprime el arreglo de distan minimas
printf("Distancias minimas [");
for(int i=0;i<num-1;i++)
printf("%.2f, ",minDist[i]==DBL_MAX ? -1:minDist[i]);
printf("%.2f]\n",minDist[num-1]==DBL_MAX ? -1:minDist[num-1]);
//Imprime el arreglo de padres
printf("Padres [");
for(int i=0;i<num-1;i++)
printf("%d, ",parents[i]);
printf("%d]\n",parents[num-1]);
double segundos = (double)(tf - ti) / CLOCKS_PER_SEC;
printf("\nTiempo de ejecucion: %lf Segundos\n",segundos);
free(fp);
free(graph);
free(minDist);
return 0;
}
bool allVisited(){
int aux=0;
for(int i=0;i<num;i++)
aux+=visited[i];
if(aux==num)
return true;
else
return false;
}
|
99f2257d05dae1ec32ec174a36ed770a5454de3d | 785f542387f302225a8a95af820eaccb50d39467 | /codechef/STDYTAB/STDYTAB-7171322.cpp | 9c1e59ed0c4157b73073d0b9271d9fb978e00f86 | [] | no_license | anveshi/Competitive-Programming | ce33b3f0356beda80b50fee48b0c7b0f42c44b0c | 9a719ea3a631320dfa84c60300f45e370694b378 | refs/heads/master | 2016-08-12T04:27:13.078738 | 2015-01-19T17:30:00 | 2016-03-08T17:44:36 | 51,570,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 942 | cpp | STDYTAB-7171322.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL MOD = 1000000000;
const LL Max = 2002;
LL dp[2*Max][Max];
LL ans[Max][Max];
LL fun(LL i, LL j){
if(dp[i][j]!=0)return dp[i][j];
if(j==0)return 1;
if(i<j)return 0;
if(i==j)return 1;
else return (fun(i-1,j-1) + fun(i-1,j))%MOD;
}
void pre(){
for(int i=0;i<2*Max;i++){
for(int j=0;j<Max;j++){
dp[i][j]=fun(i,j);
}
}
return ;
}
int main(){
pre();
LL T,N,M;
scanf("%lld",&T);
while(T--){
scanf("%lld %lld",&N,&M);
for(int i=1;i<=N;i++){
LL presum = 0;
for(int j=0;j<=M;j++){
if(i==1)
ans[i][j] = dp[j+M-1][M-1];
else{
presum += ans[i-1][j];
presum %= MOD;
ans[i][j] = (presum*dp[j+M-1][M-1])%MOD;
}
}
}
LL res = 0;
for(int i=0;i<=M;i++){
res += ans[N][i];
res %= MOD;
}
printf("%lld\n",res);
}
return 0;
} |
dd273190f867c9c83992727f4cba19ff4aac6bac | 9d08bfcea0bc36875e08264962d3b6fc667a0aff | /gameengine/GameEngine/FlatTextureGraphicsObject.h | 4434833e016011185c7d3fdc3904136f608a2957 | [] | no_license | hmehta410/GameEngine | 4269bc66593fb9aa118196195f15995bd30a8f7d | a6db648712a097aaf60488cf0032b4841f6d1799 | refs/heads/master | 2020-04-06T04:42:16.502989 | 2017-05-20T20:27:47 | 2017-05-20T20:46:44 | 82,880,522 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 866 | h | FlatTextureGraphicsObject.h | #ifndef GRAPHICS_OBJECT_FLAT_TEXTURE_H
#define GRAPHICS_OBJECT_FLAT_TEXTURE_H
#include "GraphicsObject.h"
#include "TextureManager.h"
//This draws a mesh with a flat texture. There is no lighting or base color
//associated with this graphicsObject.
class FlatTextureGraphicsObject :public GraphicsObject
{
public:
FlatTextureGraphicsObject(const Model* model, ComponentHandle<Transform>* transform, Texture* node);
//move is for textureID
FlatTextureGraphicsObject(FlatTextureGraphicsObject&& other);
FlatTextureGraphicsObject& operator=(FlatTextureGraphicsObject&& other);
//GrahpicsObject contract
virtual void SetState() override;
virtual void SetGPUData() override;
virtual void Draw() override;
virtual void RestoreState() override;
private:
GLuint textureID;
GLuint projMatrixIndex;
GLuint viewMatrixIndex;
GLuint worldMatrixIndex;
};
#endif |
2062aa59e42b92f3f362b5df5f3846207ba10d42 | 8156c6d3e4ca1858d507b1a74d058449f6bfd84f | /software/gcs/src/pathplanner/headers/node.h | 1c0a95e8cb9fb37ca16d2d6c2e3f645ea664ad1e | [
"MIT"
] | permissive | DronesForBlood/DronesForBlood | 6681e188913c5cecdf4ae44758de994ecbca14dd | 41bea478903ea6e3e6d22e9a8ed83684097d88cc | refs/heads/master | 2022-07-27T18:27:40.407000 | 2018-12-12T14:09:41 | 2018-12-12T14:09:41 | 147,182,510 | 5 | 3 | MIT | 2022-07-06T19:56:50 | 2018-09-03T09:29:49 | C++ | UTF-8 | C++ | false | false | 3,901 | h | node.h | #ifndef NODE_H
#define NODE_H
#include <utility>
#include <vector>
#include <memory>
#include <math.h>
#include <iostream>
#include <thread>
#include <mutex>
#include <opencv2/core/core.hpp>
#include "headers/global/defines.h"
#include "headers/global/geofunctions.h"
class Node;
struct NeighborNode {
NeighborNode() {}
NeighborNode(std::weak_ptr<Node> node, double distance) {
this->node = node;
this->distance = distance;
}
std::weak_ptr<Node> node;
double distance;
};
struct DynamicPenalty {
DynamicPenalty() {}
DynamicPenalty(std::string ID, int penalty, int epochFrom, int epochTo) {
this->ID = ID;
this->penalty = penalty;
this->epochFrom = epochFrom;
this->epochTo = epochTo;
}
std::string ID;
int penalty;
int epochFrom;
int epochTo;
};
class Node
{
public:
Node();
~Node();
Node(std::pair<std::size_t, std::size_t> index, std::pair<double, double> coordinate);
void addToColor(int r, int g, int b);
cv::Scalar getColor() {return color;}
bool checkIfNodeIsInDangerZone(double distanceToNode);
void removeDynamicPenalty(std::string ID);
void addDynamicPenalty(std::string ID, int penalty, int epochFrom, int epochTo);
void resetNode();
void setPointerToSelf(std::weak_ptr<Node> pointer) {pointerToSelf = pointer;}
void setNeighbors(std::vector<std::shared_ptr<Node>> nodes);
void setNodeReadyMutex(std::shared_ptr<std::mutex> mutex) {nodeReadyMutex = mutex;}
void setCheckNodesAgain(bool *val) {checkNodesAgain = val;}
void checkAndUpdateNeighbors();
void lockAccessNode() {accessNodeMutex.lock();}
bool tryLockAccessNode() {return accessNodeMutex.try_lock();}
void unlockAccessNode() {accessNodeMutex.unlock();}
void unlockNodeReady();
void setUpdated(bool val) {wasUpdated = updated; updated = val;}
void setNextUpdated(bool val);
bool getUpdated() {return updated;}
void setStable(bool val) {stable = val;}
void setNextStable(bool val);
bool getStable() {return stable;}
double getCost() {return cost;}
int getPenalty() {return myPenalty;}
int getTotalPenalty() {return totalPenalty;}
void addToCost(double val) {cost += val;}
void addToTotalPenalty(int val) {totalPenalty += val;}
void setPenalty(int val);
void setTotalPentaly(int val) {totalPenalty = val;}
void setCostAndUpdate(double val);
void addToNextCost(double val, bool mayUpdate);
void addToNextTotalPenalty(int val, bool mayUpdate);
int getPenaltyForDynamicZones(double cost);
std::pair<std::size_t, std::size_t> getNodeIndex() {return selfNodeIndex;}
std::pair<double, double> getWorldCoordinate() {return worldCoordinate;}
std::pair<std::size_t, std::size_t> getSourceIndex() {return sourceNodeIndex;}
std::shared_ptr<Node> getPointerToSource() {return pointerToSource;}
void setNodeAsInit();
void updateSourceAndCost(std::pair<std::size_t, std::size_t> sourceNodeIndex, double newCost);
void setPointerToSource(std::shared_ptr<Node> pointer) {pointerToSource = pointer;}
private:
bool willBeInDynamicZone(DynamicPenalty &dynamic, double distanceToNode);
private:
std::weak_ptr<Node> pointerToSelf;
std::shared_ptr<Node> pointerToSource = nullptr;
std::pair<std::size_t, std::size_t> selfNodeIndex;
std::pair<std::size_t, std::size_t> sourceNodeIndex;
std::vector<DynamicPenalty> dynamicPenalties;
std::pair<double, double> worldCoordinate;
double cost = -1.;
int myPenalty = 0.;
int totalPenalty = 0.;
bool stable = true;
bool updated = false;
bool wasUpdated = false;
std::vector<NeighborNode> neighbors;
std::mutex accessNodeMutex;
std::shared_ptr<std::mutex> nodeReadyMutex;
bool *checkNodesAgain;
int epochETA = 0;
cv::Scalar color;
};
#endif // NODE_H
|
221a8b93638d8b79ba3f5c07c273accece906f6a | 4c9716c0e708a4c8ddb5b63925f21f284701a42c | /code/btas/ctf-master/src/scaling/strp_tsr.h | 64fb45f47da4dbb92121521bd7239d3bdcd31c49 | [
"BSD-3-Clause"
] | permissive | shiyangdaisy23/tensor-contraction | 8564e97c820be07614d9f821210c8ea99533b4c6 | cc79c5683da718dfc8735aea7f56fba36fb628b9 | refs/heads/master | 2021-01-16T18:24:02.409163 | 2017-08-11T20:45:48 | 2017-08-11T20:45:48 | 100,068,903 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,725 | h | strp_tsr.h | /*Copyright (c) 2011, Edgar Solomonik, all rights reserved.*/
#ifndef __STRP_TSR_H__
#define __STRP_TSR_H__
#include "../scaling/scale_tsr.h"
#include "../summation/sum_tsr.h"
#include "../contraction/ctr_comm.h"
#include "../mapping/mapping.h"
namespace CTF_int {
class summation;
class strp_tsr {
public:
int alloced;
int order;
int64_t blk_sz;
int * edge_len;
int * strip_dim;
int * strip_idx;
char * A;
char * buffer;
algstrct const * sr_A;
/**
* \brief strips out part of tensor to be operated on
* \param[in] dir whether to strip or unstrip tensor
*/
void run(int const dir);
/**
* \brief deallocates buffer
*/
void free_exp();
/**
* \brief returns the number of bytes of buffer space
we need
* \return bytes needed
*/
int64_t mem_fp();
/**
* \brief copies strp_tsr object
*/
strp_tsr * clone();
/**
* \brief copies strp_tsr object
*/
strp_tsr(strp_tsr * o);
~strp_tsr(){ if (buffer != NULL) CTF_int::cdealloc(buffer); CTF_int::cdealloc(edge_len); CTF_int::cdealloc(strip_dim); CTF_int::cdealloc(strip_idx);}
strp_tsr(){ buffer = NULL; }
};
class strp_scl : public scl {
public:
scl * rec_scl;
strp_tsr * rec_strp;
/**
* \brief runs strip for scale of tensor
*/
void run();
/**
* \brief gets memory usage of op
*/
int64_t mem_fp();
/**
* \brief copies strp_scl object
*/
scl * clone();
/**
* \brief copies scl object
*/
strp_scl(scl * other);
/**
* \brief deconstructor
*/
~strp_scl();
strp_scl(){}
};
class strp_sum : public tsum {
public:
tsum * rec_tsum;
strp_tsr * rec_strp_A;
strp_tsr * rec_strp_B;
int strip_A;
int strip_B;
/**
* \brief runs strip for sum of tensors
*/
void run();
/**
* \brief gets memory usage of op
*/
int64_t mem_fp();
/**
* \brief copies strp_sum object
*/
tsum * clone();
strp_sum(tsum * other);
/**
* \brief deconstructor
*/
~strp_sum();
strp_sum(summation const * s);
};
class strp_ctr : public ctr {
public:
ctr * rec_ctr;
strp_tsr * rec_strp_A;
strp_tsr * rec_strp_B;
strp_tsr * rec_strp_C;
int strip_A;
int strip_B;
int strip_C;
/**
* \brief runs strip for contraction of tensors
*/
void run(char * A, char * B, char * C);
/**
* \brief returns the number of bytes of buffer space we need recursively
* \return bytes needed for recursive contraction
*/
int64_t mem_fp();
int64_t mem_rec();
/**
* \brief returns the number of bytes sent recursively
* \return bytes needed for recursive contraction
*/
double est_time_rec(int nlyr);
/**
* \brief copies strp_ctr object
*/
ctr * clone();
/**
* \brief deconstructor
*/
~strp_ctr();
/**
* \brief copies strp_ctr object
*/
strp_ctr(ctr *other);
strp_ctr(contraction const * c) : ctr(c) {}
};
/**
* \brief build stack required for stripping out diagonals of tensor
* \param[in] order number of dimensions of this tensor
* \param[in] order_tot number of dimensions invovled in contraction/sum
* \param[in] idx_map the index mapping for this contraction/sum
* \param[in] vrt_sz size of virtual block
* \param[in] edge_map mapping of each dimension
* \param[in] topology the tensor is mapped to
* \param[in] sr algstrct to be given to all stpr objs
* \param[in,out] blk_edge_len edge lengths of local block after strip
* \param[in,out] blk_sz size of local sub-block block after strip
* \param[out] stpr class that recursively strips tensor
* \return 1 if tensor needs to be stripped, 0 if not
*/
int strip_diag(int order,
int order_tot,
int const * idx_map,
int64_t vrt_sz,
mapping const * edge_map,
topology const * topo,
algstrct const * sr,
int * blk_edge_len,
int64_t * blk_sz,
strp_tsr ** stpr);
}
#endif // __STRP_TSR_H__
|
1c8478cd7dc6c1a33363166f72e33b359de54bc2 | 878e68660404763c157c62e32ec0867c49c8a802 | /test/main.cpp | 8e33b59481a295fef48e6265e5e33cadf289aef0 | [] | no_license | ogorodnikoff2012/ded2018-square-equation-solver | 1a47ad48b5d7163a224f8ba3193d7d20d27e5537 | a2d3b08992573fc31c13a8a3cba01f0055d6caaa | refs/heads/master | 2020-03-28T15:05:15.185638 | 2018-09-20T14:57:18 | 2018-09-20T14:57:18 | 148,554,199 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 855 | cpp | main.cpp | #include <testing.h>
#include <iostream>
#include <solverapp.h>
#include <sstream>
#include <set>
TEST_SET(SimpleTestSet) {
TEST(HelloWorld) {
std::cout << "Hello world!" << std::endl;
return true;
};
}
TEST_SET(SolverAppSet) {
TEST(SimpleTest) {
std::stringstream data;
Console console(std::cin, data);
console.setVariable("verbosity", "ERROR");
SolverApp app(&console);
app.exec({"solve", "1", "0", "-1"});
std::cerr << "Stream: " << data.str() << std::endl;
std::set<double> answer;
double buffer;
while (data >> buffer) {
answer.insert(buffer);
}
return answer == std::set<double>{-1, 1};
};
}
int main() {
test_autogen::SimpleTestSet().runTests();
test_autogen::SolverAppSet().runTests();
return 0;
}
|
c8d01e5a0fba1ad15df12dcccb7ee35085ebe843 | 59e2123d7366dee1214e0a2537ef68570e038045 | /zestawienie.h | 40395a64b3b05b88350b163469d9aa9b2aeb3c0a | [] | no_license | quetz05/pszt | 6a16fdc7845d906cc8f7a4367755771586a15539 | 36c1a89438e6f6e6342854251d65c1003f7d5a54 | refs/heads/master | 2021-01-10T20:47:52.983599 | 2013-05-26T20:50:17 | 2013-05-26T20:50:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | h | zestawienie.h | #ifndef ZESTAWIENIE_H
#define ZESTAWIENIE_H
#include <QDialog>
#include "kometa.h"
#include "populacja.h"
#include <QGraphicsScene>
using namespace std;
namespace Ui {
class Zestawienie;
}
class Zestawienie : public QDialog
{
Q_OBJECT
public:
explicit Zestawienie(QWidget *parent = 0);
~Zestawienie();
void prepareData(Populacja *pop);
private:
Ui::Zestawienie *ui;
QGraphicsScene *scena;
};
#endif // ZESTAWIENIE_H
|
d22be6ebb51039f5564b121d2dd033136064e416 | 452418d2523cc68aa73b50cdc043162b140d5ce3 | /DblLinkList.h | 72d9abc1c1aae7b79ee85fcf749744759a0dc926 | [] | no_license | Amireux233/TextEditor | 406031457e5609697391fb35cef2500d051155a8 | 878ec2d3b2781ce03c59e761ebe5633055223683 | refs/heads/master | 2021-09-03T11:08:35.599228 | 2018-01-08T15:20:30 | 2018-01-08T15:20:30 | 116,693,006 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,767 | h | DblLinkList.h | #ifndef __DBL_LK_LIST_H__
#define __DBL_LK_LIST_H__
#include "utility.h" // 实用程序软件包
#include "dbl_node.h" // 双向链表结点类模板
// 简单双向循环链表类模板
template <class ElemType>
class DblLinkList
{
protected:
// 循环链表实现的数据成员:
DblNode<ElemType> *head; // 头结点指针
// 辅助函数模板:
DblNode<ElemType> *GetElemPtr(int position) const; // 返回指向第position个结点的指针
void Init(); // 初始化线性表
public:
// 抽象数据类型方法声明及重载编译系统默认方法声明:
DblLinkList(); // 无参数的构造函数模板
virtual ~DblLinkList(); // 析构函数模板
int Length() const; // 求线性表长度
bool Empty() const; // 判断线性表是否为空
void Clear(); // 将线性表清空
void Traverse(void(*visit)(const ElemType &)) const; // 遍历线性表
StatusCode GetElem(int position, ElemType &e) const; // 求指定位置的元素
StatusCode SetElem(int position, const ElemType &e); // 设置指定位置的元素值
StatusCode Delete(int position, ElemType &e); // 删除元素
StatusCode Insert(int position, const ElemType &e); // 插入元素
DblLinkList(const DblLinkList<ElemType> ©); // 复制构造函数模板
DblLinkList<ElemType> &operator =(const DblLinkList<ElemType> ©);
// 重载赋值运算符
};
// 简单链表类模板的实现部分
template<class ElemType>
DblNode<ElemType> *DblLinkList<ElemType>::GetElemPtr(int position) const
// 操作结果:返回指向第position个结点的指针
{
if (position == 0)
{ // 头结点的序号为0
return head;
}
DblNode<ElemType> *tmpPtr = head->next;// 用tmpPtr遍历线性表以查找第position个结点
int curPosition = 1; // tmpPtr所指结点的位置
while (tmpPtr != head && curPosition < position)
// 顺指针向后查找,直到tmpPtr指向第position个结点
{
tmpPtr = tmpPtr->next;
curPosition++;
}
if (tmpPtr != head && curPosition == position)
{ // 查找成功
return tmpPtr;
}
else
{ // 查找失败
return NULL;
}
}
template <class ElemType>
void DblLinkList<ElemType>::Init()
// 操作结果:初始化线性表
{
head = new DblNode<ElemType>; // 构造头指针
head->back = head; // 空双向循环链表的头结点前驱为头结点本身
head->next = head; // 空循环链表的头结点后继为头结点本身
}
template <class ElemType>
DblLinkList<ElemType>::DblLinkList()
// 操作结果:构造一个空链表
{
Init();
}
template <class ElemType>
DblLinkList<ElemType>::~DblLinkList()
// 操作结果:销毁线性表
{
Clear(); // 清空线性表
delete head; // 释放头结点所点空间
}
template <class ElemType>
int DblLinkList<ElemType>::Length() const
// 操作结果:返回线性表元素个数
{
int count = 0; // 计数器
for (DblNode<ElemType> *tmpPtr = head->next; tmpPtr != head; tmpPtr = tmpPtr->next)
{ // 用tmpPtr依次指向每个元素
count++; // 对线性表的每个元素进行计数
}
return count;
}
template <class ElemType>
bool DblLinkList<ElemType>::Empty() const
// 操作结果:如线性表为空,则返回true,否则返回false
{
return head->next == head;
}
template <class ElemType>
void DblLinkList<ElemType>::Clear()
// 操作结果:清空线性表
{
ElemType tmpElem; // 临时元素值
while (Length() > 0)
{ // 表性表非空,则删除第1个元素
Delete(1, tmpElem);
}
}
template <class ElemType>
void DblLinkList<ElemType>::Traverse(void(*visit)(const ElemType &)) const
// 操作结果:依次对线性表的每个元素调用函数(*visit)
{
for (DblNode<ElemType> *tmpPtr = head->next; tmpPtr != head; tmpPtr = tmpPtr->next)
{ // 用tmpPtr依次指向每个元素
(*visit)(tmpPtr->data); // 对线性表的每个元素调用函数(*visit)
}
}
template <class ElemType>
StatusCode DblLinkList<ElemType>::GetElem(int position, ElemType &e) const
// 操作结果:当线性表存在第position个元素时,用e返回其值,返回ENTRY_FOUND,
// 否则返回NOT_PRESENT
{
if (position < 1 || position > Length())
{ // position范围错
return NOT_PRESENT; // 元素不存在
}
else
{ // position合法
DblNode<ElemType> *tmpPtr;
tmpPtr = GetElemPtr(position); // 取出指向第position个结点的指针
e = tmpPtr->data; // 用e返回第position个元素的值
return ENTRY_FOUND;
}
}
template <class ElemType>
StatusCode DblLinkList<ElemType>::SetElem(int position, const ElemType &e)
// 操作结果:将线性表的第position个位置的元素赋值为e,
// position的取值范围为1≤position≤Length(),
// position合法时返回SUCCESS,否则返回RANGE_ERROR
{
if (position < 1 || position > Length())
{ // position范围错
return RANGE_ERROR;
}
else
{ // position合法
DblNode<ElemType> *tmpPtr;
tmpPtr = GetElemPtr(position); // 取出指向第position个结点的指针
tmpPtr->data = e; // 设置第position个元素的值
return SUCCESS;
}
}
template <class ElemType>
StatusCode DblLinkList<ElemType>::Delete(int position, ElemType &e)
// 操作结果:删除线性表的第position个位置的元素, 并用e返回其值,
// position的取值范围为1≤position≤Length(),
// position合法时返回SUCCESS,否则返回RANGE_ERROR
{
if (position < 1 || position > Length())
{ // position范围错
return RANGE_ERROR;
}
else
{ // position合法
DblNode<ElemType> *tmpPtr;
tmpPtr = GetElemPtr(position); // 取出指向第position个结点的指针
tmpPtr->back->next = tmpPtr->next; // 修改向右的指针
tmpPtr->next->back = tmpPtr->back; // 修改向左的指针
e = tmpPtr->data; // 用e返回被删结点元素值
delete tmpPtr; // 释放被删结点
return SUCCESS;
}
}
template <class ElemType>
StatusCode DblLinkList<ElemType>::Insert(int position, const ElemType &e)
// 操作结果:在线性表的第position个位置前插入元素e
// position的取值范围为1≤position≤Length()+1
// position合法时返回SUCCESS, 否则返回RANGE_ERROR
{
if (position < 1 || position > Length() + 1)
{ // position范围错
return RANGE_ERROR; // 位置不合法
}
else
{ // position合法
DblNode<ElemType> *tmpPtr, *nextPtr, *newPtr;
tmpPtr = GetElemPtr(position - 1); // 取出指向第position-1个结点的指针
nextPtr = tmpPtr->next; // nextPtr指向第position个结点
newPtr = new DblNode<ElemType>(e, tmpPtr, nextPtr);// 生成新结点
tmpPtr->next = newPtr; // 修改向右的指针
nextPtr->back = newPtr; // 修改向左的指针
return SUCCESS;
}
}
template <class ElemType>
DblLinkList<ElemType>::DblLinkList(const DblLinkList<ElemType> ©)
// 操作结果:由线性表copy构造新线性表——复制构造函数模板
{
int copyLength = copy.Length(); // copy的长度
ElemType e;
Init(); // 初始化线性表
for (int curPosition = 1; curPosition <= copyLength; curPosition++)
{ // 复制数据元素
copy.GetElem(curPosition, e); // 取出第curPosition个元素
Insert(Length() + 1, e); // 将e插入到当前线性表
}
}
template <class ElemType>
DblLinkList<ElemType> &DblLinkList<ElemType>::operator =(const DblLinkList<ElemType> ©)
// 操作结果:将线性表copy赋值给当前线性表——重载赋值运算符
{
if (© != this)
{
int copyLength = copy.Length(); // copy的长度
ElemType e;
Clear(); // 清空当前线性表
for (int curPosition = 1; curPosition <= copyLength; curPosition++)
{ // 复制数据元素
copy.GetElem(curPosition, e); // 取出第curPosition个元素
Insert(Length() + 1, e); // 将e插入到当前线性表
}
}
return *this;
}
#endif#pragma once
|
f53bc017c497f05e8178fb5cc2ab0423c38fbe3e | 6c5a5a681b82fc9646184d5dc3a348f97bc48950 | /Src/SA/SA_Cursr.cpp | 285ddc5838b3a092871565ec3c6629f4d63db1fe | [] | no_license | elipriaulx/SpeechAnalyzer | 9a70ae1ecdcf0fbc42ab4ad3cbceaacbc9976299 | 50ee960e5df95bd47864d25ce067d62f514dab6e | refs/heads/master | 2022-04-09T02:16:35.381456 | 2020-03-21T19:10:02 | 2020-03-21T19:10:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,772 | cpp | SA_Cursr.cpp | /////////////////////////////////////////////////////////////////////////////
// sa_cursr.cpp:
// Implementation of the CStartCursorWnd classes.
// Author: Urs Ruchti
// copyright 2000 JAARS Inc. SIL
//
// Revision History
// 1.06.1.2
// SDM Added code to detect CONTROL+SHIFT on cursor move and cause Update Boundaries
// SDM Restricted select to control key only
// SDM Added message handlers OnKey... to Start&Stop cursors
// 1.06.6U4
// SDM Changed CPrivateCursorWnd to use CPrivateCursorWnd::ChangePosition()
// 1.06.6U5
// SDM Modified Calculate position to adjust for new plot alignment
// 1.5Test8.1
// SDM Added support for no overlap drag UpdateBoundaries
// 1.5Test10.2
// SDM Added annotation deselection on MouseUp if cursors do not include selected
// 1.5Test10.4
// SDM Made cursor windows dependent on CCursorWnd (new class)
// SDM added bDrawn flag
// 1.5Test11.0
// SDM replaced GetOffset() + GetDuration() with CSegment::GetStop()
// 1.5Test11.4
// SDM added support for editing PHONEMIC/TONE/ORTHO to span multiple segments
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "sa_cursr.h"
#include "sa_plot.h"
#include "sa_graph.h"
#include "Process\Process.h"
#include "Segment.h"
#include "Process\sa_p_fra.h"
#include "math.h"
#include "sa_doc.h"
#include "sa_view.h"
#include "sa_wbch.h"
#include "mainfrm.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
CCursorWnd::CCursorWnd() {
bDrawn = FALSE;
}
BOOL CCursorWnd::IsDrawn() {
return bDrawn;
}
void CCursorWnd::SetDrawn(BOOL bNewDrawn) {
bDrawn = bNewDrawn;
}
|
c6b4cf4c31adb40a0e71bc83d4343d478be5d6b3 | 4a85bf4c1121ead415341d5fe789f321984b170a | /src/myChair.h | 0ab8f5a3e2741700efd01dca687803154e978cb2 | [] | no_license | JASalorte/Graphic---Ejemplo-de-escena | 7e6b2a82609660ce65a1f84b32323fc9bb4adcfe | e9c678cf44776b07c71f139b8f3e32002539d967 | refs/heads/master | 2021-07-09T21:35:48.589802 | 2017-10-08T11:56:16 | 2017-10-08T11:56:16 | 106,132,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 334 | h | myChair.h | #ifndef MYCHAIR_H
#define MYCHAIR_H
#include "CGFobject.h"
#include "CGFappearance.h"
class myChair: public CGFobject {
public:
float angle;
float transX, transZ;
myChair();
void draw();
CGFappearance* materialWoods;
CGFappearance* materialMetal;
CGFappearance* tableAppearance;
CGFappearance* MetalAppearance;
};
#endif |
de50e2cc7c66e5cec8230026210b8a333660951b | 0fa1152e1e434ce9fe9e2db95f43f25675bf7d27 | /src/modules/control_allocator/ActuatorEffectiveness/ActuatorEffectivenessRotors.hpp | 14f96b7dab43aafcbea9b920ff86f47690f7d37a | [
"BSD-3-Clause"
] | permissive | PX4/PX4-Autopilot | 4cc90dccc9285ca4db7f595ac5a7547df02ca92e | 3d61ab84c42ff8623bd48ff0ba74f9cf26bb402b | refs/heads/main | 2023-08-30T23:58:35.398450 | 2022-03-26T01:29:03 | 2023-08-30T15:40:01 | 5,298,790 | 3,146 | 3,798 | BSD-3-Clause | 2023-09-14T17:22:04 | 2012-08-04T21:19:36 | C++ | UTF-8 | C++ | false | false | 5,536 | hpp | ActuatorEffectivenessRotors.hpp | /****************************************************************************
*
* Copyright (c) 2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file ActuatorEffectivenessRotors.hpp
*
* Actuator effectiveness computed from rotors position and orientation
*
* @author Julien Lecoeur <julien.lecoeur@gmail.com>
*/
#pragma once
#include "ActuatorEffectiveness.hpp"
#include <px4_platform_common/module_params.h>
#include <uORB/Subscription.hpp>
#include <uORB/SubscriptionInterval.hpp>
class ActuatorEffectivenessTilts;
using namespace time_literals;
class ActuatorEffectivenessRotors : public ModuleParams, public ActuatorEffectiveness
{
public:
enum class AxisConfiguration {
Configurable, ///< axis can be configured
FixedForward, ///< axis is fixed, pointing forwards (positive X)
FixedUpwards, ///< axis is fixed, pointing upwards (negative Z)
};
static constexpr int NUM_ROTORS_MAX = 12;
struct RotorGeometry {
matrix::Vector3f position;
matrix::Vector3f axis;
float thrust_coef;
float moment_ratio;
int tilt_index;
};
struct Geometry {
RotorGeometry rotors[NUM_ROTORS_MAX];
int num_rotors{0};
bool propeller_torque_disabled{false};
bool yaw_by_differential_thrust_disabled{false};
bool propeller_torque_disabled_non_upwards{false}; ///< keeps propeller torque enabled for upward facing motors
bool three_dimensional_thrust_disabled{false}; ///< for handling of tiltrotor VTOL, as they pass in 1D thrust and collective tilt
};
ActuatorEffectivenessRotors(ModuleParams *parent, AxisConfiguration axis_config = AxisConfiguration::Configurable,
bool tilt_support = false);
virtual ~ActuatorEffectivenessRotors() = default;
bool getEffectivenessMatrix(Configuration &configuration, EffectivenessUpdateReason external_update) override;
void getDesiredAllocationMethod(AllocationMethod allocation_method_out[MAX_NUM_MATRICES]) const override
{
allocation_method_out[0] = AllocationMethod::SEQUENTIAL_DESATURATION;
}
void getNormalizeRPY(bool normalize[MAX_NUM_MATRICES]) const override
{
normalize[0] = true;
}
static int computeEffectivenessMatrix(const Geometry &geometry,
EffectivenessMatrix &effectiveness, int actuator_start_index = 0);
bool addActuators(Configuration &configuration);
const char *name() const override { return "Rotors"; }
/**
* Sets the motor axis from tilt configurations and current tilt control.
* @param tilts configured tilt servos
* @param tilt_control current tilt control in [-1, 1] (can be NAN)
* @return the motors as bitset which are not tiltable
*/
uint32_t updateAxisFromTilts(const ActuatorEffectivenessTilts &tilts, float tilt_control);
const Geometry &geometry() const { return _geometry; }
/**
* Get the tilted axis {0, 0, -1} rotated by -tilt_angle around y, then
* rotated by tilt_direction around z.
*/
static matrix::Vector3f tiltedAxis(float tilt_angle, float tilt_direction);
void enablePropellerTorque(bool enable) { _geometry.propeller_torque_disabled = !enable; }
void enableYawByDifferentialThrust(bool enable) { _geometry.yaw_by_differential_thrust_disabled = !enable; }
void enablePropellerTorqueNonUpwards(bool enable) { _geometry.propeller_torque_disabled_non_upwards = !enable; }
void enableThreeDimensionalThrust(bool enable) { _geometry.three_dimensional_thrust_disabled = !enable; }
uint32_t getMotors() const;
uint32_t getUpwardsMotors() const;
uint32_t getForwardsMotors() const;
private:
void updateParams() override;
const AxisConfiguration _axis_config;
const bool _tilt_support; ///< if true, tilt servo assignment params are loaded
struct ParamHandles {
param_t position_x;
param_t position_y;
param_t position_z;
param_t axis_x;
param_t axis_y;
param_t axis_z;
param_t thrust_coef;
param_t moment_ratio;
param_t tilt_index;
};
ParamHandles _param_handles[NUM_ROTORS_MAX];
param_t _count_handle;
Geometry _geometry{};
};
|
33f79218be8a6f56ac47fb0f36fae0ae12077434 | cf152fe5d548e4268da163019004cccc90bf5032 | /riri_DmxSerial_shutter_servo2_mg996r_moko/riri_DmxSerial_shutter_servo2_mg996r_moko.ino | 808767ef405af3745c023e2c2b259d5f5685bd8e | [] | no_license | ririfonfon/moko | 2404e4e08f6b7fcf51b58684c41dfcbef8fcbf35 | c5d579ca8f9aaaec54215610ae0e86ec1d8f1908 | refs/heads/master | 2020-04-10T22:20:45.662473 | 2018-03-07T22:04:41 | 2018-03-07T22:04:41 | 124,298,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | ino | riri_DmxSerial_shutter_servo2_mg996r_moko.ino | #include <DMXSerial.h>
#include <Servo.h> // the servo library
int val;
int vals;
Servo servo; // declare variables for up to eight servos
const int RedPin = 9; // PWM output pin for Red Light.
void setup () {
pinMode(RedPin, OUTPUT);
DMXSerial.init(DMXReceiver);
servo.attach(13);
}
void loop() {
val = (DMXSerial.read(501));
vals = map(val, 0, 255, 160, 0);
servo.write(vals);
analogWrite(RedPin, val);
delay(15);
}
|
bd9655e023f527722ab31e021ba8b017a1ba8c90 | 428aeb6cdc5765c971c173278232e444804b3773 | /interview/kmeans.cpp | 759578251efc373c9f696841320a552108c084c0 | [] | no_license | chucai2000/cpp_practice | ec2df213b34f40c4fa87f63668dae73dccd9dc23 | f3f42c624de03dd39069cfbdeb7823f55c6d7b43 | refs/heads/master | 2020-01-23T21:30:33.894661 | 2017-03-07T03:14:55 | 2017-03-07T03:14:55 | 74,701,727 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,132 | cpp | kmeans.cpp | #include "kmeans.h"
TEST(kmeans, execution)
{
kmeans::KMeans obj;
std::random_device rd;
std::mt19937 engine(rd());
std::normal_distribution<float> norm_mean_pos_one(10., 0.05);
std::normal_distribution<float> norm_mean_neg_one(-10., 0.05);
std::vector<kmeans::Point> points;
unsigned int num_of_points_per_cluster = 100;
for (unsigned int i = 0; i < num_of_points_per_cluster; ++i) {
points.push_back(kmeans::Point(norm_mean_pos_one(engine), norm_mean_pos_one(engine)));
}
for (unsigned int i = 0; i < num_of_points_per_cluster; ++i) {
points.push_back(kmeans::Point(norm_mean_neg_one(engine), norm_mean_pos_one(engine)));
}
for (unsigned int i = 0; i < num_of_points_per_cluster; ++i) {
points.push_back(kmeans::Point(norm_mean_neg_one(engine), norm_mean_neg_one(engine)));
}
for (unsigned int i = 0; i < num_of_points_per_cluster; ++i) {
points.push_back(kmeans::Point(norm_mean_pos_one(engine), norm_mean_neg_one(engine)));
}
obj.set_points(points);
obj.set_kval(5);
obj.set_num_of_iterations(1000);
obj.compute();
}
|
68fda4f7050c521651cb5aec5b663d26ac737ab5 | e4a38bf0acce19c7efa5866dd3ac1498b2ddfd52 | /P1403 约数研究/P1403 约数研究/源.cpp | 9f663abb8485a69fa7bd92319f1e480e7d53609a | [] | no_license | XieJiongyan/LuoguSolver | 6527747a262b675f6c586e899181db20b450b3a9 | 17d24f8d3a59d23f2efbc10eedf91041d70757db | refs/heads/master | 2022-11-28T21:16:32.640382 | 2020-08-08T06:49:48 | 2020-08-08T06:49:48 | 282,229,369 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 204 | cpp | 源.cpp | #include <iostream>
#include "Primernum.h"
using namespace::std;
int main()
{
long long x = 0;
cin >> x;
primernum.generate(x);
cout << primernum.countdiv(x) << endl;
system("pause");
return 0;
}
|
41314891c50f1fd9a1a884628f69f01bb1700ef0 | a473a8794728c425076030d98567fe8b27059b37 | /lib_forward_list/forwars_list_01.cpp | 09899a34c225d02c63526eae7f23817d3734bbb9 | [] | no_license | sootsprite/cpp-unit-testing | 15a5e034d6b987ec3b0edc42d479021771efa8eb | 5a3e646e52bc2547bb8a52178540fdb3a0c816b7 | refs/heads/master | 2016-09-05T17:11:43.876559 | 2014-07-30T03:30:44 | 2014-07-30T03:30:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | cpp | forwars_list_01.cpp | #include <iostream>
#include <list>
#include <forward_list>
#include <algorithm>
int main(int argc, char const* argv[]) {
// in case of list
std::list<int> li;
for(int i = 0; i < 10; ++i)
li.push_back(i);
for(auto&& i : li)
std::cout << i << " ";
std::cout << std::endl;
// in case of forward_list
std::forward_list<int> fl;
auto itr = fl.before_begin();
for(int i = 0; i < 10; ++i)
itr = fl.insert_after(itr, i);
for(auto&& i : fl)
std::cout << i << " ";
std::cout << std::endl;
return 0;
}
|
f042375d7b6bc756cb205655a700b971caff54e3 | 315b4721a030871f23aa68b29e81dead78d93a82 | /at_tenka1_2017_d.cpp | ce076aa9bf561ab5a7207215d9036d60e7caeca9 | [] | no_license | ArutoriaWhite/Competitive-programming | ce71166ac51929ed6d37761256dfdfee7ebd207e | e19642bd76f1fa12b1162930c4a7f3b199cd2573 | refs/heads/master | 2023-06-16T21:58:01.308407 | 2021-07-19T12:07:12 | 2021-07-19T12:07:12 | 216,078,983 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 894 | cpp | at_tenka1_2017_d.cpp | #include <bits/stdc++.h>
#define yukari ios::sync_with_stdio(0), cin.tie(0)
#define de(x) cout << #x << "=" << x << ", "
#define dend cout << '\n'
#define lowbit(x) (x&-x)
#define mem(a,x) memset(a,x,sizeof(a))
#define exi(x,s) (s.find(x)!=s.end())
#define Uset unordered_set
#define Umap unordered_map
#define Pq priority_queue
#define pb push_back
#define fi first
#define se second
using namespace std;
typedef pair<int,int> Pii;
typedef long long ll;
const int INF=0x3f3f3f3f, MIN=0xc0c0c0c0, N = 1e5+10;
int n, k, a[N], b[N], res;
int main()
{
cin >> n >> k;
for (int i=0; i<n; i++)
cin >> a[i] >> b[i];
for (int x=k,t=0; x>0; x&=~(t-1))
{
t = lowbit(x), x--;
int sum = 0;
for (int i=0; i<n; i++)
if ((x|a[i]) == x) sum += b[i];
res = max(res, sum);
}
cout << res << '\n';
}
|
27578d9bf2aa261b8595a6c969961a671d6c39d0 | 8051bea8fd9bbd19df3b0bff227515540aef94e8 | /http_client.h | 7a2380d0ee1c387be7565fb98ed38288c829eef7 | [] | no_license | charles-edouardlatour/HLS_Proxy | 451121c39f954ad8b96ad21fda90554a95a5aba7 | 6368b70d8b7af94021c0c6d1e1900cf2503a6db3 | refs/heads/master | 2022-04-16T20:19:58.199806 | 2020-02-01T14:15:30 | 2020-02-02T17:49:01 | 236,071,411 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | h | http_client.h | #ifndef HTTP_CLIENT
#define HTTP_CLIENT
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <string>
namespace http = boost::beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
/// Client to send http requests.
class HttpClient
{
public:
HttpClient(const std::string& host, const std::string& port);
~HttpClient();
http::response<http::dynamic_body> get(http::request<http::string_body>& req) const;
std::string get_host() const {
return _host;
}
private:
std::string _host;
std::string _port;
};
#endif // HTTP_CLIENT |
39553bf2b90ac5fd9f5cf0b5afc554900eccf42b | d2bb8b920f5d1d23f3db2d1256d1fd6213940014 | /engine/Engine/src/audio/Sound3d.h | 0dda6ec176ef5aa469ca943c866383277e49b098 | [
"MIT"
] | permissive | ZieIony/Ghurund | 726672d56838d18b6dd675f304feee1d95a296bd | 0ce83cabd91f7ac71286dcd8e12d486bed2d75cf | refs/heads/master | 2023-08-17T08:14:19.548027 | 2022-02-12T16:33:32 | 2022-02-12T16:34:54 | 124,959,579 | 91 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 646 | h | Sound3d.h | #pragma once
#include "Sound.h"
namespace Ghurund::Audio {
class Sound3D:public Sound {
private:
X3DAUDIO_EMITTER emitter = { 0 }; // sound source's position
public:
Sound3D() {
emitter.ChannelCount = 1;
emitter.CurveDistanceScaler = FLT_MIN;
X3DAUDIO_DSP_SETTINGS DSPSettings = { 0 };
FLOAT32* matrix = new FLOAT32[deviceDetails.OutputFormat.Format.nChannels];
DSPSettings.SrcChannelCount = 1;
DSPSettings.DstChannelCount = deviceDetails.OutputFormat.Format.nChannels;
DSPSettings.pMatrixCoefficients = matrix;
}
};
} |
e2fd81ad1dee3c62b9ffdbf1ebbc47032d8936b6 | 44b98554e6ea51babba2f20f68d05bf9d5635cd9 | /app/ipcam/hw_auto_detect/hw_auto_detect.cpp | fa0f0018e348882059c14f0b5eea041526cbdc5a | [] | no_license | pengdu/bbam | 8550688d1aa6dda680fbe953439e595efc1b7107 | afc307dc04fffe89a111a0f1b5ef6376f52e194c | refs/heads/master | 2015-08-10T03:58:11.792991 | 2013-10-24T06:23:54 | 2013-10-24T06:23:54 | 16,098,118 | 5 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 3,559 | cpp | hw_auto_detect.cpp | #include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <tinyxml.h>
#include <capability.h>
#include <capability_table.h>
#include <mw_hw_check.h>
#define CAPABILITY_AUTO_PROFILE \
"/etc/ambaipcam/capability/capability_auto.xml"
// #define CAPABILITY_AUTO_PROFILE "capability.xml"
typedef int (* FuncDetect)(unsigned int * Type);
typedef struct tagSysAutoDetectionTable
{
const char * s_Field;
FuncDetect s_Func;
const SysValueTable * s_ValueTable;
} SysAutoDetectionTable;
static SysAutoDetectionTable l_AutoDetectionTable[] =
{
{"CPU", mw_hw_get_cpu_type, l_CPUValueTable },
{"VideoIn", mw_hw_get_sensor_type, l_VinValueTable },
{"Lens", mw_hw_get_zoomlens_type, l_LensValueTable },
{"MainBoard", mw_hw_get_encoder_board_type, l_MainBoardValueTable},
{NULL, NULL, NULL },
};
int main(int argc, const char * argv [])
{
int RetVal = 0;
TiXmlDocument XmlDoc;
TiXmlNode * XmlNode = NULL;
TiXmlElement * XmlRootNode = NULL;
const SysAutoDetectionTable * Item = NULL;
do
{
// Remove profile, if it is existed
if (0 == access(CAPABILITY_AUTO_PROFILE, F_OK))
{
unlink(CAPABILITY_AUTO_PROFILE);
}
// Create root element
XmlNode = XmlDoc.InsertEndChild(TiXmlElement("Capability"));
if (NULL == XmlNode)
{
fprintf(stderr, "Failed to add root element\n");
RetVal = 1;
break;
}
XmlRootNode = XmlNode->ToElement();
for (Item = l_AutoDetectionTable; Item->s_Field != NULL; ++ Item)
{
unsigned int Value = 0;
const SysValueTable * ValueItem = NULL;
XmlNode = XmlRootNode->InsertEndChild(TiXmlElement(Item->s_Field));
if (NULL == XmlNode)
{
fprintf(stderr, "Failed to add %s element\n", Item->s_Field);
RetVal = 1;
break;
}
XmlNode->ToElement()->SetAttribute("readonly", 1);
RetVal = Item->s_Func(&Value);
if (RetVal != 0)
{
fprintf(stderr, "Failed to detect %s type\n", Item->s_Field);
RetVal = 1;
break;
}
for (ValueItem = Item->s_ValueTable; ValueItem->s_ValueText != NULL; ++ ValueItem)
{
if (ValueItem->s_Value == (int)Value)
{
XmlNode = XmlNode->InsertEndChild(TiXmlText(ValueItem->s_ValueText));
if (NULL == XmlNode)
{
fprintf(stderr, "Failed to add text %s\n", ValueItem->s_ValueText);
RetVal = 1;
}
break;
}
}
if (NULL == ValueItem->s_ValueText)
{
fprintf(stderr, "Failed to find the value %u of in table of %s\n", Value, Item->s_Field);
RetVal = 1;
break;
}
}
if (RetVal != 0)
{
break;
}
if (!XmlDoc.SaveFile(CAPABILITY_AUTO_PROFILE))
{
fprintf(stderr, "Failed to save capability profile\n");
RetVal = 1;
break;
}
} while (0);
return RetVal;
}
|
1d51ef1a53f4036b1642fd06b6f0fa21312b0cd9 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /third_party/skia/src/gpu/vk/GrVkPipelineStateCache.cpp | 2e6a85bb2c6737b0509cf403e1c7987f60e64a8c | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 4,672 | cpp | GrVkPipelineStateCache.cpp | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrVkResourceProvider.h"
#include "GrVkGpu.h"
#include "GrProcessor.h"
#include "GrVkPipelineState.h"
#include "GrVkPipelineStateBuilder.h"
#include "SkOpts.h"
#include "glsl/GrGLSLFragmentProcessor.h"
#include "glsl/GrGLSLProgramDataManager.h"
#ifdef GR_PIPELINE_STATE_CACHE_STATS
// Display pipeline state cache usage
static const bool c_DisplayVkPipelineCache{false};
#endif
struct GrVkResourceProvider::PipelineStateCache::Entry {
Entry() : fPipelineState(nullptr) {}
static const GrVkPipelineState::Desc& GetKey(const Entry* entry) {
return entry->fPipelineState->getDesc();
}
static uint32_t Hash(const GrVkPipelineState::Desc& key) {
return key.getChecksum();
}
sk_sp<GrVkPipelineState> fPipelineState;
private:
SK_DECLARE_INTERNAL_LLIST_INTERFACE(Entry);
};
GrVkResourceProvider::PipelineStateCache::PipelineStateCache(GrVkGpu* gpu)
: fCount(0)
, fGpu(gpu)
#ifdef GR_PIPELINE_STATE_CACHE_STATS
, fTotalRequests(0)
, fCacheMisses(0)
#endif
{}
GrVkResourceProvider::PipelineStateCache::~PipelineStateCache() {
SkASSERT(0 == fCount);
// dump stats
#ifdef GR_PIPELINE_STATE_CACHE_STATS
if (c_DisplayVkPipelineCache) {
SkDebugf("--- Pipeline State Cache ---\n");
SkDebugf("Total requests: %d\n", fTotalRequests);
SkDebugf("Cache misses: %d\n", fCacheMisses);
SkDebugf("Cache miss %%: %f\n", (fTotalRequests > 0) ?
100.f * fCacheMisses / fTotalRequests :
0.f);
SkDebugf("---------------------\n");
}
#endif
}
void GrVkResourceProvider::PipelineStateCache::reset() {
fHashTable.foreach([](Entry** entry) {
delete *entry;
});
fHashTable.reset();
fCount = 0;
}
void GrVkResourceProvider::PipelineStateCache::abandon() {
fHashTable.foreach([](Entry** entry) {
SkASSERT((*entry)->fPipelineState.get());
(*entry)->fPipelineState->abandonGPUResources();
});
this->reset();
}
void GrVkResourceProvider::PipelineStateCache::release() {
fHashTable.foreach([this](Entry** entry) {
SkASSERT((*entry)->fPipelineState.get());
(*entry)->fPipelineState->freeGPUResources(fGpu);
});
this->reset();
}
sk_sp<GrVkPipelineState> GrVkResourceProvider::PipelineStateCache::refPipelineState(
const GrPipeline& pipeline,
const GrPrimitiveProcessor& primProc,
GrPrimitiveType primitiveType,
const GrVkRenderPass& renderPass) {
#ifdef GR_PIPELINE_STATE_CACHE_STATS
++fTotalRequests;
#endif
// Get GrVkProgramDesc
GrVkPipelineState::Desc desc;
if (!GrVkPipelineState::Desc::Build(&desc, primProc, pipeline, primitiveType,
*fGpu->vkCaps().glslCaps())) {
GrCapsDebugf(fGpu->caps(), "Failed to build vk program descriptor!\n");
return nullptr;
}
desc.finalize();
Entry* entry = nullptr;
if (Entry** entryptr = fHashTable.find(desc)) {
SkASSERT(*entryptr);
entry = *entryptr;
}
if (!entry) {
#ifdef GR_PIPELINE_STATE_CACHE_STATS
++fCacheMisses;
#endif
sk_sp<GrVkPipelineState> pipelineState(
GrVkPipelineStateBuilder::CreatePipelineState(fGpu,
pipeline,
primProc,
primitiveType,
desc,
renderPass));
if (nullptr == pipelineState) {
return nullptr;
}
if (fCount < kMaxEntries) {
entry = new Entry;
fCount++;
} else {
SkASSERT(fCount == kMaxEntries);
entry = fLRUList.head();
fLRUList.remove(entry);
entry->fPipelineState->freeGPUResources(fGpu);
fHashTable.remove(entry->fPipelineState->getDesc());
}
entry->fPipelineState = std::move(pipelineState);
fHashTable.set(entry);
fLRUList.addToTail(entry);
return entry->fPipelineState;
} else {
fLRUList.remove(entry);
fLRUList.addToTail(entry);
}
return entry->fPipelineState;
}
|
867a16ad9881807c9feb461fecb83742475fb031 | 6494946d8db9db58f57c68253a8d0b658998c8ef | /Engine/Source/Renderer/Backend/Vulkan/Renderer Backend Layer/Compute/VulkanComputeCore.h | b55475d89482136810ec97b47838564e2aa8f43a | [] | no_license | DhirajWishal/DynamikEngine-Prototype | bc7dbad1d8c13d2489bcfdc7d6f22e55932f5b7b | 0a95277c394b69e66f79342f028834458694af93 | refs/heads/master | 2022-11-10T00:02:30.496607 | 2020-06-27T04:46:03 | 2020-06-27T04:46:03 | 198,091,316 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,336 | h | VulkanComputeCore.h | #pragma once
#ifndef _DYNAMIK_RENDERER_VULKAN_COMPUTE_CORE_H
#define _DYNAMIK_RENDERER_VULKAN_COMPUTE_CORE_H
#include <vulkan/vulkan.h>
namespace Dynamik {
namespace Renderer {
namespace Backend {
struct VulkanComputeShaderPhysicalDeviceLimits {
VulkanComputeShaderPhysicalDeviceLimits() {}
VulkanComputeShaderPhysicalDeviceLimits(VkPhysicalDeviceProperties props)
{
maxSharedMemorySize = props.limits.maxComputeSharedMemorySize;
maxWorkGroupCount[0] = props.limits.maxComputeWorkGroupCount[0];
maxWorkGroupCount[1] = props.limits.maxComputeWorkGroupCount[1];
maxWorkGroupCount[2] = props.limits.maxComputeWorkGroupCount[2];
maxWorkGroupInvocations = props.limits.maxComputeWorkGroupInvocations;
maxWorkGroupSize[0] = props.limits.maxComputeWorkGroupSize[0];
maxWorkGroupSize[1] = props.limits.maxComputeWorkGroupSize[1];
maxWorkGroupSize[2] = props.limits.maxComputeWorkGroupSize[2];
}
~VulkanComputeShaderPhysicalDeviceLimits() {}
UI32 maxSharedMemorySize = 0;
UI32 maxWorkGroupCount[3] = { 0 };
UI32 maxWorkGroupInvocations = 0;
UI32 maxWorkGroupSize[3] = { 0 };
};
struct VulkanComputeQueue {
std::optional<UI32> transferFamily;
std::optional<UI32> computeFamily;
static VulkanComputeQueue getQueues(VkPhysicalDevice physicalDevice);
B1 isComplete();
};
class VulkanComputeCore {
public:
VulkanComputeCore() {}
virtual ~VulkanComputeCore() {}
void initializeInstance();
void initializeDevice();
void submitQueue(std::vector<VkCommandBuffer> commandBuffers);
void finishCompute();
static UI32 getBestTransferQueue(VkPhysicalDevice physicalDevice);
static UI32 getBestComputeQueue(VkPhysicalDevice physicalDevice);
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice logicalDevice = VK_NULL_HANDLE;
VulkanComputeQueue queueFamilyIndices;
VkQueue computeQueue = VK_NULL_HANDLE;
VkQueue transferQueue = VK_NULL_HANDLE;
VulkanComputeShaderPhysicalDeviceLimits physicalDeviceLimits;
VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties;
private:
void initializePhysicalDevice();
void initializeLogicalDevice();
};
}
}
}
#endif // !_DYNAMIK_RENDERER_VULKAN_COMPUTE_CORE_H
|
1cafc44e73caeca2d6e57219bda659e940d2f11a | 5064c00dab4bb072a9c1753deda1a6948d139f33 | /ForkSPE/Code/Editor/Editor/SelectionEditObject.cpp | 381a6cf85042c71aa9cbffa083011d7ca1f515d3 | [] | no_license | google-code/asuraengine | be030dd909ba82e53515c53669a239c8aef2e164 | cfbdd1c65ee2ba23333383162db834eaaba35786 | refs/heads/master | 2018-01-07T21:19:08.100522 | 2015-03-15T15:35:55 | 2015-03-15T15:35:55 | 32,268,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,901 | cpp | SelectionEditObject.cpp | /*
* Selection editor object file
*
* This file is part of the "SoftPixel Sandbox" (Copyright (c) 2011 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "SelectionEditObject.h"
#include "EditBaseObject.h"
#include "ObjectSelector.h"
#include "EditMeshObject.h"
#include "Utility.h"
SelectionEditObject::SelectionEditObject(EditBaseObject* Object) :
SelectionNode (SELECTION_EDITOBJECT ),
Object_ (Object )
{
}
SelectionEditObject::~SelectionEditObject()
{
}
void SelectionEditObject::SetSelection(bool Enable)
{
Object_->SetSelection(Enable);
}
void SelectionEditObject::ApplyTranslation(
const dim::matrix4f &Transformation, const SSelectorTransformation &SelectorTrans)
{
#ifdef SP_COMPILE_WITH_PHYSICS
if (EditCollisionObject::IsSimulation())
{
/* Update translation with physics simulation */
if (Object_->GetType() == OBJECT_MESH)
{
EditMeshObject* MeshObject = static_cast<EditMeshObject*>(Object_);
physics::RigidBody* RigidBody = MeshObject->GetRigidBody();
if (RigidBody)
RigidBody->setVelocity(Transformation.getPosition() * RigidBody->getMass());
}
}
else
#endif
{
/* Update translation */
Object_->GetNode()->setPositionMatrix(
Object_->GetNode()->getPositionMatrix(true) * Transformation, true
);
}
/* Call transformation update callback */
Object_->UpdateTransformation();
}
void SelectionEditObject::ApplyRotation(
const dim::matrix4f &Transformation, const SSelectorTransformation &SelectorTrans)
{
/* Update translation for grouping */
if (SelectorTrans.Grouping || SelectorTrans.UseCursor3D)
{
const dim::vector3df OriginOffset(Object_->GetNode()->getPosition(true) - SelectorTrans.Position);
const dim::vector3df MoveOffset(Transformation * OriginOffset - OriginOffset);
Object_->GetNode()->translate(MoveOffset);
}
/* Update rotation */
if (Object_->GetFlags() & OBJECT_FLAG_ROTATE)
{
Object_->GetNode()->setRotationMatrix(
Transformation * Object_->GetNode()->getRotationMatrix(true), true
);
}
/* Call transformation update callback */
Object_->UpdateTransformation();
}
void SelectionEditObject::ApplyScaling(
const dim::matrix4f &Transformation, const SSelectorTransformation &SelectorTrans)
{
/* Get updated scale motion */
dim::vector3df ScaleMotion(Transformation.getScale(true));
if (SelectorTrans.UsedCenter)
{
const dim::vector3df Size(GetTransformation().getScale().getAbs());
ScaleMotion = ScaleMotion * Size / SelectorTrans.LargestScaling;
}
if (Object_->GetFlags() & OBJECT_FLAG_SCALE)
Object_->GetNode()->transform(ScaleMotion);
if (SelectorTrans.Grouping && ObjectSelector::SelectedList.size() > 1)
{
/* Update translation for grouping scaling */
const dim::vector3df OriginDir(
Object_->GetNode()->getPosition(true) - SelectorTrans.Position
);
Object_->GetNode()->translate(
OriginDir * Transformation.getScale(true) / SelectorTrans.LargestScaling
);
}
else if (ObjectSelector::SelectedList.size() == 1 && SelectorTrans.ScaleMode != SCALEMODE_NORMAL)
{
/* Update translation for positive/negative scaling */
if (SelectorTrans.ScaleMode == SCALEMODE_POSITIVE_XYZ)
Object_->GetNode()->move(-ScaleMotion * Object_->GetBoundBox().Min);
else if (SelectorTrans.ScaleMode == SCALEMODE_NEGATIVE_XYZ)
Object_->GetNode()->move(-ScaleMotion * Object_->GetBoundBox().Max);
}
/* Call transformation update callback */
Object_->UpdateTransformation();
}
void SelectionEditObject::PickPosition(
const scene::SIntersectionContact &Contact, const dim::vector3d<bool> &AxesEnabled)
{
/* Setup bounding box picking offset */
const dim::aabbox3df BoundBox(
Utility::GetRotatedAABB(
Object_->GetBoundBox().getScaled(Object_->GetNode()->getScale(true)),
Object_->GetNode()->getRotationMatrix(true)
)
);
dim::vector3df Position(Contact.Point);
if (Contact.Normal.X < -0.5f) Position.X -= BoundBox.Max.X;
else if (Contact.Normal.X > 0.5f) Position.X -= BoundBox.Min.X;
else if (Contact.Normal.Z < -0.5f) Position.Z -= BoundBox.Max.Z;
else if (Contact.Normal.Z > 0.5f) Position.Z -= BoundBox.Min.Z;
else if (Contact.Normal.Y < -0.5f) Position.Y -= BoundBox.Max.Y;
else Position.Y -= BoundBox.Min.Y;
/* Setup new object position */
scene::SceneNode* Node = Object_->GetNode();
if (!AxesEnabled.X || !AxesEnabled.Y || !AxesEnabled.Z)
{
const dim::vector3df PrevPosition = Node->getPosition(true);
if (!AxesEnabled.X) Position.X = PrevPosition.X;
if (!AxesEnabled.Y) Position.Y = PrevPosition.Y;
if (!AxesEnabled.Z) Position.Z = PrevPosition.Z;
}
Node->setPosition(Position, true);
/* Call transformation update callback */
Object_->UpdateTransformation();
}
dim::matrix4f SelectionEditObject::GetTransformation() const
{
return Object_->GetNode()->getTransformMatrix(true);
}
bool SelectionEditObject::SetupVisibilityFilter()
{
VisibleFiltered_ = Object_->IsVisibleFiltered();
return VisibleFiltered_;
}
void SelectionEditObject::Delete()
{
EditBaseObject::DeleteObject(Object_);
}
// ================================================================================
|
4bbc5db3e0fe1e2c5c1d5b356dad21568c761a3c | eee94734ab34b11012b572daf5004ab457c4f9da | /2013/Falling Ants.cpp | 280fbd55b325d0626d46f98edab3caa9c96eba46 | [] | no_license | mashrur29/ACM-ICPC-Dhaka-Regionals | b2c832461dcb8c131d67bbc499c2bdb8e272df02 | 669bd3501aab3fa532219fc452cb892af9e3d882 | refs/heads/master | 2021-09-16T01:25:21.466351 | 2018-06-14T07:51:53 | 2018-06-14T07:51:53 | 110,779,612 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 814 | cpp | Falling Ants.cpp | // https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4447
#include<bits/stdc++.h>
using namespace std;
#define eps 1e-9
const double g = 9.8;
double _calculate(double h) {
double ret = 1.0 - (1.0/(2.0 * h));
return ret;
}
int volume(int L, int W, int H) {
return (L * W * H);
}
int main() {
int n;
while(cin>>n && n) {
double res = -10000000000.0;
int ans;
for(int i=1; i<=n; i++) {
int L, W, H;
cin>>L>>W>>H;
double tmp = _calculate(H);
if(tmp + eps >= res) {
if(tmp == res) ans = max(ans, volume(L, W, H));
else ans = volume(L, W, H);
res = tmp;
}
}
cout<<ans<<endl;
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.