hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
6eafe9cb59a4c7d0f53033ba8e903c6ed9e55207
4,055
hpp
C++
components/structures/include/ftl/data/new_frameset.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
4
2020-12-28T15:29:15.000Z
2021-06-27T12:37:15.000Z
components/structures/include/ftl/data/new_frameset.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
null
null
null
components/structures/include/ftl/data/new_frameset.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
2
2021-01-13T05:28:39.000Z
2021-05-04T03:37:11.000Z
#ifndef _FTL_DATA_NFRAMESET_HPP_ #define _FTL_DATA_NFRAMESET_HPP_ #include <ftl/threads.hpp> #include <ftl/timer.hpp> #include <ftl/data/new_frame.hpp> #include <ftl/utility/intrinsics.hpp> #include <functional> //#include <opencv2/opencv.hpp> #include <vector> namespace ftl { namespace data { // Allows a latency of 20 frames maximum //static const size_t kMaxFramesets = 15; static const size_t kMaxFramesInSet = 32; enum class FSFlag : int { STALE = 0, PARTIAL = 1, DISCARD = 4, AUTO_SEND = 8 }; /** * Represents a set of synchronised frames, each with two channels. This is * used to collect all frames from multiple computers that have the same * timestamp. */ class FrameSet : public ftl::data::Frame { private: //FrameSet(Pool *ppool, Session *parent, uint32_t pid, int64_t ts) : // Frame(ppool, parent, pid | 0xFF, ts) {}; public: FrameSet(Pool *ppool, FrameID pid, int64_t ts, size_t psize=1); ~FrameSet(); //int id=0; //int64_t timestamp; // Millisecond timestamp of all frames int64_t localTimestamp; std::vector<Frame> frames; //std::atomic<int> count=0; // Actual packet count //std::atomic<int> expected=0; // Expected packet count std::atomic<unsigned int> mask; // Mask of all sources that contributed //std::atomic<int> flush_count; // How many channels have been flushed SHARED_MUTEX smtx; //Eigen::Matrix4d pose; // Set to identity by default. inline void set(FSFlag f) { flags_ |= (1 << static_cast<int>(f)); } inline void clear(FSFlag f) { flags_ &= ~(1 << static_cast<int>(f)); } inline bool test(FSFlag f) const { return flags_ & (1 << static_cast<int>(f)); } inline void clearFlags() { flags_ = 0; } std::unordered_set<ftl::codecs::Channel> channels(); /** * Move the entire frameset to another frameset object. This will * invalidate the current frameset object as all memory buffers will be * moved. */ void moveTo(ftl::data::FrameSet &); /** * Mark a frame as being completed. This modifies the mask and count * members. */ void completed(size_t ix); inline void markPartial() { set(ftl::data::FSFlag::PARTIAL); } /** * Are all frames complete within this frameset? */ inline bool isComplete() { return mask != 0 && ftl::popcount(mask) >= frames.size(); } /** * Check that a given frame is valid in this frameset. */ inline bool hasFrame(size_t ix) const { return (1 << ix) & mask; } /** * Get the first valid frame in this frameset. No valid frames throws an * exception. */ Frame &firstFrame(); const Frame &firstFrame() const; const Frame &firstFrame(ftl::codecs::Channel) const; inline Frame &operator[](int ix) { return frames[ix]; } inline const Frame &operator[](int ix) const { return frames[ix]; } /** * Flush all frames in the frameset. */ void flush(); /** * Store all frames. */ void store(); /** * Flush a channel for all frames in the frameset. */ void flush(ftl::codecs::Channel); void resize(size_t s); /** * Force a change to all frame timestamps. This is generally used internally * to allow frameset buffering in advance of knowing an exact timestamp. * The method will update the timestamps of all contained frames and the * frameset itself. */ void changeTimestamp(int64_t ts); /** * Make a frameset from a single frame. It borrows the pool, id and * timestamp from the frame and creates a wrapping frameset instance. */ static std::shared_ptr<FrameSet> fromFrame(Frame &); /** * Check if channel has changed in any frames. */ bool hasAnyChanged(ftl::codecs::Channel) const; bool anyHasChannel(ftl::codecs::Channel) const; private: std::atomic<int> flags_; }; using FrameSetPtr = std::shared_ptr<ftl::data::FrameSet>; using FrameSetCallback = std::function<bool(const FrameSetPtr&)>; class Generator { public: virtual ftl::Handle onFrameSet(const FrameSetCallback &)=0; }; /** * Callback type for receiving video frames. */ //typedef std::function<bool(ftl::rgbd::FrameSet &)> VideoCallback; } } #endif // _FTL_DATA_FRAMESET_HPP_
25.34375
87
0.693711
knicos
6eb68ae0d50e51b6645fa88451887be88d8954e8
251
hpp
C++
editor/ui/windows/inspector/status/status_sceneobject.hpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
editor/ui/windows/inspector/status/status_sceneobject.hpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
editor/ui/windows/inspector/status/status_sceneobject.hpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
#pragma once #include "chokoeditor.hpp" CE_BEGIN_ED_NAMESPACE class EW_IS_SceneObject : public EW_I_Status { public: bool expanded = false; int childHeight = 0; EW_I_Status::UMap components = EW_I_Status::UMap(); }; CE_END_ED_NAMESPACE
17.928571
55
0.749004
chokomancarr
6ebac47afa2efeed3ac3c7a06b4f0ce30f10cbb1
613
hpp
C++
inc/openssl/openssl_ecdsa.hpp
finlchain/fvm
87ac95227aeec88f27198374830a8289fcdfd1a9
[ "MIT" ]
null
null
null
inc/openssl/openssl_ecdsa.hpp
finlchain/fvm
87ac95227aeec88f27198374830a8289fcdfd1a9
[ "MIT" ]
null
null
null
inc/openssl/openssl_ecdsa.hpp
finlchain/fvm
87ac95227aeec88f27198374830a8289fcdfd1a9
[ "MIT" ]
null
null
null
/** * Description : * * @date 2021/01/21 * @author FINL Chain Team * @version 1.0 */ #ifndef __OPENSSL_ECDSA_HPP__ #define __OPENSSL_ECDSA_HPP__ #ifdef __cplusplus extern "C" { #endif // extern EVP_PKEY *openssl_get_ec_pkey(char *p_prikey_str, int32_t ec_algo) ; // extern int32_t openssl_ecdsa_sig(EVP_PKEY *p_pkey, uint8_t *p_data, uint32_t data_len, SSL_SIG_U *p_sig_hex); extern int32_t openssl_ecdsa_verify(uint8_t *p_data, uint32_t data_len, SSL_SIG_U *p_sig_hex, uint8_t *p_comp_pubkey, int32_t ec_algo); #ifdef __cplusplus } #endif #endif // __OPENSSL_ECDSA_HPP__
21.137931
136
0.730832
finlchain
6ec08bdb415f88d0fd904866710d7bb642703013
13,657
cpp
C++
Code/Ports/MD3Port/MD3PointConf.cpp
ScottEllisNovatex/opendatacon
1d5a6627db88f0335615c67d4417791651f0944c
[ "ECL-2.0", "Apache-2.0" ]
12
2018-01-23T20:16:03.000Z
2020-08-01T16:31:56.000Z
Code/Ports/MD3Port/MD3PointConf.cpp
ScottEllisNovatex/opendatacon
1d5a6627db88f0335615c67d4417791651f0944c
[ "ECL-2.0", "Apache-2.0" ]
83
2015-07-16T07:41:05.000Z
2022-02-21T06:26:03.000Z
Code/Ports/MD3Port/MD3PointConf.cpp
ScottEllisNovatex/opendatacon
1d5a6627db88f0335615c67d4417791651f0944c
[ "ECL-2.0", "Apache-2.0" ]
12
2018-01-22T00:48:53.000Z
2021-02-03T11:06:39.000Z
/* opendatacon * * Copyright (c) 2018: * * DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi * yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA== * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * MD3PointConf.cpp * * Created on: 01/04/2018 * Author: Scott Ellis <scott.ellis@novatex.com.au> */ #include "MD3PointConf.h" #include <algorithm> #include <map> #include <memory> #include <opendatacon/IOTypes.h> #include <opendatacon/util.h> #include <regex> using namespace odc; MD3PointConf::MD3PointConf(const std::string & _FileName, const Json::Value& ConfOverrides): ConfigParser(_FileName, ConfOverrides), FileName(_FileName) { LOGDEBUG("Conf processing file - {}",FileName); ProcessFile(); // This should call process elements below? } void MD3PointConf::ProcessElements(const Json::Value& JSONRoot) { if (!JSONRoot.isObject()) return; // Root level Configuration values LOGDEBUG("MD3 Conf processing"); try { // PollGroups must be processed first if (JSONRoot.isMember("PollGroups")) { const auto PollGroups = JSONRoot["PollGroups"]; ProcessPollGroups(PollGroups); } if (JSONRoot.isMember("Analogs")) { const auto Analogs = JSONRoot["Analogs"]; LOGDEBUG("Conf processed - Analog Points"); ProcessAnalogCounterPoints(Analog, Analogs); } if (JSONRoot.isMember("Counters")) { const auto Counters = JSONRoot["Counters"]; LOGDEBUG("Conf processed - Counter Points"); ProcessAnalogCounterPoints(Counter, Counters); } if (JSONRoot.isMember("AnalogControls")) { const auto AnalogControls = JSONRoot["AnalogControls"]; LOGDEBUG("Conf processed - AnalogControls"); ProcessAnalogCounterPoints(AnalogControl, AnalogControls); } if (JSONRoot.isMember("Binaries")) { const auto Binaries = JSONRoot["Binaries"]; LOGDEBUG("Conf processed - Binary Points"); ProcessBinaryPoints(Binary, Binaries); } if (JSONRoot.isMember("BinaryControls")) { const auto BinaryControls = JSONRoot["BinaryControls"]; LOGDEBUG("Conf processed -Binary Controls"); ProcessBinaryPoints(BinaryControl, BinaryControls); } if (JSONRoot.isMember("NewDigitalCommands")) { NewDigitalCommands = JSONRoot["NewDigitalCommands"].asBool(); LOGDEBUG("Conf processed - NewDigitalCommands - {}",NewDigitalCommands); } if (JSONRoot.isMember("OverrideOldTimeStamps")) { OverrideOldTimeStamps = JSONRoot["OverrideOldTimeStamps"].asBool(); LOGDEBUG("Conf processed - OverrideOldTimeStamps - {}",OverrideOldTimeStamps); } if (JSONRoot.isMember("UpdateAnalogCounterTimeStamps")) { OverrideOldTimeStamps = JSONRoot["UpdateAnalogCounterTimeStamps"].asBool(); LOGDEBUG("Conf processed - UpdateAnalogCounterTimeStamps - {}",UpdateAnalogCounterTimeStamps); } if (JSONRoot.isMember("StandAloneOutstation")) { StandAloneOutstation = JSONRoot["StandAloneOutstation"].asBool(); LOGDEBUG("Conf processed - StandAloneOutstation - {}",StandAloneOutstation); } if (JSONRoot.isMember("MD3CommandTimeoutmsec")) { MD3CommandTimeoutmsec = JSONRoot["MD3CommandTimeoutmsec"].asUInt(); LOGDEBUG("Conf processed - MD3CommandTimeoutmsec - {}",MD3CommandTimeoutmsec); } if (JSONRoot.isMember("MD3CommandRetries")) { MD3CommandRetries = JSONRoot["MD3CommandRetries"].asUInt(); LOGDEBUG("Conf processed - MD3CommandRetries - {}",MD3CommandRetries); } } catch (const std::exception& e) { LOGERROR("Exception Caught while processing {}, {} - configuration not loaded", FileName, e.what()); } LOGDEBUG("End Conf processing"); } // This method must be processed before points are loaded void MD3PointConf::ProcessPollGroups(const Json::Value & JSONNode) { LOGDEBUG("Conf processing - PollGroups"); for (Json::ArrayIndex n = 0; n < JSONNode.size(); ++n) { if (!JSONNode[n].isMember("ID")) { LOGERROR("Poll group missing ID : {}",JSONNode[n].toStyledString() ); continue; } if (!JSONNode[n].isMember("PollRate")) { LOGERROR("Poll group missing PollRate : {}", JSONNode[n].toStyledString()); continue; } if (!JSONNode[n].isMember("PointType")) { LOGERROR("Poll group missing PollType (Binary, Analog or TimeSetCommand, NewTimeSetCommand, SystemFlagScan) : {}", JSONNode[n].toStyledString()); continue; } uint32_t PollGroupID = JSONNode[n]["ID"].asUInt(); uint32_t pollrate = JSONNode[n]["PollRate"].asUInt(); if (PollGroupID == 0) { LOGERROR("Poll group 0 is reserved (do not poll) : {}", JSONNode[n].toStyledString()); continue; } if (PollGroups.count(PollGroupID) > 0) { LOGERROR("Duplicate poll group ignored : {}", JSONNode[n].toStyledString()); continue; } PollGroupType polltype = BinaryPoints; // Default to Binary if (iequals(JSONNode[n]["PointType"].asString(), "Analog")) { polltype = AnalogPoints; } if (iequals(JSONNode[n]["PointType"].asString(), "Counter")) { polltype = CounterPoints; } if (iequals(JSONNode[n]["PointType"].asString(), "TimeSetCommand")) { polltype = TimeSetCommand; } if (iequals(JSONNode[n]["PointType"].asString(), "NewTimeSetCommand")) { polltype = NewTimeSetCommand; } if (iequals(JSONNode[n]["PointType"].asString(), "SystemFlagScan")) { polltype = SystemFlagScan; } bool ForceUnconditional = false; if (JSONNode[n].isMember("ForceUnconditional")) { ForceUnconditional = JSONNode[n]["ForceUnconditional"].asBool(); } bool TimeTaggedDigital = false; if (JSONNode[n].isMember("TimeTaggedDigital")) { TimeTaggedDigital = JSONNode[n]["TimeTaggedDigital"].asBool(); } LOGDEBUG("Conf processed - PollGroup - {}, Rate {}, Type {}, TimeTaggedDigital {}, Force Unconditional Command {}", PollGroupID, pollrate, polltype, TimeTaggedDigital, ForceUnconditional); PollGroups.emplace(std::piecewise_construct, std::forward_as_tuple(PollGroupID), std::forward_as_tuple(PollGroupID, pollrate, polltype, ForceUnconditional, TimeTaggedDigital)); } LOGDEBUG("Conf processing - PollGroups - Finished"); } // This method loads both Binary read points, and Binary Control points. void MD3PointConf::ProcessBinaryPoints(PointType ptype, const Json::Value& JSONNode) { LOGDEBUG("Conf processing - Binary"); std::string BinaryName; if (ptype == Binary) BinaryName = "Binary"; if (ptype == BinaryControl) BinaryName = "BinaryControl"; for (Json::ArrayIndex n = 0; n < JSONNode.size(); ++n) { bool error = false; uint32_t start, stop; if (JSONNode[n].isMember("Index")) { start = stop = JSONNode[n]["Index"].asUInt(); } else if (JSONNode[n]["Range"].isMember("Start") && JSONNode[n]["Range"].isMember("Stop")) { start = JSONNode[n]["Range"]["Start"].asUInt(); stop = JSONNode[n]["Range"]["Stop"].asUInt(); } else { LOGERROR("{} A point needs an \"Index\" or a \"Range\" with a \"Start\" and a \"Stop\" : {}", BinaryName ,JSONNode[n].toStyledString()); start = 1; stop = 0; error = true; } uint32_t module = 0; uint32_t offset = 0; uint32_t pollgroup = 0; BinaryPointType pointtype = BASICINPUT; std::string pointtypestring; if (JSONNode[n].isMember("Module")) module = JSONNode[n]["Module"].asUInt(); else { LOGERROR("{} A point needs an \"Module\" : {}", BinaryName ,JSONNode[n].toStyledString()); error = true; } if (JSONNode[n].isMember("Offset")) offset = JSONNode[n]["Offset"].asUInt(); else { LOGERROR("{} A point needs an \"Offset\" : {}", BinaryName, JSONNode[n].toStyledString()); error = true; } if (JSONNode[n].isMember("PointType")) { pointtypestring = JSONNode[n]["PointType"].asString(); if (pointtypestring == "BASICINPUT") pointtype = BASICINPUT; else if (pointtypestring == "TIMETAGGEDINPUT") pointtype = TIMETAGGEDINPUT; else if (pointtypestring == "DOMOUTPUT") pointtype = DOMOUTPUT; else if (pointtypestring == "POMOUTPUT") pointtype = POMOUTPUT; else if (pointtypestring == "DIMOUTPUT") pointtype = DIMOUTPUT; else { LOGERROR("{} A point needs a valid \"PointType\" : {}", BinaryName, JSONNode[n].toStyledString()); error = true; } } else { LOGERROR("{} A point needs an \"PointType\" : {}", BinaryName, JSONNode[n].toStyledString()); error = true; } if (JSONNode[n].isMember("PollGroup")) { pollgroup = JSONNode[n]["PollGroup"].asUInt(); } if (!error) { for (uint32_t index = start; index <= stop; index++) { auto moduleaddress = static_cast<uint8_t>(module + (index - start + offset) / 16); auto channel = static_cast<uint8_t>((offset + (index - start)) % 16); bool res = false; LOGDEBUG("Adding a {} - Index: {} Module: {} Channel: {} Point Type : {}", BinaryName, index, moduleaddress, channel, pointtypestring); if (ptype == Binary) { res = PointTable.AddBinaryPointToPointTable(index, moduleaddress, channel, pointtype, pollgroup); } else if (ptype == BinaryControl) { res = PointTable.AddBinaryControlPointToPointTable(index, moduleaddress, channel, pointtype, pollgroup); } else LOGERROR("Illegal point type passed to ProcessBinaryPoints"); if (res) { // If the point is part of a scan group, add the module address. Don't duplicate the address. if (pollgroup != 0) { if (PollGroups.count(pollgroup) == 0) { LOGERROR("{} Poll Group Must Be Defined for use in a Binary point : {}", BinaryName, JSONNode[n].toStyledString()); } else { // Control points and binary inputs are processed here. // If the map does have an entry for moduleaddress, we just set the second element of the pair (to a non value). // If it does not, add the moduleaddress,0 pair to the map - which will be sorted. PollGroups[pollgroup].ModuleAddresses[moduleaddress] = 0; } } } } } } LOGDEBUG("Conf processing - Binary - Finished"); } // This method loads both Analog and Counter/Timers. They look functionally similar in MD3 void MD3PointConf::ProcessAnalogCounterPoints(PointType ptype, const Json::Value& JSONNode) { LOGDEBUG("Conf processing - Analog/Counter"); for (Json::ArrayIndex n = 0; n < JSONNode.size(); ++n) { bool error = false; size_t start, stop; if (JSONNode[n].isMember("Index")) { start = stop = JSONNode[n]["Index"].asUInt(); } else if (JSONNode[n]["Range"].isMember("Start") && JSONNode[n]["Range"].isMember("Stop")) { start = JSONNode[n]["Range"]["Start"].asUInt(); stop = JSONNode[n]["Range"]["Stop"].asUInt(); } else { LOGERROR("An analog/counter point needs an \"Index\" or a \"Range\" with a \"Start\" and a \"Stop\" : {}", JSONNode[n].toStyledString()); start = 1; stop = 0; error = true; } uint32_t module = 0; uint32_t offset = 0; uint32_t pollgroup = 0; if (JSONNode[n].isMember("Module")) module = JSONNode[n]["Module"].asUInt(); else { LOGERROR("A point needs an \"Module\" : {}", JSONNode[n].toStyledString()); error = true; } if (JSONNode[n].isMember("Offset")) offset = JSONNode[n]["Offset"].asUInt(); else { LOGERROR("A point needs an \"Offset\" : {}", JSONNode[n].toStyledString()); error = true; } if (JSONNode[n].isMember("PollGroup")) { pollgroup = JSONNode[n]["PollGroup"].asUInt(); } if (!error) { for (auto index = start; index <= stop; index++) { auto moduleaddress = static_cast<uint8_t>(module + (index - start + offset) / 16); auto channel = static_cast<uint8_t>((offset + (index - start)) % 16); bool res = false; if (ptype == Analog) { res = PointTable.AddAnalogPointToPointTable(index, moduleaddress, channel, pollgroup); } else if (ptype == Counter) { res = PointTable.AddCounterPointToPointTable(index, moduleaddress, channel, pollgroup); } else if (ptype == AnalogControl) { res = PointTable.AddAnalogControlPointToPointTable(index, moduleaddress, channel, pollgroup); } else LOGERROR("Illegal point type passed to ProcessAnalogCounterPoints"); if (res) { // If the point is part of a scan group, add the module address. Don't duplicate the address. if (pollgroup != 0) { if (PollGroups.count(pollgroup) == 0) { LOGERROR("Poll Group Must Be Defined for use in an Analog/Counter point : {}",JSONNode[n].toStyledString()); } else { // This will add the module address to the poll group if missing, and then we add a channel to the current count (->second field) // Assume second is 0 the first time it is referenced? uint16_t channels = PollGroups[pollgroup].ModuleAddresses[moduleaddress]; PollGroups[pollgroup].ModuleAddresses[moduleaddress] = channels + 1; LOGDEBUG("Added Point {}, {} To Poll Group {}",moduleaddress, channel,pollgroup); if (PollGroups[pollgroup].ModuleAddresses.size() > 1) { LOGERROR("Analog or Counter Poll group {} is configured for more than one MD3 Module address. To scan another address, another poll group must be used.",pollgroup); } } } } } } } LOGDEBUG("Conf processing - Analog/Counter - Finished"); }
30.621076
178
0.674746
ScottEllisNovatex
6ec4e17f33db4a370d14ca556a143da263b6de86
7,710
cpp
C++
srci/bilinear.cpp
erikedwards4/nn
c4b8317a38a72a16fd0bf905791b6c19e49c0aa7
[ "BSD-3-Clause" ]
1
2020-08-26T09:28:40.000Z
2020-08-26T09:28:40.000Z
srci/bilinear.cpp
erikedwards4/nn
c4b8317a38a72a16fd0bf905791b6c19e49c0aa7
[ "BSD-3-Clause" ]
null
null
null
srci/bilinear.cpp
erikedwards4/nn
c4b8317a38a72a16fd0bf905791b6c19e49c0aa7
[ "BSD-3-Clause" ]
null
null
null
//Includes #include "bilinear.c" //Declarations const valarray<size_t> oktypes = {1u,2u,101u,102u}; const size_t I = 4u, O = 1u; size_t Ni1, Ni2, No, L; //Description string descr; descr += "IN method.\n"; descr += "Bilinear transformation of 2 layers of inputs.\n"; descr += "\n"; descr += "Input X1 has Ni1 neurons and input X2 has Ni2 neurons\n"; descr += "The output Y has No neurons.\n"; descr += "Each output neuron has a bias term, so B is a vector of length No.\n"; descr += "The weights (W) are a 3D tensor.\n"; descr += "\n"; descr += "If col-major: Y[n,l] = X1[:,l]'*W[:,:,n]*X2[:,l] + B[n] \n"; descr += "where:\n"; descr += "X1 has size Ni1 x L \n"; descr += "X2 has size Ni2 x L \n"; descr += "Y has size No x L \n"; descr += "W has size Ni1 x Ni2 x No \n"; descr += "B has size No x 1 \n"; descr += "\n"; descr += "If row-major: Y[l,n] = X1[l,:]*W[n,:,:]*X2[l,:]' + B[n] \n"; descr += "where:\n"; descr += "X1 has size L x Ni1 \n"; descr += "X2 has size L x Ni2 \n"; descr += "Y has size L x No \n"; descr += "W has size No x Ni2 x Ni1 \n"; descr += "B has size 1 x No \n"; descr += "\n"; descr += "Examples:\n"; descr += "$ bilinear X1 X2 W B -o Y \n"; descr += "$ bilinear X1 X2 W B > Y \n"; descr += "$ cat X | bilinear - W B > Y \n"; //Argtable struct arg_file *a_fi = arg_filen(nullptr,nullptr,"<file>",I-1,I,"input files (X1,X2,W,B)"); struct arg_file *a_fo = arg_filen("o","ofile","<file>",0,O,"output file (Y)"); //Get options //Checks if (i1.T!=i2.T || i1.T!=i3.T || i1.T!=i4.T) { cerr << progstr+": " << __LINE__ << errstr << "inputs must have the same data type" << endl; return 1; } if (i1.isempty()) { cerr << progstr+": " << __LINE__ << errstr << "input 1 (X1) found to be empty" << endl; return 1; } if (i2.isempty()) { cerr << progstr+": " << __LINE__ << errstr << "input 2 (X2) found to be empty" << endl; return 1; } if (i3.isempty()) { cerr << progstr+": " << __LINE__ << errstr << "input 3 (W) found to be empty" << endl; return 1; } if (i4.isempty()) { cerr << progstr+": " << __LINE__ << errstr << "input 4 (B) found to be empty" << endl; return 1; } if (!i1.ismat()) { cerr << progstr+": " << __LINE__ << errstr << "input 1 (X1) must be a matrix" << endl; return 1; } if (!i2.ismat()) { cerr << progstr+": " << __LINE__ << errstr << "input 2 (X2) must be a matrix" << endl; return 1; } if (!i3.iscube()) { cerr << progstr+": " << __LINE__ << errstr << "input 3 (W) must be a 3D tensor" << endl; return 1; } if (!i4.isvec()) { cerr << progstr+": " << __LINE__ << errstr << "input 4 (B) must be a vector" << endl; return 1; } L = i1.iscolmajor() ? i1.C : i1.R; Ni1 = i3.iscolmajor() ? i3.R : i3.S; Ni2 = i3.C; No = i3.iscolmajor() ? i3.S : i3.R; if (i4.N()!=No) { cerr << progstr+": " << __LINE__ << errstr << "length of input 4 (B) must equal No (num output neurons)" << endl; return 1; } if (i1.iscolmajor()) { if (i1.R!=Ni1) { cerr << progstr+": " << __LINE__ << errstr << "Input 1 (X1) must have size Ni1 x L for col-major" << endl; return 1; } if (i2.R!=Ni2) { cerr << progstr+": " << __LINE__ << errstr << "Input 2 (X2) must have size Ni2 x L for col-major" << endl; return 1; } } else { if (i1.C!=Ni1) { cerr << progstr+": " << __LINE__ << errstr << "Input 1 (X1) must have size L x Ni1 for row-major" << endl; return 1; } if (i2.C!=Ni2) { cerr << progstr+": " << __LINE__ << errstr << "Input 2 (X2) must have size L x Ni2 for row-major" << endl; return 1; } } //Set output header info o1.F = i1.F; o1.T = i1.T; o1.R = i1.iscolmajor() ? No : L; o1.C = i1.isrowmajor() ? No : L; o1.S = i1.S; o1.H = i1.H; //Other prep //Process if (i1.T==1u) { float *X1, *X2, *W, *B, *Y; try { X1 = new float[i1.N()]; } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem allocating for input file 1 (X1)" << endl; return 1; } try { X2 = new float[i2.N()]; } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem allocating for input file 2 (X2)" << endl; return 1; } try { W = new float[i3.N()]; } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem allocating for input file 3 (W)" << endl; return 1; } try { B = new float[i4.N()]; } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem allocating for input file 4 (B)" << endl; return 1; } try { Y = new float[o1.N()]; } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem allocating for output file (Y)" << endl; return 1; } try { ifs1.read(reinterpret_cast<char*>(X1),i1.nbytes()); } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem reading input file 1 (X1)" << endl; return 1; } try { ifs2.read(reinterpret_cast<char*>(X2),i2.nbytes()); } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem reading input file 2 (X2)" << endl; return 1; } try { ifs3.read(reinterpret_cast<char*>(W),i3.nbytes()); } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem reading input file 3 (W)" << endl; return 1; } try { ifs4.read(reinterpret_cast<char*>(B),i4.nbytes()); } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem reading input file 4 (B)" << endl; return 1; } if (codee::bilinear_s(Y,X1,X2,W,B,Ni1,Ni2,No,L)) { cerr << progstr+": " << __LINE__ << errstr << "problem during function call" << endl; return 1; } if (wo1) { try { ofs1.write(reinterpret_cast<char*>(Y),o1.nbytes()); } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem writing output file (Y)" << endl; return 1; } } delete[] X1; delete[] X2; delete[] W; delete[] B; delete[] Y; } else if (i1.T==101u) { float *X1, *X2, *W, *B, *Y; try { X1 = new float[2u*i1.N()]; } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem allocating for input file 1 (X1)" << endl; return 1; } try { X2 = new float[2u*i2.N()]; } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem allocating for input file 2 (X2)" << endl; return 1; } try { W = new float[2u*i3.N()]; } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem allocating for input file 3 (W)" << endl; return 1; } try { B = new float[2u*i4.N()]; } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem allocating for input file 4 (B)" << endl; return 1; } try { Y = new float[2u*o1.N()]; } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem allocating for output file (Y)" << endl; return 1; } try { ifs1.read(reinterpret_cast<char*>(X1),i1.nbytes()); } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem reading input file 1 (X1)" << endl; return 1; } try { ifs2.read(reinterpret_cast<char*>(X2),i2.nbytes()); } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem reading input file 2 (X2)" << endl; return 1; } try { ifs3.read(reinterpret_cast<char*>(W),i3.nbytes()); } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem reading input file 3 (W)" << endl; return 1; } try { ifs4.read(reinterpret_cast<char*>(B),i4.nbytes()); } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem reading input file 4 (B)" << endl; return 1; } if (codee::bilinear_c(Y,X1,X2,W,B,Ni1,Ni2,No,L)) { cerr << progstr+": " << __LINE__ << errstr << "problem during function call" << endl; return 1; } if (wo1) { try { ofs1.write(reinterpret_cast<char*>(Y),o1.nbytes()); } catch (...) { cerr << progstr+": " << __LINE__ << errstr << "problem writing output file (Y)" << endl; return 1; } } delete[] X1; delete[] X2; delete[] W; delete[] B; delete[] Y; } //Finish
53.916084
150
0.56511
erikedwards4
6eca9d2697d7c4cd63999c7a715c8a7d8e087640
3,230
cpp
C++
src/Loaders/NFS3/FRD/PolyBlock.cpp
AmrikSadhra/FCE-To-Obj
a3c928077add2bd5d5f3463daee6008f150a0a54
[ "MIT" ]
212
2019-08-10T16:57:57.000Z
2022-03-30T02:21:05.000Z
src/Loaders/NFS3/FRD/PolyBlock.cpp
AmrikSadhra/FCE-To-Obj
a3c928077add2bd5d5f3463daee6008f150a0a54
[ "MIT" ]
11
2018-07-10T18:01:09.000Z
2019-06-26T13:41:24.000Z
src/Loaders/NFS3/FRD/PolyBlock.cpp
AmrikSadhra/FCE-to-OBJ
a3c928077add2bd5d5f3463daee6008f150a0a54
[ "MIT" ]
20
2020-02-09T02:38:35.000Z
2022-03-23T20:26:28.000Z
#include "PolyBlock.h" using namespace LibOpenNFS::NFS3; PolyBlock::PolyBlock(std::ifstream &frd, uint32_t nTrackBlockPolys) : m_nTrackBlockPolys(nTrackBlockPolys), obj{} { ASSERT(this->_SerializeIn(frd), "Failed to serialize PolyBlock from file stream"); } bool PolyBlock::_SerializeIn(std::ifstream &ifstream) { for (uint32_t polyBlockIdx = 0; polyBlockIdx < NUM_POLYGON_BLOCKS; polyBlockIdx++) { SAFE_READ(ifstream, &sz[polyBlockIdx], sizeof(uint32_t)); if (sz[polyBlockIdx] != 0) { SAFE_READ(ifstream, &szdup[polyBlockIdx], sizeof(uint32_t)); if (szdup[polyBlockIdx] != sz[polyBlockIdx]) { return false; } poly[polyBlockIdx] = std::vector<PolygonData>(sz[polyBlockIdx]); SAFE_READ(ifstream, poly[polyBlockIdx].data(), sizeof(PolygonData) * sz[polyBlockIdx]); } } // Sanity check if (sz[4] != m_nTrackBlockPolys) { return false; } for (auto &o : obj) { SAFE_READ(ifstream, &o.n1, sizeof(uint32_t)); if (o.n1 > 0) { SAFE_READ(ifstream, &o.n2, sizeof(uint32_t)); o.types.resize(o.n2); o.numpoly.resize(o.n2); o.poly.resize(o.n2); uint32_t polygonCount = 0; o.nobj = 0; for (uint32_t k = 0; k < o.n2; ++k) { SAFE_READ(ifstream, &o.types[k], sizeof(uint32_t)); if (o.types[k] == 1) { SAFE_READ(ifstream, &o.numpoly[o.nobj], sizeof(uint32_t)); o.poly[o.nobj] = std::vector<PolygonData>(o.numpoly[o.nobj]); SAFE_READ(ifstream, o.poly[o.nobj].data(), sizeof(PolygonData) * o.numpoly[o.nobj]); polygonCount += o.numpoly[o.nobj]; ++o.nobj; } } // n1 == total nb polygons if (polygonCount != o.n1) { return false; } } } return true; } void PolyBlock::_SerializeOut(std::ofstream &ofstream) { for (uint32_t polyBlockIdx = 0; polyBlockIdx < NUM_POLYGON_BLOCKS; polyBlockIdx++) { ofstream.write((char *) &sz[polyBlockIdx], sizeof(uint32_t)); if (sz[polyBlockIdx] != 0) { ofstream.write((char *) &szdup[polyBlockIdx], sizeof(uint32_t)); ofstream.write((char *) poly[polyBlockIdx].data(), sizeof(PolygonData) * sz[polyBlockIdx]); } } for (auto &o : obj) { ofstream.write((char *) &o.n1, sizeof(uint32_t)); if (o.n1 > 0) { ofstream.write((char *) &o.n2, sizeof(uint32_t)); o.nobj = 0; for (uint32_t k = 0; k < o.n2; ++k) { ofstream.write((char *) &o.types[k], sizeof(uint32_t)); if (o.types[k] == 1) { ofstream.write((char *) &o.numpoly[o.nobj], sizeof(uint32_t)); ofstream.write((char *) o.poly[o.nobj].data(), sizeof(PolygonData) * o.numpoly[o.nobj]); ++o.nobj; } } } } }
30.761905
113
0.508669
AmrikSadhra
6ece4ca293c53317f3ce6ae3277518386e1f4873
7,023
hxx
C++
src/openlcb/BroadcastTimeServer.hxx
rilull/openmrn
f562c9957d4df2cbde7af6b9ebc70e190bd5f80c
[ "BSD-2-Clause" ]
7
2019-03-03T22:15:01.000Z
2021-12-17T13:09:21.000Z
src/openlcb/BroadcastTimeServer.hxx
rilull/openmrn
f562c9957d4df2cbde7af6b9ebc70e190bd5f80c
[ "BSD-2-Clause" ]
3
2019-10-17T20:51:59.000Z
2020-07-20T20:28:53.000Z
src/openlcb/BroadcastTimeServer.hxx
rilull/openmrn
f562c9957d4df2cbde7af6b9ebc70e190bd5f80c
[ "BSD-2-Clause" ]
7
2020-05-22T21:19:40.000Z
2021-05-30T08:19:55.000Z
/** @copyright * Copyright (c) 2018, Stuart W. Baker * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @file BroadcastTimeServer.hxx * * Implementation of a Broadcast Time Protocol Server. * * @author Stuart W. Baker * @date 4 November 2018 */ #ifndef _OPENLCB_BROADCASTTIMESERVER_HXX_ #define _OPENLCB_BROADCASTTIMESERVER_HXX_ #include "openlcb/BroadcastTime.hxx" #include "openlcb/BroadcastTimeAlarm.hxx" namespace openlcb { class BroadcastTimeServerTime; class BroadcastTimeServerSync; class BroadcastTimeServerSet; class BroadcastTimeServerAlarm; /// Implementation of a Broadcast Time Protocol client. class BroadcastTimeServer : public BroadcastTime { public: /// Constructor. /// @param node the virtual node that will be listening for events and /// responding to Identify messages. /// @param clock_id 48-bit unique identifier for the clock instance BroadcastTimeServer(Node *node, NodeID clock_id); /// Destructor. ~BroadcastTimeServer(); #if defined(GTEST) void shutdown(); bool is_shutdown(); #endif private: /// Handle requested identification message. /// @param entry registry entry for the event range /// @param event information about the incoming message /// @param done used to notify we are finished void handle_identify_global(const EventRegistryEntry &entry, EventReport *event, BarrierNotifiable *done) override { AutoNotify an(done); if (event->dst_node && event->dst_node != node_) { // not for us return; } if (is_terminated()) { start_flow(STATE(query_response)); } event->event_write_helper<1>()->WriteAsync( node_, Defs::MTI_PRODUCER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(EncodeRange(entry.event, 0x1 << 16)), done->new_child()); // we can configure ourselves event->event_write_helper<2>()->WriteAsync( node_, Defs::MTI_CONSUMER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(EncodeRange(entry.event + 0x8000, 0x1 << 15)), done->new_child()); } /// Handle requested identification message. /// @param entry registry entry for the event range /// @param event information about the incoming message /// @param done used to notify we are finished void handle_identify_consumer(const EventRegistryEntry &entry, EventReport *event, BarrierNotifiable *done) override { AutoNotify an(done); if (event->event >= (eventBase_ + 0x8000)) { // we can configure ourselves event->event_write_helper<1>()->WriteAsync( node_, Defs::MTI_CONSUMER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(EncodeRange(entry.event + 0x8000, 0x1 << 15)), done->new_child()); } } /// Handle requested identification message. /// @param entry registry entry for the event range /// @param event information about the incoming message /// @param done used to notify we are finished void handle_identify_producer(const EventRegistryEntry &entry, EventReport *event, BarrierNotifiable *done) override { AutoNotify an(done); event->event_write_helper<1>()->WriteAsync( node_, Defs::MTI_PRODUCER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(EncodeRange(entry.event, 0x1 << 16)), done->new_child()); } /// Handle an incoming consumer identified. /// @param entry registry entry for the event range /// @param event information about the incoming message /// @param done used to notify we are finished void handle_consumer_identified(const EventRegistryEntry &entry, EventReport *event, BarrierNotifiable *done) override; /// Handle an incoming event report. /// @param entry registry entry for the event range /// @param event information about the incoming message /// @param done used to notify we are finished void handle_event_report(const EventRegistryEntry &entry, EventReport *event, BarrierNotifiable *done) override; /// Try the possible set event shortcut. /// @param event event that we would be "setting" virtual void set_shortcut(uint64_t event) override; /// Entry to state machine. /// @return query_response after timeout Action entry() { return sleep_and_call(&timer_, MSEC_TO_NSEC(300), STATE(query_response)); } /// Respond to a query by scheduling a sync. /// @return exit() Action query_response(); //BroadcastTimeAlarmDate alarmDate_; ///< date rollover alarm time_t secondsRequested_; ///< pending clock time in seconds uint16_t updateRequested_ : 1; ///< clock settings have change #if defined(GTEST) uint16_t shutdown_ : 1; #endif BroadcastTimeServerTime *time_; BroadcastTimeServerSync *sync_; BroadcastTimeServerSet *set_; BroadcastTimeServerAlarm *alarm_; friend class BroadcastTimeServerTime; friend class BroadcastTimeServerSync; friend class BroadcastTimeServerSet; friend class BroadcastTimeServerAlarm; DISALLOW_COPY_AND_ASSIGN(BroadcastTimeServer); }; } // namespace openlcb #endif // _OPENLCB_BROADCASTTIMESERVER_HXX_
36.388601
80
0.666239
rilull
6ecec92a9c7711fcf34c52832bfc14d728f42dfb
1,379
cpp
C++
codeforces/q3.cpp
nancyanand2807/algorithm-ds
9f79bd9a37bdf858a512ded44aa33040e8a7b9af
[ "MIT" ]
5
2020-10-01T13:08:35.000Z
2021-02-01T17:51:15.000Z
codeforces/q3.cpp
nancyanand2807/algorithm-ds
9f79bd9a37bdf858a512ded44aa33040e8a7b9af
[ "MIT" ]
21
2020-10-01T12:58:05.000Z
2020-10-07T11:58:30.000Z
codeforces/q3.cpp
sansyrox/summer_of_cpp
e07acee254e25febe5b11bc1adc743f5aaf57cc8
[ "MIT" ]
23
2020-10-01T12:59:06.000Z
2020-10-15T13:08:34.000Z
#include<iostream> #include<bits/stdc++.h> using namespace std; #define ll long long #define mp make_pair #define pb push_back bool isSorted(vector<ll> a){ for(ll i=0 ; i<a.size()-1; i++){ if(a[i]<=a[i+1]){ return false; } } return true; } ll dp[1000001]; ll returnMinSteps(vector<ll> stack, vector<ll> hand, ll i, ll n ){ if(i>(n<<1)){ return 1e9; } if(isSorted(stack)){ return dp[i]=0; } if(dp[i]!=-1 and i<1000001) return dp[i]; ll minStep=1e9; for(int x=0; x<n; x++){ ll t = hand[x]; stack.pb(t); hand[x] = stack.front(); stack.erase(stack.begin()); // cout<<"Stack\n"; // for(auto j:stack){ // cout<<j<<" "; // } // cout<<endl; // cout<<"Hand\n"; // for(auto j:hand){ // cout<<j<<" "; // } // cout<<endl; minStep=min( minStep, 1+returnMinSteps(stack,hand,i+1,n) ); } return dp[i]=minStep; } int main() { ll n; cin>>n; vector<ll> stack,hand; for(ll i=0; i<n; i++){ ll t; cin>>t; hand.pb(t); } for(ll i=0; i<n; i++){ ll t; cin>>t; stack.pb(t); } for(ll i=0; i<1000001; i++) dp[i]=-1; cout<<returnMinSteps(stack,hand,0,n); return 0; }
17.2375
66
0.453227
nancyanand2807
6ecef951df0077854a776b896183a8e547863ea8
4,698
cpp
C++
disc-fe/test/core_tests/hierarchic_team_policy.cpp
hillyuan/Tianxin
57c7a5ed2466dda99471dec41cd85878335774d7
[ "BSD-3-Clause" ]
1
2022-03-22T03:49:50.000Z
2022-03-22T03:49:50.000Z
disc-fe/test/core_tests/hierarchic_team_policy.cpp
hillyuan/Tianxin
57c7a5ed2466dda99471dec41cd85878335774d7
[ "BSD-3-Clause" ]
null
null
null
disc-fe/test/core_tests/hierarchic_team_policy.cpp
hillyuan/Tianxin
57c7a5ed2466dda99471dec41cd85878335774d7
[ "BSD-3-Clause" ]
null
null
null
// @HEADER // *********************************************************************** // // Panzer: A partial differential equation assembly // engine for strongly coupled complex multiphysics systems // Copyright (2011) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Roger P. Pawlowski (rppawlo@sandia.gov) and // Eric C. Cyr (eccyr@sandia.gov) // *********************************************************************** // @HEADER #include <Teuchos_ConfigDefs.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_RCP.hpp> #include "KokkosExp_View_Fad.hpp" #include "Kokkos_DynRankView_Fad.hpp" #include "Panzer_HierarchicParallelism.hpp" #include "Sacado.hpp" namespace panzer_test { const int M = 100; const int N = 16; template<typename Scalar, typename VectorType,typename OutputStream> void checkPolicy(bool use_stream_instance, VectorType& a, VectorType& b, VectorType& c, bool& success, OutputStream& out) { Kokkos::deep_copy(a,0.0); Kokkos::deep_copy(b,1.0); Kokkos::deep_copy(c,2.0); if (use_stream_instance) { PHX::ExecSpace exec_space; auto policy = panzer::HP::inst().teamPolicy<Scalar>(exec_space,M); Kokkos::parallel_for("test 0",policy,KOKKOS_LAMBDA (const Kokkos::TeamPolicy<PHX::ExecSpace>::member_type team){ const int i = team.league_rank(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team,0,N), [&] (const int j) { a(i,j) += b(i,j) + c(i,j); }); }); } else { auto policy = panzer::HP::inst().teamPolicy<Scalar>(M); Kokkos::parallel_for("test 0",policy,KOKKOS_LAMBDA (const Kokkos::TeamPolicy<PHX::ExecSpace>::member_type team){ const int i = team.league_rank(); Kokkos::parallel_for(Kokkos::TeamThreadRange(team,0,N), [&] (const int j) { a(i,j) += b(i,j) + c(i,j); }); }); } Kokkos::fence(); auto a_host = Kokkos::create_mirror_view(a); Kokkos::deep_copy(a_host,a); auto tol = 1000.0 * std::numeric_limits<double>::epsilon(); for (int i=0; i < M; ++i) { for (int j=0; j < N; ++j) { TEST_FLOATING_EQUALITY(Sacado::scalarValue(a_host(i,j)),3.0,tol); } } } TEUCHOS_UNIT_TEST(HierarchicTeamPolicy, StreamsDouble) { using Scalar = double; PHX::View<Scalar**> a("a",M,N); PHX::View<Scalar**> b("b",M,N); PHX::View<Scalar**> c("c",M,N); panzer_test::checkPolicy<Scalar>(false,a,b,c,success,out); // default exec space panzer_test::checkPolicy<Scalar>(true,a,b,c,success,out); // specify exec space } TEUCHOS_UNIT_TEST(HierarchicTeamPolicy, StreamsDFAD) { using Scalar = Sacado::Fad::DFad<double>; const int deriv_dim = 8; PHX::View<Scalar**> a("a",M,N,deriv_dim); PHX::View<Scalar**> b("b",M,N,deriv_dim); PHX::View<Scalar**> c("c",M,N,deriv_dim); panzer_test::checkPolicy<Scalar>(false,a,b,c,success,out); // default exec space panzer_test::checkPolicy<Scalar>(true,a,b,c,success,out); // specify exec space } }
39.15
118
0.66539
hillyuan
6ed1f44350cf62939fb1c539e8c3ded0bc7473ad
5,170
cpp
C++
CC/src/SimpleCloud.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
CC/src/SimpleCloud.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
CC/src/SimpleCloud.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
1
2019-02-03T12:19:42.000Z
2019-02-03T12:19:42.000Z
//########################################################################## //# # //# CCLIB # //# # //# This program is free software; you can redistribute it and/or modify # //# it under the terms of the GNU Library General Public License as # //# published by the Free Software Foundation; version 2 or later of the # //# License. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU General Public License for more details. # //# # //# COPYRIGHT: EDF R&D / TELECOM ParisTech (ENST-TSI) # //# # //########################################################################## #include "ScalarField.h" #include "SimpleCloud.h" using namespace CCLib; SimpleCloud::SimpleCloud() : m_points(nullptr) , m_scalarField(nullptr) , globalIterator(0) , m_validBB(false) { m_scalarField = new ScalarField("Default"); m_scalarField->link(); m_points = new PointsContainer(); m_points->link(); } SimpleCloud::~SimpleCloud() { m_points->release(); m_scalarField->release(); } void SimpleCloud::clear() { m_scalarField->clear(); m_points->clear(); placeIteratorAtBeginning(); m_validBB=false; } unsigned SimpleCloud::size() const { return m_points->currentSize(); } void SimpleCloud::addPoint(const CCVector3 &P) { m_points->addElement(P.u); m_validBB=false; } void SimpleCloud::addPoint(const PointCoordinateType P[]) { m_points->addElement(P); m_validBB=false; } void SimpleCloud::forEach(genericPointAction action) { unsigned n = m_points->currentSize(); if (m_scalarField->currentSize() >= n) //existing scalar field? { for (unsigned i=0; i<n; ++i) { action(*reinterpret_cast<CCVector3*>(m_points->getValue(i)),(*m_scalarField)[i]); } } else //otherwise (we provide a fake zero distance) { ScalarType d = 0; for (unsigned i=0; i<n; ++i) { action(*reinterpret_cast<CCVector3*>(m_points->getValue(i)),d); } } } void SimpleCloud::getBoundingBox(CCVector3& bbMin, CCVector3& bbMax) { if (!m_validBB) { m_points->computeMinAndMax(); m_validBB = true; } bbMin = CCVector3(m_points->getMin()); bbMax = CCVector3(m_points->getMax()); } bool SimpleCloud::reserve(unsigned n) { if (!m_points->reserve(n)) { return false; } if (m_scalarField->capacity() != 0 && !m_scalarField->reserve(n)) { return false; } return true; } bool SimpleCloud::resize(unsigned n) { unsigned oldCount = m_points->capacity(); if (!m_points->resize(n)) { return false; } if (m_scalarField->capacity() > 0 && !m_scalarField->resize(n)) { //revert to previous state m_points->resize(oldCount); return false; } return true; } void SimpleCloud::placeIteratorAtBeginning() { globalIterator = 0; } const CCVector3* SimpleCloud::getNextPoint() { return reinterpret_cast<CCVector3*>(globalIterator < m_points->currentSize() ? m_points->getValue(globalIterator++) : 0); } const CCVector3* SimpleCloud::getPointPersistentPtr(unsigned index) { assert(index < m_points->currentSize()); return reinterpret_cast<CCVector3*>(m_points->getValue(index)); } void SimpleCloud::getPoint(unsigned index, CCVector3& P) const { assert(index < m_points->currentSize()); P = *reinterpret_cast<CCVector3*>(m_points->getValue(index)); } void SimpleCloud::setPointScalarValue(unsigned pointIndex, ScalarType value) { assert(pointIndex<m_scalarField->currentSize()); m_scalarField->setValue(pointIndex,value); } ScalarType SimpleCloud::getPointScalarValue(unsigned pointIndex) const { assert(pointIndex<m_scalarField->currentSize()); return m_scalarField->getValue(pointIndex); } bool SimpleCloud::enableScalarField() { return m_scalarField->resize(m_points->capacity()); } bool SimpleCloud::isScalarFieldEnabled() const { return m_scalarField->isAllocated(); } void SimpleCloud::applyTransformation(PointProjectionTools::Transformation& trans) { unsigned count = m_points->currentSize(); if (fabs(trans.s - 1.0) > ZERO_TOLERANCE) { for (unsigned i=0; i<count; ++i) { CCVector3* P = reinterpret_cast<CCVector3*>(m_points->getValue(i)); (*P) *= trans.s; } m_validBB = false; } if (trans.R.isValid()) { for (unsigned i=0; i<count; ++i) { CCVector3* P = reinterpret_cast<CCVector3*>(m_points->getValue(i)); (*P) = trans.R * (*P); m_validBB = false; } } if (trans.T.norm() > ZERO_TOLERANCE) { for (unsigned i=0; i<count; ++i) { CCVector3* P = reinterpret_cast<CCVector3*>(m_points->getValue(i)); (*P) += trans.T; } m_validBB = false; } }
24.619048
122
0.603868
ohanlonl
6ed597585b57b3f6aa2ef5cf5a724d1b1a8ff6fa
1,726
cpp
C++
ulpc/d_admf/src/CpConfigAsCSV.cpp
nikhilc149/e-utran-features-bug-fixes
4e9d08b54c9181e9790208556ddd716907f7d3d9
[ "Apache-2.0" ]
null
null
null
ulpc/d_admf/src/CpConfigAsCSV.cpp
nikhilc149/e-utran-features-bug-fixes
4e9d08b54c9181e9790208556ddd716907f7d3d9
[ "Apache-2.0" ]
null
null
null
ulpc/d_admf/src/CpConfigAsCSV.cpp
nikhilc149/e-utran-features-bug-fixes
4e9d08b54c9181e9790208556ddd716907f7d3d9
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020 Sprint * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CpConfigAsCSV.h" CpConfigAsCSV::CpConfigAsCSV() { } CpConfigAsCSV::CpConfigAsCSV(const std::string &strPath) : strCSVPath(strPath) { ReadCpConfig(); } CpConfigAsCSV::~CpConfigAsCSV() { } int8_t CpConfigAsCSV::ReadCpConfig(void) { std::string strLine; std::ifstream ifsCpFile(strCSVPath); if (ifsCpFile.is_open()) { while (getline(ifsCpFile, strLine)) { vecCpConfig.push_back(strLine); } ifsCpFile.close(); } else return RET_FAILURE; return RET_SUCCESS; } int8_t CpConfigAsCSV::UpdateCpConfig(uint8_t uiAction, const std::string &strIpAddr) { if (ADD_ACTION == uiAction) { std::ofstream ofsCpFile(strCSVPath, std::ios::app); if (ofsCpFile.is_open()) { ofsCpFile << strIpAddr << std::endl; ofsCpFile.close(); } else return RET_FAILURE; } #if 0 } else if (UPDATE_ACTION == uiAction) { std::fstream fs; std::string strLine; fs.open(strCSVPath, std::ios::out | std::ios::in); if (fs.is_open()) { while (getline(fs, strLine)) { if (strLine == strIpAddr) { } } fs.close(); } else if (DELETE_ACTION == uiAction) { } #endif return RET_SUCCESS; }
19.613636
78
0.692932
nikhilc149
6ed5dac18f95e4fc1b05d6033551c0a321ff404f
2,047
cpp
C++
ReferenceDesign/SampleQTHMI/HMIWidgets/CRotationWidget.cpp
zenghuan1/HMI_SDK_LIB
d0d03af04abe07f5ca087cabcbb1e4f4858f266a
[ "BSD-3-Clause" ]
8
2019-01-04T10:08:39.000Z
2021-12-13T16:34:08.000Z
ReferenceDesign/SampleQTHMI/HMIWidgets/CRotationWidget.cpp
zenghuan1/HMI_SDK_LIB
d0d03af04abe07f5ca087cabcbb1e4f4858f266a
[ "BSD-3-Clause" ]
33
2017-07-27T09:51:59.000Z
2018-07-13T09:45:52.000Z
ReferenceDesign/SampleQTHMI/HMIWidgets/CRotationWidget.cpp
JH-G/HMI_SDK_LIB
caa4eac66d1f3b76349ef5d6ca5cf7dd69fcd760
[ "BSD-3-Clause" ]
12
2017-07-28T02:54:53.000Z
2022-02-20T15:48:24.000Z
#include "CRotationWidget.h" #include "HMIFrameWork/log_interface.h" CRotationWidget::CRotationWidget(QWidget *parent) :QLabel(parent) ,m_timer(NULL) ,m_bRotationStarted(false) ,m_nRotationAngle(0) ,m_image() ,m_eDirection(DEFAULT_DIRECTION) { m_timer = new QTimer(this); connect(m_timer, SIGNAL(timeout()), this, SLOT(onRatateTimeout()), Qt::UniqueConnection); this->hide(); } CRotationWidget::~CRotationWidget() { if (!m_timer) delete m_timer; } void CRotationWidget::setPixmap(const QString &path) { this->setPixmap(QPixmap(path)); } void CRotationWidget::setPixmap(const QPixmap &pixmap) { m_image = pixmap; } void CRotationWidget::start() { INFO("CRotationWidget::start"); if (!m_timer->isActive()) { m_bRotationStarted = true; // show(); m_timer->start(100); onRatateTimeout(); } } void CRotationWidget::stop() { INFO("CRotationWidget::stop()"); if (m_timer->isActive()) { m_timer->stop(); } // hide(); m_bRotationStarted = false; m_nRotationAngle = 0; } void CRotationWidget::setRotateDirection(CRotationWidget::eRotateDirection direction) { m_eDirection = direction; } void CRotationWidget::paintEvent(QPaintEvent *event) { if (m_bRotationStarted && !m_image.isNull()) { QPainter painter(this); painter.setRenderHint(QPainter::SmoothPixmapTransform); qreal x = m_image.width()/2; qreal y = m_image.height()/2; painter.translate(x, y); painter.rotate(m_nRotationDegree); painter.translate(-x, -y); painter.drawPixmap(0, 0, m_image.width(), m_image.height(), m_image); } else { QLabel::paintEvent(event); } } void CRotationWidget::onRatateTimeout() { if(ROTATE_CLOCKWISE == m_eDirection) { ++m_nRotationAngle; } else { --m_nRotationAngle; } m_nRotationAngle = m_nRotationAngle % 36; m_nRotationDegree = 10 * m_nRotationAngle; update(); }
20.676768
93
0.640938
zenghuan1
6ee132057013d5c465a17e529ad6c61eb84f7ba1
6,627
hh
C++
benchmark/Voter_bench.hh
yishayahu/sto_real
8c7672e1d89727c147a884a9fc9c43f26590bd68
[ "MIT" ]
null
null
null
benchmark/Voter_bench.hh
yishayahu/sto_real
8c7672e1d89727c147a884a9fc9c43f26590bd68
[ "MIT" ]
null
null
null
benchmark/Voter_bench.hh
yishayahu/sto_real
8c7672e1d89727c147a884a9fc9c43f26590bd68
[ "MIT" ]
null
null
null
#pragma once #include <iomanip> #include <PlatformFeatures.hh> #include "sampling.hh" #include "Voter_structs.hh" #include "DB_index.hh" #include "DB_params.hh" #include "DB_hot_oindex.hh" namespace voter { struct constants { static constexpr int num_contestants = 6; static constexpr int64_t max_votes_per_phone_number = 1000; }; template<typename DBParams> class voter_db { public: //for masstree change to true template<typename K, typename V> using OIndex = typename std::conditional<false, bench::ordered_index<K, V, DBParams>, bench::hot_ordered_index<K, V, DBParams>>::type; typedef OIndex<contestant_key, contestant_row> contestant_tbl_type; typedef OIndex<area_code_state_key, area_code_state_row> areacodestate_tbl_type; typedef OIndex<votes_key, votes_row> votes_tbl_type; typedef OIndex<v_votes_phone_key, v_votes_phone_row> v_votesphone_idx_type; typedef OIndex<v_votes_id_state_key, v_votes_id_state_row> v_votesidst_idx_type; explicit voter_db() : tbl_contestant_(), tbl_areacodestate_(), tbl_votes_(), idx_votesphone_(), idx_votesidst_() {} contestant_tbl_type& tbl_contestant() { return tbl_contestant_; } areacodestate_tbl_type& tbl_areacode_state() { return tbl_areacodestate_; } votes_tbl_type& tbl_votes() { return tbl_votes_; } v_votesphone_idx_type& view_votes_by_phone() { return idx_votesphone_; } v_votesidst_idx_type& view_votes_by_id_state() { return idx_votesidst_; } void thread_init_all() { tbl_contestant_.thread_init(); tbl_areacodestate_.thread_init(); tbl_votes_.thread_init(); idx_votesphone_.thread_init(); idx_votesidst_.thread_init(); } private: contestant_tbl_type tbl_contestant_; areacodestate_tbl_type tbl_areacodestate_; votes_tbl_type tbl_votes_; v_votesphone_idx_type idx_votesphone_; v_votesidst_idx_type idx_votesidst_; }; extern std::vector<std::string> area_codes; extern std::vector<std::string> area_code_state_map; extern std::vector<std::string> contestant_names; extern void initialize_data(); typedef typename sampling::StoRandomDistribution<>::rng_type rng_type; struct basic_dists { rng_type thread_rng; std::uniform_int_distribution<size_t> area_code_id_dist; std::uniform_int_distribution<int32_t> contestant_num_dist; std::uniform_int_distribution<uint32_t> phone_num_dist; std::uniform_int_distribution<int> coin_flip; std::uniform_int_distribution<int> percent_sampler; explicit basic_dists(int seed) : thread_rng(seed), area_code_id_dist(0ul, area_codes.size() - 1ul), contestant_num_dist(1, constants::num_contestants), phone_num_dist(0u, 9999999u), coin_flip(0, 1), percent_sampler(0, 99) {} }; class input_generator { public: explicit input_generator(int rng_seed) : dists(rng_seed) { constexpr int num_conts = constants::num_contestants; for(size_t i = 0; i < area_codes.size(); ++i) { int32_t contestant_choice = 1; if (dists.percent_sampler(dists.thread_rng) < 30) { contestant_choice = (std::abs((int)(std::sin((double)i) * num_conts)) % num_conts) + 1; } contestant_heat_map.push_back(contestant_choice); } } // returns contestant number + phone number std::pair<int32_t, phone_number_str> generate_phone_call() { phone_number_str tel; std::stringstream ss; auto idx = dists.area_code_id_dist(dists.thread_rng); int32_t contestant_n = contestant_heat_map[idx]; if (dists.coin_flip(dists.thread_rng) == 0) { contestant_n = dists.contestant_num_dist(dists.thread_rng); } if (dists.percent_sampler(dists.thread_rng) == 0) { contestant_n = 999; } tel.area_code = area_codes[idx]; ss << std::setw(7) << std::setfill('0') << dists.phone_num_dist(dists.thread_rng); tel.number = ss.str(); return {contestant_n, tel}; } private: basic_dists dists; std::vector<int32_t> contestant_heat_map; }; template <typename DBParams> class voter_runner { public: typedef voter_db<DBParams> db_type; explicit voter_runner(int rid, db_type& database, double time_limit) : id(rid), db(database), ig(rid+1040), tsc_elapse_limit(), stat_committed_txns() { tsc_elapse_limit = static_cast<uint64_t>(time_limit * db_params::constants::processor_tsc_frequency * db_params::constants::billion); } void run(); size_t committed_txns() const { return stat_committed_txns; } private: void run_txn_vote(const phone_number_str& tel, int32_t contestant_number); bool vote_inner(const phone_number_str& tel, int32_t contestant_number); int id; db_type& db; input_generator ig; uint64_t tsc_elapse_limit; size_t stat_committed_txns; }; template <typename DBParams> class voter_loader { public: typedef voter_db<DBParams> db_type; explicit voter_loader(db_type& database) : db(database) {} void load() { std::cout << "Loading..." << std::endl; always_assert(!area_codes.empty()); always_assert(area_codes.size() == area_code_state_map.size()); for (int i = 0; i < constants::num_contestants; ++i) { contestant_key ck(i); contestant_row cr; cr.name = contestant_names[i]; db.tbl_contestant().nontrans_put(ck, cr); } for (size_t i = 0; i < area_codes.size(); ++i) { area_code_state_key acs_k(area_codes[i]); area_code_state_row acs_r; acs_r.state = area_code_state_map[i]; db.tbl_areacode_state().nontrans_put(acs_k, acs_r); } std::cout << "Loaded." << std::endl; } private: db_type& db; }; template <typename DBParams> void voter_runner<DBParams>::run() { ::TThread::set_id(id); set_affinity(id); db.thread_init_all(); size_t cnt = 0; auto begin_tsc = read_tsc(); while (true) { int32_t cn; phone_number_str tel; std::tie(cn, tel) = ig.generate_phone_call(); run_txn_vote(tel, cn); ++cnt; if (((cnt & 0xfffu) == 0) && ((read_tsc() - begin_tsc) >= tsc_elapse_limit)) break; } stat_committed_txns = cnt; } }; // namespace voter
29.717489
103
0.657311
yishayahu
6ee4155f94aa419d2661aa5536bd2ced2d547e35
191
cpp
C++
src/World/Chunk/ChunkSection.cpp
leiapollos/game-engine-cgj-2019-2020
c23f930f9f814a6d796645aa4c994f8d4a69b7c0
[ "MIT" ]
null
null
null
src/World/Chunk/ChunkSection.cpp
leiapollos/game-engine-cgj-2019-2020
c23f930f9f814a6d796645aa4c994f8d4a69b7c0
[ "MIT" ]
null
null
null
src/World/Chunk/ChunkSection.cpp
leiapollos/game-engine-cgj-2019-2020
c23f930f9f814a6d796645aa4c994f8d4a69b7c0
[ "MIT" ]
null
null
null
/*#include "ChunkSection.h" ChunkSection::ChunkSection(World& world): m_pWorld(world) {} Chunk* getChunkBlock(int x, int y, int z) { return &world.getChunkManager().getChunk(x,y,z); }*/
27.285714
60
0.701571
leiapollos
6eed985e5d3d34fde22e722ea244e5204dd2f8d2
8,138
hpp
C++
iiop/include/morbid/iiop/meta_compiler.hpp
felipealmeida/mORBid
3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b
[ "BSL-1.0" ]
2
2018-01-31T07:06:23.000Z
2021-02-18T00:49:05.000Z
iiop/include/morbid/iiop/meta_compiler.hpp
felipealmeida/mORBid
3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b
[ "BSL-1.0" ]
null
null
null
iiop/include/morbid/iiop/meta_compiler.hpp
felipealmeida/mORBid
3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b
[ "BSL-1.0" ]
null
null
null
/* (c) Copyright 2012 Felipe Magno de Almeida * * Distributed under the Boost Software License, Version 1.0. (See * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #ifndef MORBID_IIOP_META_COMPILER_HPP #define MORBID_IIOP_META_COMPILER_HPP #include <morbid/iiop/domain.hpp> #include <morbid/giop/common_terminals.hpp> #include <morbid/giop/compile.hpp> #include <boost/spirit/home/karma.hpp> #include <boost/spirit/home/qi.hpp> #include <boost/spirit/home/phoenix.hpp> namespace morbid { namespace iiop { namespace generator { template <typename Tag, typename Modifiers, typename Enable = void> struct make_primitive; template <typename Tag, typename Elements , typename Modifiers, typename Enable = void> struct make_composite; template <typename Directive, typename Body , typename Modifiers, typename Enable = void> struct make_directive; } namespace parser { template <typename Tag, typename Modifiers, typename Enable = void> struct make_primitive; template <typename Tag, typename Elements , typename Modifiers, typename Enable = void> struct make_composite; template <typename Directive, typename Body , typename Modifiers, typename Enable = void> struct make_directive; } } } namespace boost { namespace spirit { template <> struct make_component< ::morbid::iiop::generator_domain, proto::tag::terminal> { template <typename Sig> struct result; template <typename This, typename Elements, typename Modifiers> struct result<This(Elements, Modifiers)> { typedef typename ::morbid::iiop::generator::make_primitive< typename remove_const<typename Elements::car_type>::type , typename remove_reference<Modifiers>::type >::result_type type; }; template <typename Elements, typename Modifiers> typename result<make_component(Elements, Modifiers)>::type operator()(Elements const& elements, Modifiers const& modifiers) const { typedef typename remove_const<typename Elements::car_type>::type term; return ::morbid::iiop::generator::make_primitive<term, Modifiers>()(elements.car, modifiers); } }; template <typename Tag> struct make_component< ::morbid::iiop::generator_domain, Tag> { template <typename Sig> struct result; template <typename This, typename Elements, typename Modifiers> struct result<This(Elements, Modifiers)> { typedef typename ::morbid::iiop::generator::make_composite<Tag, Elements , typename remove_reference<Modifiers>::type>::result_type type; }; template <typename Elements, typename Modifiers> typename result<make_component(Elements, Modifiers)>::type operator()(Elements const& elements, Modifiers const& modifiers) const { return ::morbid::iiop::generator::make_composite<Tag, Elements, Modifiers>()(elements, modifiers); } }; template <> struct make_component< ::morbid::iiop::generator_domain, tag::action> { template <typename Sig> struct result; template <typename This, typename Elements, typename Modifiers> struct result<This(Elements, Modifiers)> { typedef typename boost::remove_const<typename Elements::car_type>::type subject_type; typedef typename boost::remove_const<typename Elements::cdr_type::car_type>::type action_type; typedef karma::action<subject_type, action_type> type; }; template <typename Elements> typename result<make_component(Elements, unused_type)>::type operator()(Elements const& elements, unused_type) const { typename result<make_component(Elements, unused_type)>::type result(elements.car, elements.cdr.car); return result; } }; template <> struct make_component< ::morbid::iiop::generator_domain, tag::directive> { template <typename Sig> struct result; template <typename This, typename Elements, typename Modifiers> struct result<This(Elements, Modifiers)> { typedef typename ::morbid::iiop::generator::make_directive< typename boost::remove_const<typename Elements::car_type>::type, typename boost::remove_const<typename Elements::cdr_type::car_type>::type, typename boost::remove_reference<Modifiers>::type >::result_type type; }; template <typename Elements, typename Modifiers> typename result<make_component(Elements, Modifiers)>::type operator()(Elements const& elements, Modifiers const& modifiers) const { return ::morbid::iiop::generator::make_directive< typename boost::remove_const<typename Elements::car_type>::type, typename boost::remove_const<typename Elements::cdr_type::car_type>::type, Modifiers>()(elements.car, elements.cdr.car, modifiers); } }; template <> struct make_component< ::morbid::iiop::parser_domain, proto::tag::terminal> { template <typename Sig> struct result; template <typename This, typename Elements, typename Modifiers> struct result<This(Elements, Modifiers)> { typedef typename ::morbid::iiop::parser::make_primitive< typename remove_const<typename Elements::car_type>::type , typename remove_reference<Modifiers>::type >::result_type type; }; template <typename Elements, typename Modifiers> typename result<make_component(Elements, Modifiers)>::type operator()(Elements const& elements, Modifiers const& modifiers) const { typedef typename remove_const<typename Elements::car_type>::type term; return ::morbid::iiop::parser::make_primitive<term, Modifiers>() (elements.car, modifiers); } }; template <typename Tag> struct make_component< ::morbid::iiop::parser_domain, Tag> { template <typename Sig> struct result; template <typename This, typename Elements, typename Modifiers> struct result<This(Elements, Modifiers)> { typedef typename ::morbid::iiop::parser::make_composite <Tag, Elements, typename remove_reference<Modifiers>::type>::result_type type; }; template <typename Elements, typename Modifiers> typename result<make_component(Elements, Modifiers)>::type operator()(Elements const& elements, Modifiers const& modifiers) const { return ::morbid::iiop::parser::make_composite<Tag, Elements, Modifiers>() (elements, modifiers); } }; template <> struct make_component< ::morbid::iiop::parser_domain, tag::action> { template <typename Sig> struct result; template <typename This, typename Elements, typename Modifiers> struct result<This(Elements, Modifiers)> { typedef typename boost::remove_const<typename Elements::car_type>::type subject_type; typedef typename boost::remove_const<typename Elements::cdr_type::car_type>::type action_type; typedef karma::action<subject_type, action_type> type; }; template <typename Elements> typename result<make_component(Elements, unused_type)>::type operator()(Elements const& elements, unused_type) const { typename result<make_component(Elements, unused_type)>::type result(elements.car, elements.cdr.car); return result; } }; template <> struct make_component< ::morbid::iiop::parser_domain, tag::directive> { template <typename Sig> struct result; template <typename This, typename Elements, typename Modifiers> struct result<This(Elements, Modifiers)> { typedef typename ::morbid::iiop::parser::make_directive< typename boost::remove_const<typename Elements::car_type>::type, typename boost::remove_const<typename Elements::cdr_type::car_type>::type, typename boost::remove_reference<Modifiers>::type >::result_type type; }; template <typename Elements, typename Modifiers> typename result<make_component(Elements, Modifiers)>::type operator()(Elements const& elements, Modifiers const& modifiers) const { return ::morbid::iiop::parser::make_directive< typename boost::remove_const<typename Elements::car_type>::type, typename boost::remove_const<typename Elements::cdr_type::car_type>::type, Modifiers>()(elements.car, elements.cdr.car, modifiers); } }; } } namespace morbid { namespace iiop { } } #endif
29.064286
102
0.729786
felipealmeida
6ef2f5bd54309474f7104d077b418397e901be63
320
cpp
C++
CPP, C++ Solutions/1047. Remove All Adjacent Duplicates In String.cpp
arpitkekri/My-Leetcode-Solution-In-CPP
345f1c53c627fce33ee84672c5d3661863367040
[ "MIT" ]
4
2021-06-21T04:32:12.000Z
2021-11-02T04:20:36.000Z
CPP, C++ Solutions/1047. Remove All Adjacent Duplicates In String.cpp
arpitkekri/My-Leetcode-Solution-In-CPP
345f1c53c627fce33ee84672c5d3661863367040
[ "MIT" ]
null
null
null
CPP, C++ Solutions/1047. Remove All Adjacent Duplicates In String.cpp
arpitkekri/My-Leetcode-Solution-In-CPP
345f1c53c627fce33ee84672c5d3661863367040
[ "MIT" ]
2
2021-08-19T11:27:18.000Z
2021-09-26T14:51:30.000Z
// TC - O(n) // SC - O(n) class Solution { public: string removeDuplicates(string s) { int n = s.size(); string ans = ""; for(int i = 0; i < n; i++) { if(ans.size() && ans.back() == s[i]) ans.pop_back(); else ans.push_back(s[i]); } return ans; } };
22.857143
64
0.440625
arpitkekri
6ef5286e1312e89f2f92cfa1b65593526d1412cf
1,808
hpp
C++
mutex_proxy.hpp
hmito/hmLib
0f2515ba9c99c06d02e2fa633eeae73bcd793983
[ "MIT" ]
null
null
null
mutex_proxy.hpp
hmito/hmLib
0f2515ba9c99c06d02e2fa633eeae73bcd793983
[ "MIT" ]
null
null
null
mutex_proxy.hpp
hmito/hmLib
0f2515ba9c99c06d02e2fa633eeae73bcd793983
[ "MIT" ]
1
2015-09-22T03:32:11.000Z
2015-09-22T03:32:11.000Z
#ifndef HMLIB_MUTEXPROXY_INC #define HMLIB_MUTEXPROXY_INC 102 # /*===mutex_proxy=== 汎用Mutexを受け取って代理的に機能する mutex_proxy v1_02/130420 hmIto 空リファレンスを許容するように修正 mutex_proxy v1_01/130412 hmIto try_lockがtry_lockiとなっていた致命的な問題を修正 mutex_proxy:v1_00/130308 hmIto 汎用mutex参照クラス、mutex_proxyを追加 */ #include<functional> #include"exceptions.hpp" namespace hmLib{ class mutex_proxy{ public: typedef exceptions::exception_pattern<mutex_proxy> exception; private: bool Active; std::function<void(void)> FnLock; std::function<void(void)> FnUnlock; std::function<bool(void)> FnTryLock; private: mutex_proxy(const mutex_proxy& My_); const mutex_proxy& operator=(const mutex_proxy& My_); public: mutex_proxy():Active(false){} mutex_proxy(mutex_proxy&& My_):Active(false){ std::swap(Active,My_.Active); std::swap(FnLock,My_.FnLock); std::swap(FnUnlock,My_.FnUnlock); std::swap(FnTryLock,My_.FnTryLock); } const mutex_proxy& operator=(mutex_proxy&& My_){ std::swap(Active,My_.Active); std::swap(FnLock,My_.FnLock); std::swap(FnUnlock,My_.FnUnlock); std::swap(FnTryLock,My_.FnTryLock); return *this; } template<typename mutex_> mutex_proxy(mutex_& Mx_) :Active(true) ,FnLock(std::bind(std::mem_fn(&mutex_::lock),std::ref(Mx_))) ,FnUnlock(std::bind(std::mem_fn(&mutex_::unlock),std::ref(Mx_))) ,FnTryLock(std::bind(std::mem_fn(&mutex_::try_lock),std::ref(Mx_))){ } public: bool is_proxy()const{return Active;} public: void lock(){ hmLib_assert(Active, exception, "mutex_proxy have no reference"); FnLock(); } void unlock(){ hmLib_assert(Active, exception, "mutex_proxy have no reference"); FnUnlock(); } bool try_lock(){ hmLib_assert(Active, exception, "mutex_proxy have no reference"); return FnTryLock(); } }; } # #endif
26.202899
71
0.722345
hmito
6ef583ceea04e6f511954bc1c2c6ae4b87d3f7a8
1,878
hh
C++
CosmicRayShieldGeom/inc/CRSScintillatorModuleId.hh
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
1
2021-06-23T22:09:28.000Z
2021-06-23T22:09:28.000Z
CosmicRayShieldGeom/inc/CRSScintillatorModuleId.hh
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
125
2020-04-03T13:44:30.000Z
2021-10-15T21:29:57.000Z
CosmicRayShieldGeom/inc/CRSScintillatorModuleId.hh
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
null
null
null
#ifndef CosmicRayShieldGeom_CRSScintillatorModuleId_hh #define CosmicRayShieldGeom_CRSScintillatorModuleId_hh // // Identifier of one module in CosmicRayShield // // // // Original author KLG; based on Rob Kutschke's SectorId // #include <ostream> #include "CosmicRayShieldGeom/inc/CRSScintillatorShieldId.hh" namespace mu2e { class CRSScintillatorModuleId { friend class CRSScintillatorLayerId; friend class CRSScintillatorBarId; public: CRSScintillatorModuleId(): _shieldId(CRSScintillatorShieldId(-1)), _moduleNumber(-1) { } /* CRSScintillatorModuleId( CRSScintillatorShieldId shieldId, int moduleNumber): _shieldId(shieldId), _moduleNumber(moduleNumber) { } */ CRSScintillatorModuleId( int shieldNumber, int moduleNumber): _shieldId(CRSScintillatorShieldId(shieldNumber)), _moduleNumber(moduleNumber) { } // Compiler generated d'tor, copy and assignment constructors // should be OK. const CRSScintillatorShieldId getShieldId() const {return _shieldId;} const int getShieldNumber() const {return _shieldId;} const int getModuleNumber() const {return _moduleNumber;} bool operator==(CRSScintillatorModuleId const & rhs) const { return ( _shieldId == rhs._shieldId && _moduleNumber == rhs._moduleNumber ); } bool operator!=(CRSScintillatorModuleId const & rhs) const { return !( *this == rhs); } private: CRSScintillatorShieldId _shieldId; int _moduleNumber; }; inline std::ostream& operator<<(std::ostream& ost, const CRSScintillatorModuleId& moduleId ) { ost << moduleId.getShieldId() << " " << moduleId.getModuleNumber(); return ost; } } //namespace mu2e #endif /* CosmicRayShieldGeom_CRSScintillatorModuleId_hh */
22.902439
94
0.685836
lborrel
6ef77a0f98c6d81b705465b60ebeba208e0717b1
2,215
hpp
C++
DataSpec/DNAMP2/CINF.hpp
RetroView/RetroCommon
a413a010b50a53ebc6b0c726203181fc179d3370
[ "MIT" ]
106
2021-04-09T19:42:56.000Z
2022-03-30T09:13:28.000Z
DataSpec/DNAMP2/CINF.hpp
Austint30/metaforce
a491e2e9f229c8db92544b275cd1baa80bacfd17
[ "MIT" ]
58
2021-04-09T12:48:58.000Z
2022-03-22T00:11:42.000Z
DataSpec/DNAMP2/CINF.hpp
Austint30/metaforce
a491e2e9f229c8db92544b275cd1baa80bacfd17
[ "MIT" ]
13
2021-04-06T23:23:20.000Z
2022-03-16T02:09:48.000Z
#pragma once #include "DataSpec/DNACommon/DNACommon.hpp" #include "DataSpec/DNACommon/RigInverter.hpp" #include "DNAMP2.hpp" namespace DataSpec::DNAMP2 { struct CINF : BigDNA { AT_DECL_DNA Value<atUint32> boneCount; struct Bone : BigDNA { AT_DECL_DNA Value<atUint32> id; Value<atUint32> parentId; Value<atVec3f> origin; Value<atVec4f> q1; Value<atVec4f> q2; Value<atUint32> linkedCount; Vector<atUint32, AT_DNA_COUNT(linkedCount)> linked; }; Vector<Bone, AT_DNA_COUNT(boneCount)> bones; Value<atUint32> boneIdCount; Vector<atUint32, AT_DNA_COUNT(boneIdCount)> boneIds; Value<atUint32> nameCount; struct Name : BigDNA { AT_DECL_DNA String<-1> name; Value<atUint32> boneId; }; Vector<Name, AT_DNA_COUNT(nameCount)> names; atUint32 getInternalBoneIdxFromId(atUint32 id) const; atUint32 getBoneIdxFromId(atUint32 id) const; const std::string* getBoneNameFromId(atUint32 id) const; void sendVertexGroupsToBlender(hecl::blender::PyOutStream& os) const; template <class PAKBridge> void sendCINFToBlender(hecl::blender::PyOutStream& os, const typename PAKBridge::PAKType::IDType& cinfId) const; template <class UniqueID> static std::string GetCINFArmatureName(const UniqueID& cinfId); CINF() = default; using Armature = hecl::blender::Armature; using BlenderBone = hecl::blender::Bone; int RecursiveAddArmatureBone(const Armature& armature, const BlenderBone* bone, int parent, int& curId, std::unordered_map<std::string, atInt32>& idMap, std::map<std::string, int>& nameMap); CINF(const Armature& armature, std::unordered_map<std::string, atInt32>& idMap); template <class PAKBridge> static bool Extract(const SpecBase& dataSpec, PAKEntryReadStream& rs, const hecl::ProjectPath& outPath, PAKRouter<PAKBridge>& pakRouter, const typename PAKBridge::PAKType::Entry& entry, bool force, hecl::blender::Token& btok, std::function<void(const char*)> fileChanged); static bool Cook(const hecl::ProjectPath& outPath, const hecl::ProjectPath& inPath, const hecl::blender::Armature& armature); }; } // namespace DataSpec::DNAMP2
35.15873
117
0.716027
RetroView
6ef93e6d4ba32714e5698ca06eabe43f62c25beb
3,843
cpp
C++
Arduino/Libraries/MenloPlatform/MenloPlatformArm.cpp
menloparkinnovation/openpux
d6c45124343675e2d6be60e968b763ea975b7b80
[ "Apache-2.0" ]
3
2016-01-04T16:17:00.000Z
2019-12-24T14:09:58.000Z
Arduino/Libraries/MenloPlatform/MenloPlatformArm.cpp
menloparkinnovation/openpux
d6c45124343675e2d6be60e968b763ea975b7b80
[ "Apache-2.0" ]
null
null
null
Arduino/Libraries/MenloPlatform/MenloPlatformArm.cpp
menloparkinnovation/openpux
d6c45124343675e2d6be60e968b763ea975b7b80
[ "Apache-2.0" ]
2
2019-09-27T04:42:42.000Z
2019-12-24T14:10:00.000Z
/* * Copyright (C) 2015 Menlo Park Innovation LLC * * This is licensed software, all rights as to the software * is reserved by Menlo Park Innovation LLC. * * A license included with the distribution provides certain limited * rights to a given distribution of the work. * * This distribution includes a copy of the license agreement and must be * provided along with any further distribution or copy thereof. * * If this license is missing, or you wish to license under different * terms please contact: * * menloparkinnovation.com * menloparkinnovation@gmail.com */ /* * Date: 05/09/2015 * * Platform support for ARM32. * */ #include "MenloPlatform.h" #if MENLO_ARM32 #if MENLO_BOARD_SPARKCORE void EnableWatchdog() { } void ResetWatchdog() { } #else void EnableWatchdog() { } void ResetWatchdog() { } #endif // MENLO_BOARD_SPARKCORE char* MenloPlatform::GetStringPointerFromStringArray(char** array, int index) { // Uniform 32 bit address space, even if strings are in readonly memory return array[index]; } unsigned long MenloPlatform::GetMethodPointerFromMethodArray(char** array, int index) { // // Uniform 32 bit address space, even if strings are in readonly memory // Function pointers == char* // // // Note: C++ Method pointers declared as the following allocate // (2) pointer sized entries. The first is the 32 bit function // address, while the second is a compiler specific encoding for // the type of method. Since these are straightforward non-virtual // methods this information is all 0's for the current version of GCC // for ARM/Arduino. // // As a result every other 32 bit entry must be skipped. // // typedef int (DweetRadio::*StateMethod)(char* buf, int size, bool isSet); // // PROGMEM const StateMethod radio_function_table[] = // { // &DweetRadio::ChannelHandler, // &DweetRadio::TxAddrHandler, // &DweetRadio::RxAddrHandler, // &DweetRadio::PowerHandler, // &DweetRadio::OptionsHandler, // &DweetRadio::GatewayHandler // }; // // 00085300 <_ZL20radio_function_table>: // 85300: 000825a7 00000000 000825b3 00000000 .%.......%...... // 85310: 000825bf 00000000 000825cb 00000000 .%.......%...... // 85320: 000825d7 00000000 000825e3 00000000 .%.......%...... // 85330: 000826b1 00000000 .&...... // // Multiply index by 2 to skip the NULL entries return (unsigned long)array[index*2]; } #if !defined(IMPLEMENTS_EEPROM_ROUTINES) // // EEPROM emulation // // Note: This differs for each ARM processor // #if MENLO_BOARD_SPARKCORE uint8_t eeprom_read_byte(const uint8_t* index) { return EEPROM.read((int)index); } void eeprom_write_byte(const uint8_t* index, uint8_t value) { // // update is used instead of write since it reads the location // and avoids the write if the value matches. // // Better for wear leveling. // EEPROM.update((int)index, value); } #else // // Basic implementation for runtime store/retrieval. // // ARM versions have plenty of RAM for the emulation array // // Note: This is zero init static uint8_t eeprom_emulation[1024] = { 0 }; uint8_t eeprom_read_byte(const uint8_t* index) { return eeprom_emulation[(int)index]; } void eeprom_write_byte(const uint8_t* index, uint8_t value) { eeprom_emulation[(int)index] = value; } #endif // EEPROM emulation #endif // MENLO_BOARD_SPARKCORE #if REQUIRES_PGM_ROUTINES uint16_t pgm_read_word(const int* ptr) { const uint16_t* p = (const uint16_t*)ptr; return *p; } // // Address is to a pointer word in memory // void* pgm_read_ptr(const int* ptr) { char** p = (char**)ptr; return *p; } #endif // PGM emulation #endif // MENLO_ARM32
21.711864
79
0.672652
menloparkinnovation
6efa1ddbc8bd8012c9c82697dec646d20884d9be
1,535
cpp
C++
src/iotjs_module_constants.cpp
chivalry02/iotjs
a7007b88120a020c5ece835811cec9ded48f9f2b
[ "Apache-2.0" ]
null
null
null
src/iotjs_module_constants.cpp
chivalry02/iotjs
a7007b88120a020c5ece835811cec9ded48f9f2b
[ "Apache-2.0" ]
null
null
null
src/iotjs_module_constants.cpp
chivalry02/iotjs
a7007b88120a020c5ece835811cec9ded48f9f2b
[ "Apache-2.0" ]
1
2021-01-16T18:15:34.000Z
2021-01-16T18:15:34.000Z
/* Copyright 2015 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "uv.h" #include "iotjs_module.h" #include "iotjs_module_constants.h" namespace iotjs { #define SET_CONSTANT(object, constant) \ do { \ JObject value(constant); \ object->SetProperty(#constant, value); \ } while (0) JObject* InitConstants() { Module* module = GetBuiltinModule(MODULE_CONSTANTS); JObject* constants = module->module; if (constants == NULL) { constants = new JObject(); SET_CONSTANT(constants, O_APPEND); SET_CONSTANT(constants, O_CREAT); SET_CONSTANT(constants, O_EXCL); SET_CONSTANT(constants, O_RDONLY); SET_CONSTANT(constants, O_RDWR); SET_CONSTANT(constants, O_SYNC); SET_CONSTANT(constants, O_TRUNC); SET_CONSTANT(constants, O_WRONLY); SET_CONSTANT(constants, S_IFMT); SET_CONSTANT(constants, S_IFDIR); SET_CONSTANT(constants, S_IFREG); module->module = constants; } return constants; } } // namespace iotjs
25.583333
75
0.715961
chivalry02
6efa268fef73fb20f485a5e38aa6e70522c338a2
12,139
cpp
C++
Official Windows Platform Sample/Windows 8.1 desktop samples/[C++]-Windows 8.1 desktop samples/Extract app bundle contents sample/C++/ExtractBundle.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/AppxPackingExtractBundle/cpp/ExtractBundle.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
Samples/AppxPackingExtractBundle/cpp/ExtractBundle.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved // This is a simple application which uses the Appx Bundle APIs to read the // contents of an Appx bundle, and extract its contents to a folder on disk. #include <stdio.h> #include <windows.h> #include <strsafe.h> #include <shlwapi.h> #include <AppxPackaging.h> // For Appx Bundle APIs #include "ExtractBundle.h" // Types of footprint files in a bundle const int FootprintFilesCount = 3; const APPX_BUNDLE_FOOTPRINT_FILE_TYPE FootprintFilesType[FootprintFilesCount] = { APPX_BUNDLE_FOOTPRINT_FILE_TYPE_MANIFEST, APPX_BUNDLE_FOOTPRINT_FILE_TYPE_BLOCKMAP, APPX_BUNDLE_FOOTPRINT_FILE_TYPE_SIGNATURE }; const LPCWSTR FootprintFilesName[FootprintFilesCount] = { L"manifest", L"block map", L"digital signature" }; // // Function to create a writable IStream over a file with the specified name // under the specified path. This function will also create intermediate // subdirectories if necessary. For simplicity, file names including path are // assumed to be 200 characters or less. A real application should be able to // handle longer names and allocate the necessary buffer dynamically. // // Parameters: // path - Path of the folder containing the file to be opened. This should NOT // end with a slash ('\') character. // fileName - Name, not including path, of the file to be opened // stream - Output parameter pointing to the created instance of IStream over // the specified file when this function succeeds. // HRESULT GetOutputStream( _In_ LPCWSTR path, _In_ LPCWSTR fileName, _Outptr_ IStream** stream) { HRESULT hr = S_OK; const int MaxFileNameLength = 200; WCHAR fullFileName[MaxFileNameLength + 1]; // Create full file name by concatenating path and fileName hr = StringCchCopyW(fullFileName, MaxFileNameLength, path); if (SUCCEEDED(hr)) { hr = StringCchCat(fullFileName, MaxFileNameLength, L"\\"); } if (SUCCEEDED(hr)) { hr = StringCchCat(fullFileName, MaxFileNameLength, fileName); } // Search through fullFileName for the '\' character which denotes // subdirectory and create each subdirectory in order of depth. for (int i = 0; SUCCEEDED(hr) && (i < MaxFileNameLength); i++) { if (fullFileName[i] == L'\0') { break; } else if (fullFileName[i] == L'\\') { // Temporarily set string to terminate at the '\' character // to obtain name of the subdirectory to create fullFileName[i] = L'\0'; if (!CreateDirectory(fullFileName, NULL)) { DWORD lastError = GetLastError(); // It is normal for CreateDirectory to fail if the subdirectory // already exists. Other errors should not be ignored. if (lastError != ERROR_ALREADY_EXISTS) { hr = HRESULT_FROM_WIN32(lastError); } } // Restore original string fullFileName[i] = L'\\'; } } // Create stream for writing the file if (SUCCEEDED(hr)) { hr = SHCreateStreamOnFileEx( fullFileName, STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, // default file attributes TRUE, // create new file if it does not exist NULL, // no template stream); } return hr; } // // Function to print some basic information about an IAppxFile object, and // write it to disk under the given path. // // Parameters: // file - Instance of IAppxFile obtained from IAppxBundleReader representing // a footprint file or payload package in the bundle. // outputPath - Path of the folder where extracted files should be placed // HRESULT ExtractFile( _In_ IAppxFile* file, _In_ LPCWSTR outputPath) { HRESULT hr = S_OK; LPWSTR fileName = NULL; LPWSTR contentType = NULL; UINT64 fileSize = 0; IStream* fileStream = NULL; IStream* outputStream = NULL; ULARGE_INTEGER fileSizeLargeInteger = {0}; // Get basic information about the file hr = file->GetName(&fileName); if (SUCCEEDED(hr)) { hr = file->GetContentType(&contentType); } if (SUCCEEDED(hr)) { hr = file->GetSize(&fileSize); fileSizeLargeInteger.QuadPart = fileSize; } if (SUCCEEDED(hr)) { wprintf(L"\nFile name: %s\n", fileName); wprintf(L"Content type: %s\n", contentType); wprintf(L"Size: %llu bytes\n", fileSize); } // Write the file out to disk if (SUCCEEDED(hr)) { hr = file->GetStream(&fileStream); } if (SUCCEEDED(hr) && (fileName != NULL)) { hr = GetOutputStream(outputPath, fileName, &outputStream); } if (SUCCEEDED(hr) && (outputStream != NULL)) { hr = fileStream->CopyTo(outputStream, fileSizeLargeInteger, NULL, NULL); } // String buffers obtained from the bundle APIs must be freed CoTaskMemFree(fileName); CoTaskMemFree(contentType); // Clean up other allocated resources if (outputStream != NULL) { outputStream->Release(); outputStream = NULL; } if (fileStream != NULL) { fileStream->Release(); fileStream = NULL; } return hr; } // // Function to extract all footprint files from a bundle reader. // // Parameters: // bundleReader - Instance of IAppxBundleReader over the bundle whose footprint // files are to be extracted. // outputPath - Path of the folder where all extracted footprint files should // be placed. // HRESULT ExtractFootprintFiles( _In_ IAppxBundleReader* bundleReader, _In_ LPCWSTR outputPath) { HRESULT hr = S_OK; wprintf(L"\nExtracting footprint files from the bundle\n"); for (int i = 0; SUCCEEDED(hr) && (i < FootprintFilesCount); i++) { IAppxFile* footprintFile = NULL; hr = bundleReader->GetFootprintFile(FootprintFilesType[i], &footprintFile); if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) { // Some footprint files are optional, it's normal for the GetFootprintFile // call to fail when the file is not present. wprintf(L"\nThe bundle doesn't contain a %s.\n", FootprintFilesName[i]); hr = S_OK; } else if (SUCCEEDED(hr)) { hr = ExtractFile(footprintFile, outputPath); } if (footprintFile != NULL) { footprintFile->Release(); footprintFile = NULL; } } return hr; } // // Function to extract all payload packages from a bundle reader. // // Parameters: // bundleReader - Instance of IAppxBundleReader over the bundle whose payload // packages are to be extracted. // outputPath - Path of the folder where all extracted payload packages should // be placed. // HRESULT ExtractPayloadPackages( _In_ IAppxBundleReader* bundleReader, _In_ LPCWSTR outputPath) { HRESULT hr = S_OK; IAppxFilesEnumerator* payloadPackages = NULL; wprintf(L"\nExtracting payload packages from the bundle\n"); // Get an enumerator of all payload packages from the bundle reader and // iterate through all of them. hr = bundleReader->GetPayloadPackages(&payloadPackages); if (SUCCEEDED(hr)) { BOOL hasCurrent = FALSE; hr = payloadPackages->GetHasCurrent(&hasCurrent); while (SUCCEEDED(hr) && hasCurrent) { IAppxFile* payloadPackage = NULL; hr = payloadPackages->GetCurrent(&payloadPackage); if (SUCCEEDED(hr)) { hr = ExtractFile(payloadPackage, outputPath); } if (SUCCEEDED(hr)) { hr = payloadPackages->MoveNext(&hasCurrent); } if (payloadPackage != NULL) { payloadPackage->Release(); payloadPackage = NULL; } } } if (payloadPackages != NULL) { payloadPackages->Release(); payloadPackages = NULL; } return hr; } // // Function to create an Appx Bundle reader given the input file name. // // Parameters: // inputFileName - Name including path to the bundle (.appxbundle file) // to be opened. // bundleReader - Output parameter pointing to the created instance of // IAppxBundleReader when this function succeeds. // HRESULT GetBundleReader( _In_ LPCWSTR inputFileName, _Outptr_ IAppxBundleReader** bundleReader) { HRESULT hr = S_OK; IAppxBundleFactory* appxBundleFactory = NULL; IStream* inputStream = NULL; // Create a new Appx bundle factory hr = CoCreateInstance( __uuidof(AppxBundleFactory), NULL, CLSCTX_INPROC_SERVER, __uuidof(IAppxBundleFactory), (LPVOID*)(&appxBundleFactory)); // Create a stream over the input Appx bundle if (SUCCEEDED(hr)) { hr = SHCreateStreamOnFileEx( inputFileName, STGM_READ | STGM_SHARE_EXCLUSIVE, 0, // default file attributes FALSE, // do not create new file NULL, // no template &inputStream); } // Create a new bundle reader using the factory if (SUCCEEDED(hr)) { hr = appxBundleFactory->CreateBundleReader( inputStream, bundleReader); } // Clean up allocated resources if (inputStream != NULL) { inputStream->Release(); inputStream = NULL; } if (appxBundleFactory != NULL) { appxBundleFactory->Release(); appxBundleFactory = NULL; } return hr; } // // Main entry point of the sample // int wmain( _In_ int argc, _In_reads_(argc) wchar_t** argv) { wprintf(L"Copyright (c) Microsoft Corporation. All rights reserved.\n"); wprintf(L"ExtractBundle sample\n\n"); if (argc != 3) { wprintf(L"Usage: ExtractBundle.exe inputFile outputPath\n"); wprintf(L" inputFile: Path to the bundle to extract\n"); wprintf(L" outputPath: Path to the folder to store extracted contents\n"); return 2; } HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (SUCCEEDED(hr)) { // Create a bundle reader using the file name given in command line IAppxBundleReader* bundleReader = NULL; hr = GetBundleReader(argv[1], &bundleReader); // Print information about all footprint files, and extract them to disk if (SUCCEEDED(hr)) { hr = ExtractFootprintFiles(bundleReader, argv[2]); } // Print information about all payload files, and extract them to disk if (SUCCEEDED(hr)) { hr = ExtractPayloadPackages(bundleReader, argv[2]); } // Clean up allocated resources if (bundleReader != NULL) { bundleReader->Release(); bundleReader = NULL; } CoUninitialize(); } if (SUCCEEDED(hr)) { wprintf(L"\nBundle extracted successfully.\n"); } else { wprintf(L"\nBundle extraction failed with HRESULT 0x%08X.\n", hr); } return SUCCEEDED(hr) ? 0 : 1; }
30.196517
87
0.596919
zzgchina888
3e049a6a00ffe2ae32607fe6fda9d1856270b945
1,819
cpp
C++
src/game/systems/player_respawn_system.cpp
Rewlion/Asteroids
3812d8e229e6feba86b17a62c6b41894becc776a
[ "MIT" ]
null
null
null
src/game/systems/player_respawn_system.cpp
Rewlion/Asteroids
3812d8e229e6feba86b17a62c6b41894becc776a
[ "MIT" ]
1
2021-10-03T22:59:52.000Z
2021-10-03T22:59:52.000Z
src/game/systems/player_respawn_system.cpp
Rewlion/Asteroids
3812d8e229e6feba86b17a62c6b41894becc776a
[ "MIT" ]
1
2021-11-12T17:24:21.000Z
2021-11-12T17:24:21.000Z
#include "player_respawn_system.h" #include <engine/ecs/Context.h> #include <engine/collision/entity_collides_component.h> #include <engine/utils/time/utils.h> #include <engine/renderer/field_component.h> #include <game/components/player_component.h> #include <game/components/spawn_request_component.h> #include <game/components/game_statistics_component.h> #include <math/math.hpp> #include <random> PlayerRespawnSystem::PlayerRespawnSystem(Context* ecsContext) : LogicSystem(ecsContext) , m_PlayerGroup(ecsContext->GetGroup<PlayerComponent>()) , m_GameStatisticsGroup(ecsContext->GetGroup<GameStatisticsComponent>()) , m_GameFieldGroup(ecsContext->GetGroup<FieldComponent>()) { } void PlayerRespawnSystem::Update(const float dt) { const bool isPlayerAlive = m_PlayerGroup->GetFirstNotNullEntity() != nullptr; const auto* gameStatistics = m_GameStatisticsGroup->GetFirstNotNullEntity()->GetFirstComponent<GameStatisticsComponent>(); const auto* gameField = m_GameFieldGroup->GetFirstNotNullEntity()->GetFirstComponent<FieldComponent>(); if (!isPlayerAlive && !m_TimerToSpawnPlayerAlreadySetup && gameStatistics->playerLifes > 0) { Time::SetupDoOnceTimer(pContext, 1.0f, "Spawn Player Clock", [this, gameStatistics, gameField](Context* ecsContext) { SpawnRequestComponent* request = pContext->GetEntityManager()->NewEntity()->AddComponent<SpawnRequestComponent>("Spawn Player Request"); request->objectType = Identity::PlayerShip; request->position = { gameField->gameFieldSize.x / 2.0f, gameField->gameFieldSize.y / 2.0f }; request->rotation = 180.0f; request->team = Team::Team0; }); m_TimerToSpawnPlayerAlreadySetup = true; } else if (isPlayerAlive && m_TimerToSpawnPlayerAlreadySetup) m_TimerToSpawnPlayerAlreadySetup = false; }
41.340909
144
0.767455
Rewlion
3e0dcb214b4ac28f94d0d8b7c62baf9d24e25e76
511
cpp
C++
src/game-ui/ui_text_element.cpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
1
2020-09-23T11:17:35.000Z
2020-09-23T11:17:35.000Z
src/game-ui/ui_text_element.cpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
null
null
null
src/game-ui/ui_text_element.cpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
null
null
null
#include "ui_text_element.hpp" #include "../render_camera.hpp" #include "../debug/draw_debug.hpp" #include "./game_ui_manager.hpp" namespace space { void UITextElement::init(GameUIManager &uiManager) { font(uiManager.defaultFont()); widthAuto(); height(24); } void UITextElement::drawSelf(Engine &engine, RenderCamera &target) { _textElement.setCharacterSize(DrawDebug::fontSize); target.texture().draw(_textElement, _transform); } } // space
22.217391
70
0.665362
astrellon
3e0e79f029ece17679ba1f7703adc6fb3f009bac
4,608
cc
C++
include/jhc/impl/hex_encode.cc
winsoft666/akali_hpp
0f8091dabaccea9b7476f6e57e7ad81269b4fe4a
[ "MIT" ]
2
2022-02-27T05:03:45.000Z
2022-03-07T03:36:52.000Z
include/jhc/impl/hex_encode.cc
winsoft666/akali_hpp
0f8091dabaccea9b7476f6e57e7ad81269b4fe4a
[ "MIT" ]
null
null
null
include/jhc/impl/hex_encode.cc
winsoft666/akali_hpp
0f8091dabaccea9b7476f6e57e7ad81269b4fe4a
[ "MIT" ]
1
2022-02-27T05:04:00.000Z
2022-02-27T05:04:00.000Z
#include "jhc/config.hpp" #ifdef JHC_NOT_HEADER_ONLY #include "../hex_encode.hpp" #endif namespace jhc { JHC_INLINE char HexEncode::Encode(unsigned char val) { const char HEX[] = "0123456789abcdef"; assert(val < 16); return (val < 16) ? HEX[val] : '!'; } JHC_INLINE bool HexEncode::Decode(char ch, unsigned char* val) { if ((ch >= '0') && (ch <= '9')) { *val = ch - '0'; } else if ((ch >= 'A') && (ch <= 'Z')) { *val = (ch - 'A') + 10; } else if ((ch >= 'a') && (ch <= 'z')) { *val = (ch - 'a') + 10; } else { return false; } return true; } JHC_INLINE size_t HexEncode::EncodeWithDelimiter(char* buffer, size_t buflen, const char* csource, size_t srclen, char delimiter) { assert(buffer); if (buflen == 0) return 0; // Init and check bounds. const unsigned char* bsource = reinterpret_cast<const unsigned char*>(csource); size_t srcpos = 0, bufpos = 0; size_t needed = delimiter ? (srclen * 3) : (srclen * 2 + 1); if (buflen < needed) return 0; while (srcpos < srclen) { unsigned char ch = bsource[srcpos++]; buffer[bufpos] = Encode((ch >> 4) & 0xF); buffer[bufpos + 1] = Encode((ch)&0xF); bufpos += 2; // Don't write a delimiter after the last byte. if (delimiter && (srcpos < srclen)) { buffer[bufpos] = delimiter; ++bufpos; } } // Null terminate. buffer[bufpos] = '\0'; return bufpos; } JHC_INLINE std::string HexEncode::Encode(const std::string& str) { return Encode(str.c_str(), str.size()); } JHC_INLINE std::string HexEncode::Encode(const char* source, size_t srclen) { return EncodeWithDelimiter(source, srclen, 0); } JHC_INLINE std::string HexEncode::EncodeWithDelimiter(const char* source, size_t srclen, char delimiter) { const size_t kBufferSize = srclen * 3; char* buffer = static_cast<char*>(::malloc((kBufferSize) * sizeof(char))); if (!buffer) return ""; const size_t length = EncodeWithDelimiter(buffer, kBufferSize, source, srclen, delimiter); assert(srclen == 0 || length > 0); std::string ret(buffer, length); free(buffer); return ret; } JHC_INLINE size_t HexEncode::DecodeWithDelimiter(char* cbuffer, size_t buflen, const char* source, size_t srclen, char delimiter) { assert(cbuffer); if (buflen == 0) return 0; // Init and bounds check. unsigned char* bbuffer = reinterpret_cast<unsigned char*>(cbuffer); size_t srcpos = 0, bufpos = 0; size_t needed = (delimiter) ? (srclen + 1) / 3 : srclen / 2; if (buflen < needed) return 0; while (srcpos < srclen) { if ((srclen - srcpos) < 2) { // This means we have an odd number of bytes. return 0; } unsigned char h1, h2; if (!Decode(source[srcpos], &h1) || !Decode(source[srcpos + 1], &h2)) return 0; bbuffer[bufpos++] = (h1 << 4) | h2; srcpos += 2; // Remove the delimiter if needed. if (delimiter && (srclen - srcpos) > 1) { if (source[srcpos] != delimiter) return 0; ++srcpos; } } return bufpos; } JHC_INLINE size_t HexEncode::Decode(char* buffer, size_t buflen, const std::string& source) { return DecodeWithDelimiter(buffer, buflen, source, 0); } JHC_INLINE std::string HexEncode::Decode(const std::string& str) { if (str.length() == 0) return ""; const size_t kBufferSize = str.length(); char* buffer = static_cast<char*>(::malloc((kBufferSize) * sizeof(char))); if (!buffer) return ""; const size_t dstSize = Decode(buffer, kBufferSize, str); std::string ret(buffer, dstSize); free(buffer); return ret; } JHC_INLINE size_t HexEncode::DecodeWithDelimiter(char* buffer, size_t buflen, const std::string& source, char delimiter) { return DecodeWithDelimiter(buffer, buflen, source.c_str(), source.length(), delimiter); } } // namespace jhc
29.922078
106
0.52474
winsoft666
3e11ccdd99526b4d6f238b0b0fc9c94ccad29ffc
1,999
cpp
C++
GameEngineX/Source/Core/TransformationMatrixStack.cpp
GeorgeHanna/BarebonesGameEngine
39a122832a4b050fff117114d1ba37bbd72edd42
[ "MIT" ]
null
null
null
GameEngineX/Source/Core/TransformationMatrixStack.cpp
GeorgeHanna/BarebonesGameEngine
39a122832a4b050fff117114d1ba37bbd72edd42
[ "MIT" ]
null
null
null
GameEngineX/Source/Core/TransformationMatrixStack.cpp
GeorgeHanna/BarebonesGameEngine
39a122832a4b050fff117114d1ba37bbd72edd42
[ "MIT" ]
null
null
null
// // TransformationMatrixStack.cpp // GameEngineX // // Created by George Hanna on 20/05/16. // Copyright © 2016 George Hanna. All rights reserved. // #include "TransformationMatrixStack.hpp" namespace TransformationMatrixStack { TransformationMatrixStack* _matrixstack; void Initialize() { _matrixstack = new TransformationMatrixStack(); } void SetupMatrices(glm::mat4x4 &mmatrix, glm::mat4x4 &mvmatrix, glm::mat4x4 &mvpmatrix) { if(_matrixstack->_size > 2) { mvpmatrix = _matrixstack->_stack[0]; mvmatrix = _matrixstack->_stack[1]; mmatrix = _matrixstack->_stack[2]; for (int i = 3; i<_matrixstack->_size; i++) { mmatrix = mmatrix * _matrixstack->_stack[i]; } mvmatrix = _matrixstack->_stack[1] * mmatrix; mvpmatrix = _matrixstack->_stack[0] * mvmatrix; } } glm::mat4x4 GetMVPMatrix() { glm::mat4x4 mvpmatrix; if(_matrixstack->_size > 0) { mvpmatrix = _matrixstack->_stack[0]; for (int i = 1; i<_matrixstack->_size; i++) { mvpmatrix = mvpmatrix * _matrixstack->_stack[i]; } } return mvpmatrix; } glm::mat4x4 GetMVMatrix() { glm::mat4x4 mvmatrix; if(_matrixstack->_size > 1) { mvmatrix = _matrixstack->_stack[1]; for (int i = 2; i<_matrixstack->_size; i++) { mvmatrix = mvmatrix * _matrixstack->_stack[i]; } } return mvmatrix; } void SetViewMatrix(glm::mat4x4 viewmatrix) { _matrixstack->_stack[1] = viewmatrix; } void Push(glm::mat4x4 matrix) { _matrixstack->_stack[_matrixstack->_size] = matrix; _matrixstack->_size++; } void Pop() { if(_matrixstack->_size > 0) _matrixstack->_size--; } }
25.628205
91
0.541771
GeorgeHanna
3e1479dd8cf889f45681b118e95cec7bcc07a683
821
cpp
C++
LyraEngine/src/core/rendering/vulkan/vertex.cpp
zhuzhile08/lyra-engine
3b5de9e91a25642ce8f763c49b25dc443e0e36fd
[ "MIT" ]
null
null
null
LyraEngine/src/core/rendering/vulkan/vertex.cpp
zhuzhile08/lyra-engine
3b5de9e91a25642ce8f763c49b25dc443e0e36fd
[ "MIT" ]
1
2022-03-13T19:48:33.000Z
2022-03-31T19:25:35.000Z
LyraEngine/src/core/rendering/vulkan/vertex.cpp
zhuzhile08/lyra-engine
3b5de9e91a25642ce8f763c49b25dc443e0e36fd
[ "MIT" ]
null
null
null
#include <core/rendering/vulkan/vertex.h> namespace lyra { Vertex::Vertex() { } Vertex::Vertex(glm::vec3 pos, glm::vec3 normal, glm::vec2 uv, glm::vec3 color) : pos(pos), normal(normal), color(color), uv(uv) { } const VkVertexInputBindingDescription Vertex::get_binding_description() noexcept { return { 0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX }; } const std::array<VkVertexInputAttributeDescription, 4> Vertex::get_attribute_descriptions() noexcept { return { {{ 0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, pos) }, { 1, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, normal) }, { 2, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, color) }, { 3, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, uv) }} }; } } // namespace lyra
17.847826
131
0.676005
zhuzhile08
3e160b8c78c00dfde9372d2a87f67bd67a015944
13,015
cpp
C++
src/chapter_10_archives_images_and_databases/problem_087_handling_images_in_an_sqlite_db.cpp
rturrado/the_modern_cpp_challenge
a569a1538802a44c3b7c44134c06c73727f2b5e3
[ "MIT" ]
null
null
null
src/chapter_10_archives_images_and_databases/problem_087_handling_images_in_an_sqlite_db.cpp
rturrado/the_modern_cpp_challenge
a569a1538802a44c3b7c44134c06c73727f2b5e3
[ "MIT" ]
null
null
null
src/chapter_10_archives_images_and_databases/problem_087_handling_images_in_an_sqlite_db.cpp
rturrado/the_modern_cpp_challenge
a569a1538802a44c3b7c44134c06c73727f2b5e3
[ "MIT" ]
null
null
null
#include "chapter_09_data_serialization/movies.h" #include "chapter_10_archives_images_and_databases.h" #include "chapter_10_archives_images_and_databases/sqlite_movies.h" #include "rtc/sstream.h" // get_unread #include "rtc/string.h" // to_lowercase #include <filesystem> #include <format> #include <iostream> // cin, cout #include <map> #include <optional> #include <ranges> #include <regex> #include <sstream> // istringstream, ostringstream #include <stdexcept> // runtime_error #include <string> // getline #include <tuple> #include <vector> namespace fs = std::filesystem; enum class command_t { add, help, list, quit, remove }; enum class subcommand_t { media, movie }; std::map<command_t, std::string> command_to_string{ { command_t::add, "add" }, { command_t::help, "help" }, { command_t::list, "list" }, { command_t::quit, "quit" }, { command_t::remove, "remove" } }; std::map<std::string, command_t> string_to_command{ { "add", command_t::add }, { "help", command_t::help }, { "list", command_t::list }, { "quit", command_t::quit}, { "remove", command_t::remove } }; std::map<subcommand_t, std::string> subcommmand_to_string{ { subcommand_t::media, "media" }, { subcommand_t::movie, "movie" } }; std::map<std::string, subcommand_t> string_to_subcommand{ { "media", subcommand_t::media }, { "movie", subcommand_t::movie } }; std::map<command_t, std::vector<subcommand_t>> command_to_subcommands{ { command_t::list, { subcommand_t::media, subcommand_t::movie } } }; struct CommandLineOptions { int movie_id{}; int media_id{}; std::regex movie_title_regex{}; fs::path media_file_path{}; std::optional<std::string> media_file_description{}; }; struct CommandNotFoundError : public std::runtime_error { CommandNotFoundError(const std::string& command) : std::runtime_error{ message_ + command } {} private: static inline std::string message_{ "command not found: " }; }; struct SubcommandNotFoundError : public std::runtime_error { SubcommandNotFoundError(const std::string& subcommand) : std::runtime_error{ message_ + subcommand } {} private: static inline std::string message_{ "subcommand not found: " }; }; struct InvalidMediaIdError : public std::runtime_error { InvalidMediaIdError(const std::string& media_id_str) : std::runtime_error{ message_ + media_id_str } {} private: static inline std::string message_{ "invalid media ID: " }; }; struct InvalidMovieIdError : public std::runtime_error { InvalidMovieIdError(const std::string& movie_id_str) : std::runtime_error{ message_ + movie_id_str } {} private: static inline std::string message_{ "invalid movie ID: " }; }; struct InvalidSubcommandError : public std::runtime_error { InvalidSubcommandError(const std::string& command_str, const std::string& subcommand_str) : std::runtime_error{ "" } { std::ostringstream oss{}; oss << std::format("invalid subcommand '{}' for command '{}'", command_str, subcommand_str); message_ = oss.str(); } virtual const char* what() const noexcept override { return message_.c_str(); } private: std::string message_{}; }; void print_usage() { std::cout << "Usage:\n"; std::cout << "\tlist movie <movie_title_regex>\n"; std::cout << "\tlist media <movie_id>\n"; std::cout << "\tadd <movie_id>, <media_file_path>, [<media_file_description>]\n"; std::cout << "\tremove <media_id>\n"; std::cout << "\thelp\n"; std::cout << "\tquit\n"; std::cout << "Where:\n"; std::cout << "\tmedia_file_description Optional media file description.\n"; std::cout << "\tmedia_file_path File path pointing to a media file.\n"; std::cout << "\tmedia_id Media ID, as shown when listing a media file.\n"; std::cout << "\tmovie_id Movie ID, as shown when listing a movie.\n"; std::cout << "\tmovie_title_regex Regular expression for a movie title.\n"; std::cout << "Examples:\n"; std::cout << "\tlist movie .*The.*\n"; std::cout << "\tlist media 4\n"; std::cout << "\tadd 4, ./res/db/BladeRunner.jpg, Front cover\n"; std::cout << "\tremove 0\n"; } auto read_command_line() { std::cout << "(help for usage) > "; std::string command_line{}; std::getline(std::cin, command_line); return command_line; } void parse_command(std::istringstream& iss, command_t& command) { std::string command_str{}; iss >> command_str; command_str = rtc::string::to_lowercase(command_str); if (not string_to_command.contains(command_str)) { throw CommandNotFoundError{ command_str }; } command = string_to_command[command_str]; } void parse_subcommand(std::istringstream& iss, const command_t& command, subcommand_t& subcommand) { if (not command_to_subcommands.contains(command)) { // this command has no subcommands return; } std::string subcommand_str{}; iss >> subcommand_str; subcommand_str = rtc::string::to_lowercase(subcommand_str); if (not string_to_subcommand.contains(subcommand_str)) { // this subcommand does not exist throw SubcommandNotFoundError{ subcommand_str }; } subcommand = string_to_subcommand[subcommand_str]; auto& valid_subcommands{ command_to_subcommands[command] }; if (std::ranges::find(valid_subcommands, subcommand) == std::cend(valid_subcommands)) { // this command does not accept this subcommand throw InvalidSubcommandError{ command_to_string[command], subcommand_str }; } } void parse_media_id_option(std::istringstream& iss, CommandLineOptions& options) { std::string media_id_str{}; iss >> media_id_str; try { options.media_id = std::stoi(media_id_str); } catch (const std::exception&) { throw InvalidMediaIdError{ media_id_str }; } } void parse_movie_id_option(std::istringstream& iss, CommandLineOptions& options) { std::string movie_id_str{}; iss >> movie_id_str; try { options.movie_id = std::stoi(movie_id_str); } catch (const std::exception&) { throw InvalidMovieIdError{ movie_id_str }; } } void parse_movie_title_regex_option(std::istringstream& iss, CommandLineOptions& options) { std::string movie_title_regex_str{}; iss >> movie_title_regex_str; options.movie_title_regex = movie_title_regex_str; } void parse_add_options(std::istringstream& iss, CommandLineOptions& options) { std::string line{ rtc::sstream::get_unread(iss) }; std::smatch matches{}; const std::regex pattern{ R"(\s*([\d]+)\s*,\s*([^,]+)(?:,\s*(.*))?)" }; if (std::regex_match(line, matches, pattern)) { options.movie_id = std::stoi(matches[1].str()); options.media_file_path = rtc::string::trim_right(matches[2].str()); if (matches.size() == 4) { options.media_file_description = rtc::string::trim_right(matches[3].str()); } } } void parse_list_media_options(std::istringstream& iss, CommandLineOptions& options) { parse_movie_id_option(iss, options); } void parse_list_movie_options(std::istringstream& iss, CommandLineOptions& options) { parse_movie_title_regex_option(iss, options); } void parse_remove_options(std::istringstream& iss, CommandLineOptions& options) { parse_media_id_option(iss, options); } auto parse_command_line(std::string command_line) { std::istringstream iss{ command_line }; command_t command{}; parse_command(iss, command); subcommand_t subcommand{}; parse_subcommand(iss, command, subcommand); CommandLineOptions options{}; switch (command) { case command_t::add: { parse_add_options(iss, options); break; } case command_t::help: break; case command_t::list: { switch (subcommand) { case subcommand_t::media: { parse_list_media_options(iss, options); break; } case subcommand_t::movie: { parse_list_movie_options(iss, options); break; } default: break; }; break; } case command_t::quit: break; case command_t::remove: { parse_remove_options(iss, options); break; } default: break; } return std::tuple<command_t, subcommand_t, CommandLineOptions>{ command, subcommand, options }; } void add_media( tmcppc::movies::sqlite_mcpp::database& movies_db, size_t movie_id, const fs::path& media_file_path, std::optional<std::string> media_file_description) { if (not fs::exists(media_file_path)) { std::cout << std::format("Error: media file not found: {}\n", media_file_path.string()); return; } try { auto media_file{ tmcppc::movies::MediaFile{ movie_id, media_file_path, media_file_description } }; movies_db.insert_media_file(movie_id, media_file); std::cout << movies_db; } catch (const tmcppc::movies::sqlite_mcpp::MovieIdNotFoundError& ex) { std::cout << "Error: " << ex.what() << "\n"; } } void delete_media(tmcppc::movies::sqlite_mcpp::database& movies_db, size_t media_id) { try { movies_db.delete_media_file(media_id); std::cout << movies_db; } catch (const tmcppc::movies::sqlite_mcpp::MediaFileIdNotFoundError& ex) { std::cout << "Error: " << ex.what() << "\n"; } } void list_media(const tmcppc::movies::sqlite_mcpp::database& movies_db, size_t movie_id) { try { for (auto& media_file : movies_db.get_media_files(movie_id)) { std::cout << media_file << "\n"; } } catch (const tmcppc::movies::sqlite_mcpp::MovieIdNotFoundError& ex) { std::cout << "Error: " << ex.what() << "\n"; } } void list_movies(const tmcppc::movies::sqlite_mcpp::database& movies_db, const std::regex& pattern) { for (auto& movie : movies_db.get_movies(pattern)) { std::cout << movie << "\n"; } } void execute_command( tmcppc::movies::sqlite_mcpp::database& movies_db, const command_t command, const subcommand_t subcommand, const CommandLineOptions& options) { switch (command) { case command_t::add: { add_media(movies_db, options.movie_id, options.media_file_path, options.media_file_description); break; } case command_t::help: { print_usage(); break; } case command_t::list: switch (subcommand) { case subcommand_t::media: { list_media(movies_db, options.movie_id); break; } case subcommand_t::movie: { list_movies(movies_db, options.movie_title_regex); break; } default: break; }; break; case command_t::remove: { delete_media(movies_db, options.media_id); break; } default: break; } } void menu(tmcppc::movies::sqlite_mcpp::database& movies_db) { for (;;) { try { auto command_line{ read_command_line() }; auto [command, subcommand, options] = parse_command_line(command_line); if (command == command_t::quit) { break; } execute_command(movies_db, command, subcommand, options); std::cout << "\n"; } catch (const std::exception& ex) { std::cout << "Error: " << ex.what() << "\n\n"; } } } // Handling movie images in an SQLite database // // Modify the program written for the previous problem to support adding media files (such as images, but also videos) to a movie. // These files must be stored in a separate table in the database and have a unique numerical identifier, the movie identifier, // a name (typically the filename), an optional description, and the actual media content, stored as a blob. // The following is a diagram with the structure of the table that must be added to the existing database: // // media // -------------------------- // (key) rowid integer // movieid integer // name text // description text // content blob // // The program written for this problem must support several commands: // - Listing all movies that match a search criterion (notably the title). // - Listing information about all existing media files for a movie. // - Adding a new media file for a movie. // - Deleting an existing media file. void problem_87_main() { const auto db_file_path{ fs::current_path() / "res" / "db" / "movies.db" }; try { { auto sqlite_db{ tmcppc::movies::sqlite_mcpp::create_movies_database(db_file_path) }; auto movies_db{ tmcppc::movies::sqlite_mcpp::database{ sqlite_db } }; menu(movies_db); } std::cout << "\n"; tmcppc::movies::sqlite_mcpp::remove_movies_database_file(db_file_path); } catch (const sqlite::sqlite_exception& ex) { std::cout << std::format("Error: code = {}, message = '{}', operation = '{}'\n", ex.get_code(), ex.what(), ex.get_sql()); } catch (const std::exception& ex) { std::cout << "Error: " << ex.what() << "\n"; } std::cout << "\n"; }
33.893229
140
0.658164
rturrado
3e16a11cfdcbf404986fc4ae1c1cad3dfaceb26d
1,601
hh
C++
isaac_variant_caller/src/lib/blt_util/stringer.hh
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
21
2015-01-09T01:11:28.000Z
2019-09-04T03:48:21.000Z
isaac_variant_caller/src/lib/blt_util/stringer.hh
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
4
2015-07-23T09:38:39.000Z
2018-02-01T05:37:26.000Z
isaac_variant_caller/src/lib/blt_util/stringer.hh
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
13
2015-01-29T16:41:26.000Z
2021-06-25T02:42:32.000Z
// -*- mode: c++; indent-tabs-mode: nil; -*- // // Copyright (c) 2009-2013 Illumina, Inc. // // This software is provided under the terms and conditions of the // Illumina Open Source Software License 1. // // You should have received a copy of the Illumina Open Source // Software License 1 along with this program. If not, see // <https://github.com/sequencing/licenses/> // /// \file /// \author Chris Saunders /// #ifndef __STRINGER_HH #define __STRINGER_HH #include "compat_util.hh" #include "scan_string.hh" #include <cstdio> #include <typeinfo> struct stringer_base { stringer_base() : _scanstr(NULL) {} protected: static void type_error(const char* tiname); void get32_error(const int write_size) const; mutable char _buff32[32]; const char* _scanstr; }; /// String conversion utility which is harder-to-use but faster than stringstream/lexical_cast /// /// Safety notes: /// 1) client must create one object for each thread /// 2) The string pointer returned will be invalid at the next conversion call to stringer /// template <typename T> struct stringer : public stringer_base { stringer<T>() { _scanstr=scan_string<T>(); if (NULL==_scanstr) { type_error(typeid(T).name()); } } const char* get32(const T val) const { static const unsigned buff_size(32); const int write_size(snprintf(_buff32,buff_size,_scanstr,val)); if ((write_size<0) || (write_size >= static_cast<int>(buff_size))) { get32_error(write_size); } return _buff32; } }; #endif
21.346667
94
0.664585
sequencing
3e188b89faf68fcc8fa897d1dadf35be57aa3a10
17,749
cpp
C++
src/gpu/GrSurfaceProxy.cpp
onlyyou2023/tingskia
4e8c00df69ab8fb986f4985a393fd83c313b8909
[ "BSD-3-Clause" ]
null
null
null
src/gpu/GrSurfaceProxy.cpp
onlyyou2023/tingskia
4e8c00df69ab8fb986f4985a393fd83c313b8909
[ "BSD-3-Clause" ]
null
null
null
src/gpu/GrSurfaceProxy.cpp
onlyyou2023/tingskia
4e8c00df69ab8fb986f4985a393fd83c313b8909
[ "BSD-3-Clause" ]
null
null
null
/* * 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 "GrSurfaceProxy.h" #include "GrSurfaceProxyPriv.h" #include "GrCaps.h" #include "GrContext.h" #include "GrContextPriv.h" #include "GrGpuResourcePriv.h" #include "GrOpList.h" #include "GrResourceProvider.h" #include "GrSurfaceContext.h" #include "GrTexturePriv.h" #include "GrTextureRenderTargetProxy.h" #include "SkMathPriv.h" #include "SkMipMap.h" GrSurfaceProxy::GrSurfaceProxy(sk_sp<GrSurface> surface, GrSurfaceOrigin origin, SkBackingFit fit) : INHERITED(std::move(surface)) , fConfig(fTarget->config()) , fWidth(fTarget->width()) , fHeight(fTarget->height()) , fOrigin(origin) , fFit(fit) , fBudgeted(fTarget->resourcePriv().isBudgeted()) , fFlags(0) , fUniqueID(fTarget->uniqueID()) // Note: converting from unique resource ID to a proxy ID! , fNeedsClear(false) , fGpuMemorySize(kInvalidGpuMemorySize) , fLastOpList(nullptr) { } GrSurfaceProxy::~GrSurfaceProxy() { // For this to be deleted the opList that held a ref on it (if there was one) must have been // deleted. Which would have cleared out this back pointer. SkASSERT(!fLastOpList); } static bool attach_stencil_if_needed(GrResourceProvider* resourceProvider, GrSurface* surface, bool needsStencil) { if (needsStencil) { GrRenderTarget* rt = surface->asRenderTarget(); if (!rt) { SkASSERT(0); return false; } if (!resourceProvider->attachStencilAttachment(rt)) { return false; } } return true; } sk_sp<GrSurface> GrSurfaceProxy::createSurfaceImpl( GrResourceProvider* resourceProvider, int sampleCnt, bool needsStencil, GrSurfaceFlags flags, GrMipMapped mipMapped, SkDestinationSurfaceColorMode mipColorMode) const { SkASSERT(GrMipMapped::kNo == mipMapped); GrSurfaceDesc desc; desc.fFlags = flags; if (fNeedsClear) { desc.fFlags |= kPerformInitialClear_GrSurfaceFlag; } desc.fOrigin = fOrigin; desc.fWidth = fWidth; desc.fHeight = fHeight; desc.fConfig = fConfig; desc.fSampleCnt = sampleCnt; sk_sp<GrSurface> surface; if (SkBackingFit::kApprox == fFit) { surface.reset(resourceProvider->createApproxTexture(desc, fFlags).release()); } else { surface.reset(resourceProvider->createTexture(desc, fBudgeted, fFlags).release()); } if (!surface) { return nullptr; } surface->asTexture()->texturePriv().setMipColorMode(mipColorMode); if (!attach_stencil_if_needed(resourceProvider, surface.get(), needsStencil)) { return nullptr; } return surface; } void GrSurfaceProxy::assign(sk_sp<GrSurface> surface) { SkASSERT(!fTarget && surface); fTarget = surface.release(); this->INHERITED::transferRefs(); #ifdef SK_DEBUG if (kInvalidGpuMemorySize != this->getRawGpuMemorySize_debugOnly()) { SkASSERT(fTarget->gpuMemorySize() <= this->getRawGpuMemorySize_debugOnly()); } #endif } bool GrSurfaceProxy::instantiateImpl(GrResourceProvider* resourceProvider, int sampleCnt, bool needsStencil, GrSurfaceFlags flags, GrMipMapped mipMapped, SkDestinationSurfaceColorMode mipColorMode, const GrUniqueKey* uniqueKey) { if (fTarget) { if (uniqueKey) { SkASSERT(fTarget->getUniqueKey() == *uniqueKey); } return attach_stencil_if_needed(resourceProvider, fTarget, needsStencil); } sk_sp<GrSurface> surface = this->createSurfaceImpl(resourceProvider, sampleCnt, needsStencil, flags, mipMapped, mipColorMode); if (!surface) { return false; } // If there was an invalidation message pending for this key, we might have just processed it, // causing the key (stored on this proxy) to become invalid. if (uniqueKey && uniqueKey->isValid()) { resourceProvider->assignUniqueKeyToResource(*uniqueKey, surface.get()); } this->assign(std::move(surface)); return true; } void GrSurfaceProxy::computeScratchKey(GrScratchKey* key) const { const GrRenderTargetProxy* rtp = this->asRenderTargetProxy(); int sampleCount = 0; if (rtp) { sampleCount = rtp->numStencilSamples(); } const GrTextureProxy* tp = this->asTextureProxy(); GrMipMapped mipMapped = GrMipMapped::kNo; if (tp) { mipMapped = tp->mipMapped(); } int width = this->worstCaseWidth(); int height = this->worstCaseHeight(); GrTexturePriv::ComputeScratchKey(this->config(), width, height, SkToBool(rtp), sampleCount, mipMapped, key); } void GrSurfaceProxy::setLastOpList(GrOpList* opList) { #ifdef SK_DEBUG if (fLastOpList) { SkASSERT(fLastOpList->isClosed()); } #endif // Un-reffed fLastOpList = opList; } GrRenderTargetOpList* GrSurfaceProxy::getLastRenderTargetOpList() { return fLastOpList ? fLastOpList->asRenderTargetOpList() : nullptr; } GrTextureOpList* GrSurfaceProxy::getLastTextureOpList() { return fLastOpList ? fLastOpList->asTextureOpList() : nullptr; } sk_sp<GrSurfaceProxy> GrSurfaceProxy::MakeWrapped(sk_sp<GrSurface> surf, GrSurfaceOrigin origin) { if (!surf) { return nullptr; } if (surf->getUniqueKey().isValid()) { // The proxy may already be in the hash. Thus we need to look for it first before creating // new one. GrResourceProvider* provider = surf->getContext()->resourceProvider(); sk_sp<GrSurfaceProxy> proxy = provider->findProxyByUniqueKey(surf->getUniqueKey(), origin); if (proxy) { return proxy; } } if (surf->asTexture()) { if (surf->asRenderTarget()) { return sk_sp<GrSurfaceProxy>(new GrTextureRenderTargetProxy(std::move(surf), origin)); } else { return sk_sp<GrSurfaceProxy>(new GrTextureProxy(std::move(surf), origin)); } } else { SkASSERT(surf->asRenderTarget()); // Not texturable return sk_sp<GrSurfaceProxy>(new GrRenderTargetProxy(std::move(surf), origin)); } } sk_sp<GrTextureProxy> GrSurfaceProxy::MakeWrapped(sk_sp<GrTexture> tex, GrSurfaceOrigin origin) { if (!tex) { return nullptr; } if (tex->getUniqueKey().isValid()) { // The proxy may already be in the hash. Thus we need to look for it first before creating // new one. GrResourceProvider* provider = tex->getContext()->resourceProvider(); sk_sp<GrTextureProxy> proxy = provider->findProxyByUniqueKey(tex->getUniqueKey(), origin); if (proxy) { return proxy; } } if (tex->asRenderTarget()) { return sk_sp<GrTextureProxy>(new GrTextureRenderTargetProxy(std::move(tex), origin)); } else { return sk_sp<GrTextureProxy>(new GrTextureProxy(std::move(tex), origin)); } } sk_sp<GrTextureProxy> GrSurfaceProxy::MakeDeferred(GrResourceProvider* resourceProvider, const GrSurfaceDesc& desc, SkBackingFit fit, SkBudgeted budgeted, uint32_t flags) { SkASSERT(0 == flags || GrResourceProvider::kNoPendingIO_Flag == flags); const GrCaps* caps = resourceProvider->caps(); // TODO: move this logic into GrResourceProvider! // TODO: share this testing code with check_texture_creation_params if (!caps->isConfigTexturable(desc.fConfig)) { return nullptr; } bool willBeRT = SkToBool(desc.fFlags & kRenderTarget_GrSurfaceFlag); if (willBeRT && !caps->isConfigRenderable(desc.fConfig, desc.fSampleCnt > 0)) { return nullptr; } // We currently do not support multisampled textures if (!willBeRT && desc.fSampleCnt > 0) { return nullptr; } int maxSize; if (willBeRT) { maxSize = caps->maxRenderTargetSize(); } else { maxSize = caps->maxTextureSize(); } if (desc.fWidth > maxSize || desc.fHeight > maxSize || desc.fWidth <= 0 || desc.fHeight <= 0) { return nullptr; } GrSurfaceDesc copyDesc = desc; copyDesc.fSampleCnt = caps->getSampleCount(desc.fSampleCnt, desc.fConfig); #ifdef SK_DISABLE_DEFERRED_PROXIES // Temporarily force instantiation for crbug.com/769760 and crbug.com/769898 sk_sp<GrTexture> tex; if (SkBackingFit::kApprox == fit) { tex = resourceProvider->createApproxTexture(copyDesc, flags); } else { tex = resourceProvider->createTexture(copyDesc, budgeted, flags); } if (!tex) { return nullptr; } return GrSurfaceProxy::MakeWrapped(std::move(tex), copyDesc.fOrigin); #else if (willBeRT) { // We know anything we instantiate later from this deferred path will be // both texturable and renderable return sk_sp<GrTextureProxy>(new GrTextureRenderTargetProxy(*caps, copyDesc, fit, budgeted, flags)); } return sk_sp<GrTextureProxy>(new GrTextureProxy(copyDesc, fit, budgeted, nullptr, 0, flags)); #endif } sk_sp<GrTextureProxy> GrSurfaceProxy::MakeDeferred(GrResourceProvider* resourceProvider, const GrSurfaceDesc& desc, SkBudgeted budgeted, const void* srcData, size_t rowBytes) { if (srcData) { GrMipLevel mipLevel = { srcData, rowBytes }; return resourceProvider->createTextureProxy(desc, budgeted, mipLevel); } return GrSurfaceProxy::MakeDeferred(resourceProvider, desc, SkBackingFit::kExact, budgeted); } sk_sp<GrTextureProxy> GrSurfaceProxy::MakeDeferredMipMap(GrResourceProvider* resourceProvider, const GrSurfaceDesc& desc, SkBudgeted budgeted) { // SkMipMap doesn't include the base level in the level count so we have to add 1 int mipCount = SkMipMap::ComputeLevelCount(desc.fWidth, desc.fHeight) + 1; std::unique_ptr<GrMipLevel[]> texels(new GrMipLevel[mipCount]); // We don't want to upload any texel data for (int i = 0; i < mipCount; i++) { texels[i].fPixels = nullptr; texels[i].fRowBytes = 0; } return MakeDeferredMipMap(resourceProvider, desc, budgeted, texels.get(), mipCount); } sk_sp<GrTextureProxy> GrSurfaceProxy::MakeDeferredMipMap( GrResourceProvider* resourceProvider, const GrSurfaceDesc& desc, SkBudgeted budgeted, const GrMipLevel texels[], int mipLevelCount, SkDestinationSurfaceColorMode mipColorMode) { if (!mipLevelCount) { if (texels) { return nullptr; } return GrSurfaceProxy::MakeDeferred(resourceProvider, desc, budgeted, nullptr, 0); } if (!texels) { return nullptr; } if (1 == mipLevelCount) { return resourceProvider->createTextureProxy(desc, budgeted, texels[0]); } #ifdef SK_DEBUG // There are only three states we want to be in when uploading data to a mipped surface. // 1) We have data to upload to all layers // 2) We are not uploading data to any layers // 3) We are only uploading data to the base layer // We check here to make sure we do not have any other state. bool firstLevelHasData = SkToBool(texels[0].fPixels); bool allOtherLevelsHaveData = true, allOtherLevelsLackData = true; for (int i = 1; i < mipLevelCount; ++i) { if (texels[i].fPixels) { allOtherLevelsLackData = false; } else { allOtherLevelsHaveData = false; } } SkASSERT((firstLevelHasData && allOtherLevelsHaveData) || allOtherLevelsLackData); #endif sk_sp<GrTexture> tex(resourceProvider->createTexture(desc, budgeted, texels, mipLevelCount, mipColorMode)); if (!tex) { return nullptr; } return GrSurfaceProxy::MakeWrapped(std::move(tex), desc.fOrigin); } sk_sp<GrTextureProxy> GrSurfaceProxy::MakeWrappedBackend(GrContext* context, GrBackendTexture& backendTex, GrSurfaceOrigin origin) { sk_sp<GrTexture> tex(context->resourceProvider()->wrapBackendTexture(backendTex)); return GrSurfaceProxy::MakeWrapped(std::move(tex), origin); } int GrSurfaceProxy::worstCaseWidth() const { if (fTarget) { return fTarget->width(); } if (SkBackingFit::kExact == fFit) { return fWidth; } return SkTMax(GrResourceProvider::kMinScratchTextureSize, GrNextPow2(fWidth)); } int GrSurfaceProxy::worstCaseHeight() const { if (fTarget) { return fTarget->height(); } if (SkBackingFit::kExact == fFit) { return fHeight; } return SkTMax(GrResourceProvider::kMinScratchTextureSize, GrNextPow2(fHeight)); } #ifdef SK_DEBUG void GrSurfaceProxy::validate(GrContext* context) const { if (fTarget) { SkASSERT(fTarget->getContext() == context); } INHERITED::validate(); } #endif sk_sp<GrTextureProxy> GrSurfaceProxy::Copy(GrContext* context, GrSurfaceProxy* src, GrMipMapped mipMapped, SkIRect srcRect, SkBudgeted budgeted) { if (!srcRect.intersect(SkIRect::MakeWH(src->width(), src->height()))) { return nullptr; } GrSurfaceDesc dstDesc; dstDesc.fOrigin = src->origin(); dstDesc.fWidth = srcRect.width(); dstDesc.fHeight = srcRect.height(); dstDesc.fConfig = src->config(); sk_sp<GrSurfaceContext> dstContext(context->contextPriv().makeDeferredSurfaceContext( dstDesc, mipMapped, SkBackingFit::kExact, budgeted)); if (!dstContext) { return nullptr; } if (!dstContext->copy(src, srcRect, SkIPoint::Make(0, 0))) { return nullptr; } return dstContext->asTextureProxyRef(); } sk_sp<GrTextureProxy> GrSurfaceProxy::Copy(GrContext* context, GrSurfaceProxy* src, GrMipMapped mipMapped, SkBudgeted budgeted) { return Copy(context, src, mipMapped, SkIRect::MakeWH(src->width(), src->height()), budgeted); } sk_sp<GrSurfaceContext> GrSurfaceProxy::TestCopy(GrContext* context, const GrSurfaceDesc& dstDesc, GrSurfaceProxy* srcProxy) { sk_sp<GrSurfaceContext> dstContext(context->contextPriv().makeDeferredSurfaceContext( dstDesc, GrMipMapped::kNo, SkBackingFit::kExact, SkBudgeted::kYes)); if (!dstContext) { return nullptr; } if (!dstContext->copy(srcProxy)) { return nullptr; } return dstContext; } void GrSurfaceProxyPriv::exactify() { if (this->isExact()) { return; } SkASSERT(SkBackingFit::kApprox == fProxy->fFit); if (fProxy->fTarget) { // The kApprox but already instantiated case. Setting the proxy's width & height to // the instantiated width & height could have side-effects going forward, since we're // obliterating the area of interest information. This call (exactify) only used // when converting an SkSpecialImage to an SkImage so the proxy shouldn't be // used for additional draws. fProxy->fWidth = fProxy->fTarget->width(); fProxy->fHeight = fProxy->fTarget->height(); return; } // The kApprox uninstantiated case. Making this proxy be exact should be okay. // It could mess things up if prior decisions were based on the approximate size. fProxy->fFit = SkBackingFit::kExact; // If fGpuMemorySize is used when caching specialImages for the image filter DAG. If it has // already been computed we want to leave it alone so that amount will be removed when // the special image goes away. If it hasn't been computed yet it might as well compute the // exact amount. }
35.92915
100
0.589329
onlyyou2023
4a3cb96166db3d8b4f2c34df754988273de8fe40
3,477
cpp
C++
drivers/storage/atapio/src/atapio.cpp
AlexandreRouma/MemeOS
b3996f23a30b95d8bb0899207e9ebf7c3f7fe37e
[ "MIT" ]
12
2018-05-02T21:41:46.000Z
2022-02-22T00:50:05.000Z
drivers/storage/atapio/src/atapio.cpp
AlexandreRouma/MemeOS
b3996f23a30b95d8bb0899207e9ebf7c3f7fe37e
[ "MIT" ]
1
2020-05-15T05:23:23.000Z
2020-05-15T19:40:03.000Z
drivers/storage/atapio/src/atapio.cpp
AlexandreRouma/MemeOS
b3996f23a30b95d8bb0899207e9ebf7c3f7fe37e
[ "MIT" ]
3
2018-03-20T17:35:31.000Z
2021-10-01T17:43:55.000Z
#include <stdint.h> #include <drivers/storage/atapio/atapio.h> #include <libs/kernel/io.h> #include <libs/kernel/panic.h> #include <drivers/timer/pit.h> #include <drivers/text_term/terminal.h> #include <libs/std/math.h> ATAPIO_Class ATAPIO; extern "C" void __cxa_pure_virtual() { while (1); } int selectDrive(int drive, int numblock, int count) { outb(0x1F1, 0x00); /* NULL byte to port 0x1F1 */ outb(0x1F2, count); /* Sector count */ outb(0x1F3, (uint8_t) numblock); /* Low 8 bits of the block address */ outb(0x1F4, (uint8_t) (numblock >> 8)); /* Next 8 bits of the block address */ outb(0x1F5, (uint8_t) (numblock >> 16)); /* Next 8 bits of the block address */ /* Drive indicator, magic bits, and highest 4 bits of the block address */ outb(0x1F6, 0xE0 | (drive << 4) | ((numblock >> 24) & 0x0F)); return 0; } int ATAPIO_Class::readBlock(int drive, int numblock, int count, char *buf) { uint16_t tmpword; int idx; if (count == 0) { kernel_panic(0x1234, "Null sector count read"); } selectDrive(drive, numblock, count); outb(0x1F7, 0x20); for (int i = 0; i < count; i++) { PIT.delay(1); uint8_t status = inb(0x1F7); while ((status & 0x80) && !(status & 0x08)) { status = inb(0x1F7); } for (idx = 0; idx < 256 * count; idx++) { tmpword = inw(0x1F0); buf[(idx * 2) + (i * 512)] = (uint8_t)tmpword; buf[(idx * 2 + 1) + (i * 512)] = (uint8_t)(tmpword >> 8); } } return count; } int ATAPIO_Class::writeBlock(int drive, int numblock, int count, char *buf) { uint16_t tmpword; int idx; if (count == 0) { kernel_panic(0x1234, "Null sector count write"); } selectDrive(drive, numblock, count); outb(0x1F7, 0x30); // Wait for ready signal uint8_t status = (inb(0x1F7) & 0x08); while (!status) { status = (inb(0x1F7) & 0x08); } for (idx = 0; idx < 256 * count; idx++) { tmpword = (buf[idx * 2 + 1] << 8) | buf[idx * 2]; outw(0x1F0, tmpword); } return count; } ATAPIODrive_t::ATAPIODrive_t(uint8_t id) { this->id = id; } bool ATAPIODrive_t::read(uint64_t addr, uint64_t size, uint8_t* buf) { uint64_t base = floor(addr / 512); uint64_t limit = ceil((addr + size) / 512); uint64_t start = addr % 512; uint8_t* buffer = (uint8_t*)malloc(((limit - base) + 1) * 512); ATAPIO.readBlock(0, base, (limit - base) + 1, (char*)buffer); // TODO: Change first param to this->id memmove(buf, buffer + start, size); free(buffer); return true; // TODO: Check operation worked } bool ATAPIODrive_t::write(uint64_t addr, uint64_t size, uint8_t* buf) { uint64_t base = floor((float)addr / 512.0f); uint64_t limit = floor((float)(addr + size) / 512.0f); uint64_t start = addr % 512; uint8_t* buffer = (uint8_t*)malloc(((limit - base) + 1) * 512); Terminal.println(itoa(base, 10)); Terminal.println(itoa(limit, 10)); Terminal.println(itoa(start, 10)); Terminal.println(itoa((limit - base) + 1, 10)); ATAPIO.readBlock(0, base, (limit - base) + 2, (char*)buffer); // TODO: Change first param to this->id memmove(buffer + start, buf, size); Terminal.println((char*)(buffer + start)); ATAPIO.writeBlock(0, base, (limit - base) + 2, (char*)buffer); free(buffer); return true; // TODO: Check operation worked }
30.769912
105
0.594478
AlexandreRouma
4a3e45cd3350182fe9ca330ca756eb52f734974c
542
cpp
C++
CODEFORCES/A Variety of Operations.cpp
HassanRahim26/COMPETITIVE-PROGRAMMING
a2d13fd27cc5e3e78612a5be500ccbe57f9201b8
[ "MIT" ]
2
2021-07-31T15:40:56.000Z
2021-08-25T10:04:00.000Z
CODEFORCES/A Variety of Operations.cpp
HassanRahim26/COMPETITIVE-PROGRAMMING
a2d13fd27cc5e3e78612a5be500ccbe57f9201b8
[ "MIT" ]
null
null
null
CODEFORCES/A Variety of Operations.cpp
HassanRahim26/COMPETITIVE-PROGRAMMING
a2d13fd27cc5e3e78612a5be500ccbe57f9201b8
[ "MIT" ]
null
null
null
/* PROBLEM LINK:- https://codeforces.com/contest/1556/problem/A */ #include<bits/stdc++.h> #define ll long long #define test ll t; cin >> t; while(t--) #define FOR for(ll i = 0; i < n; i++) #define nn "\n" using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); test { ll c, d; cin >> c >> d; if (c == 0 && d == 0) { cout << 0 << nn; } else if (c == d) { cout << 1 << nn; } else if (abs(c - d) % 2 == 0) { cout << 2 << nn; } else cout << -1 << nn; } return 0; }
13.219512
60
0.501845
HassanRahim26
4a3f1f7238bbdc56a6e45a83b273e5acaf6bc026
1,097
hpp
C++
libs/fnd/memory/include/bksge/fnd/memory/uninitialized_move_n.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/memory/include/bksge/fnd/memory/uninitialized_move_n.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/memory/include/bksge/fnd/memory/uninitialized_move_n.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file uninitialized_move_n.hpp * * @brief uninitialized_move_n を定義 * * @author myoukaku */ #ifndef BKSGE_FND_MEMORY_UNINITIALIZED_MOVE_N_HPP #define BKSGE_FND_MEMORY_UNINITIALIZED_MOVE_N_HPP #include <memory> #if defined(__cpp_lib_raw_memory_algorithms) && (__cpp_lib_raw_memory_algorithms >= 201606) namespace bksge { using std::uninitialized_move_n; } // namespace bksge #else #include <bksge/fnd/memory/uninitialized_copy.hpp> #include <bksge/fnd/memory/detail/uninitialized_copy_n_pair.hpp> #include <bksge/fnd/iterator/make_move_iterator.hpp> #include <bksge/fnd/pair.hpp> namespace bksge { template <typename InputIterator, typename Size, typename ForwardIterator> inline bksge::pair<InputIterator, ForwardIterator> uninitialized_move_n(InputIterator first, Size count, ForwardIterator result) { auto res = detail::uninitialized_copy_n_pair( bksge::make_move_iterator(first), count, result); return { res.first.base(), res.second }; } } // namespace bksge #endif #endif // BKSGE_FND_MEMORY_UNINITIALIZED_MOVE_N_HPP
23.340426
92
0.760255
myoukaku
4a4adba259cc54dc848451b024418c2db57ea1e9
8,521
cpp
C++
csapex_vision/src/mask_refinement_adapter.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
2
2016-09-02T15:33:22.000Z
2019-05-06T22:09:33.000Z
csapex_vision/src/mask_refinement_adapter.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
1
2021-02-14T19:53:30.000Z
2021-02-14T19:53:30.000Z
csapex_vision/src/mask_refinement_adapter.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
6
2016-10-12T00:55:23.000Z
2021-02-10T17:49:25.000Z
/// HEADER #include "mask_refinement_adapter.h" /// PROJECT #include <csapex/model/node_facade_impl.h> #include <csapex/msg/io.h> #include <csapex/view/utility/register_node_adapter.h> #include <csapex/utility/yaml.h> /// SYSTEM #include <QBitmap> #include <QCheckBox> #include <QGraphicsPixmapItem> #include <QGraphicsSceneEvent> #include <QPainter> #include <QPushButton> using namespace csapex; CSAPEX_REGISTER_LOCAL_NODE_ADAPTER(MaskRefinementAdapter, csapex::MaskRefinement) MaskRefinementAdapter::MaskRefinementAdapter(NodeFacadeImplementationPtr worker, NodeBox* parent, std::weak_ptr<MaskRefinement> node) : DefaultNodeAdapter(worker, parent), wrapped_(node), view_(new QGraphicsView), refresh_(false), brush_size_(1) { auto n = wrapped_.lock(); // translate to UI thread via Qt signal observe(n->next_image, this, &MaskRefinementAdapter::nextRequest); observe(n->update_brush, this, &MaskRefinementAdapter::updateBrushRequest); observe(n->input, std::bind(&MaskRefinementAdapter::inputRequest, this, std::placeholders::_1, std::placeholders::_2)); QObject::connect(this, SIGNAL(nextRequest()), this, SLOT(next())); QObject::connect(this, SIGNAL(inputRequest(QImage, QImage)), this, SLOT(setMask(QImage, QImage))); QObject::connect(this, SIGNAL(updateBrushRequest()), this, SLOT(updateBrush())); } MaskRefinementAdapter::~MaskRefinementAdapter() { } GenericStatePtr MaskRefinementAdapter::getState() const { return std::shared_ptr<State>(new State(state)); } void MaskRefinementAdapter::setParameterState(GenericStatePtr memento) { std::shared_ptr<State> m = std::dynamic_pointer_cast<State>(memento); apex_assert(m.get()); state = *m; view_->setFixedSize(QSize(state.width, state.height)); } void MaskRefinementAdapter::setupUi(QBoxLayout* layout) { QGraphicsScene* scene = view_->scene(); if (scene == nullptr) { scene = new QGraphicsScene(); view_->setScene(scene); scene->installEventFilter(this); view_->installEventFilter(this); } mask_pixmap_ = new QGraphicsPixmapItem; masked_red_pixmap_ = new QGraphicsPixmapItem; masked_bw_pixmap_ = new QGraphicsPixmapItem; view_->scene()->addItem(mask_pixmap_); view_->scene()->addItem(masked_red_pixmap_); view_->scene()->addItem(masked_bw_pixmap_); view_->setContextMenuPolicy(Qt::PreventContextMenu); view_->setMouseTracking(true); cursor_ = new QGraphicsEllipseItem; cursor_->setPen(QPen(Qt::red, 1)); view_->scene()->addItem(cursor_); layout->addWidget(view_); DefaultNodeAdapter::setupUi(layout); } bool MaskRefinementAdapter::eventFilter(QObject* o, QEvent* e) { auto node = wrapped_.lock(); if (!node) { return false; } QGraphicsSceneMouseEvent* me = dynamic_cast<QGraphicsSceneMouseEvent*>(e); switch (e->type()) { case QEvent::KeyPress: { break; } case QEvent::Resize: { if (refresh_) { fitView(); refresh_ = false; } return false; } case QEvent::GraphicsSceneMousePress: if (me->button() == Qt::MiddleButton) { middle_last_pos_ = me->screenPos(); } else if (me->button() == Qt::LeftButton) { draw(me->scenePos(), Qt::white); } else if (me->button() == Qt::RightButton) { draw(me->scenePos(), Qt::black); } e->accept(); return true; case QEvent::GraphicsSceneMouseRelease: { e->accept(); return true; } case QEvent::GraphicsSceneMouseMove: if (me->buttons() & Qt::MiddleButton) { auto scene = view_->scene(); if (!scene) { return false; } QPoint delta = me->screenPos() - middle_last_pos_; middle_last_pos_ = me->screenPos(); state.width = std::max(32, view_->width() + delta.x()); state.height = std::max(32, view_->height() + delta.y()); view_->setFixedSize(QSize(state.width, state.height)); refresh_ = true; e->accept(); } else if (me->buttons() & Qt::LeftButton) { draw(me->scenePos(), Qt::white); } else if (me->buttons() & Qt::RightButton) { draw(me->scenePos(), Qt::black); } updateCursor(me->scenePos()); return true; break; case QEvent::GraphicsSceneWheel: { e->accept(); QGraphicsSceneWheelEvent* we = dynamic_cast<QGraphicsSceneWheelEvent*>(e); int delta = we->delta() > 0 ? 1 : -1; brush_size_ = std::max(1, std::min(64, brush_size_ + delta)); node->setParameter<int>("brush/size", brush_size_); updateCursor(we->scenePos()); return true; } default: break; } return false; } void MaskRefinementAdapter::maskImage() { if (masked_red_pixmap_->isVisible()) { masked_red_pm_ = QPixmap::fromImage(img_); QPainter img_painter_red(&masked_red_pm_); img_painter_red.setClipRegion(QRegion(QBitmap(mask_pm_))); img_painter_red.fillRect(masked_red_pm_.rect(), QBrush(QColor(255, 0, 0, 128))); masked_red_pixmap_->setPixmap(masked_red_pm_); masked_red_pixmap_->setPos(0, mask_pixmap_->boundingRect().height()); masked_bw_pm_ = QPixmap::fromImage(img_); QPainter img_painter_black(&masked_bw_pm_); img_painter_black.setClipRegion(QRegion(QBitmap(mask_pm_))); img_painter_black.fillRect(masked_bw_pm_.rect(), QBrush(QColor(0, 0, 0, 255))); masked_bw_pixmap_->setPixmap(masked_bw_pm_); masked_bw_pixmap_->setPos(mask_pixmap_->boundingRect().width(), 0); } } void MaskRefinementAdapter::draw(const QPointF& pos, Qt::GlobalColor color) { double x = pos.x(); double y = pos.y(); auto bound = mask_pixmap_->boundingRect(); double w = bound.width(); double h = bound.height(); if (x >= w) { x -= w; } if (y >= h) { y -= h; } QPainter painter(&mask_); painter.setRenderHint(QPainter::Antialiasing, false); QPen pen(color, 1); painter.setPen(pen); QBrush brush(color); painter.setBrush(brush); int r = std::max(1, brush_size_ / 2); painter.drawEllipse(x - r / 2, y - r / 2, r, r); painter.end(); mask_pm_ = QPixmap::fromImage(mask_); mask_pixmap_->setPixmap(mask_pm_); maskImage(); mask_pixmap_->setZValue(0.0); cursor_->setZValue(1.0); view_->update(); } void MaskRefinementAdapter::updateCursor(const QPointF& pos) { double x = pos.x(); double y = pos.y(); if (x < 0) x = 0; if (y < 0) y = 0; double w = mask_pixmap_->boundingRect().width() + masked_bw_pixmap_->boundingRect().width(); double h = mask_pixmap_->boundingRect().height() + masked_red_pixmap_->boundingRect().height(); if (x >= w) x = w; if (y >= h) y = h; int r = std::max(1, brush_size_ / 2); cursor_->setRect(x - r / 2, y - r / 2, r, r); cursor_->update(); view_->update(); } void MaskRefinementAdapter::setMask(QImage mask, QImage masked) { auto node = wrapped_.lock(); if (!node) { return; } updateBrush(); mask_ = mask; mask_pm_ = QPixmap::fromImage(mask_); mask_pixmap_->setPixmap(mask_pm_); if (masked.isNull()) { masked_red_pixmap_->hide(); } else { img_ = masked; masked_red_pixmap_->show(); masked_bw_pixmap_->show(); maskImage(); } fitView(); } void MaskRefinementAdapter::fitView() { view_->setFixedSize(QSize(state.width, state.height)); QRectF rect = mask_pixmap_->sceneBoundingRect(); rect |= masked_red_pixmap_->sceneBoundingRect(); rect |= masked_bw_pixmap_->sceneBoundingRect(); view_->fitInView(rect, Qt::KeepAspectRatio); view_->update(); } void MaskRefinementAdapter::next() { auto node = wrapped_.lock(); if (!node) { return; } node->setMask(mask_); } void MaskRefinementAdapter::updateBrush() { auto node = wrapped_.lock(); if (!node) { return; } brush_size_ = node->readParameter<int>("brush/size"); } /// MOC #include "moc_mask_refinement_adapter.cpp"
26.711599
133
0.614012
AdrianZw
4a4ea905e5b07c7c4321419f6c5eaf44dee047a6
2,384
cpp
C++
nrf52-remote-display/src/display.cpp
chacal/arduino
6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd
[ "Apache-2.0" ]
4
2016-12-10T13:20:52.000Z
2019-10-25T19:47:44.000Z
nrf52-remote-display/src/display.cpp
chacal/arduino
6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd
[ "Apache-2.0" ]
null
null
null
nrf52-remote-display/src/display.cpp
chacal/arduino
6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd
[ "Apache-2.0" ]
1
2019-05-03T17:31:38.000Z
2019-05-03T17:31:38.000Z
#include "display.hpp" #define CONTRAST 230 display::display() { u8g2_Setup_st7565_nhd_c12864_f(&u8g2, U8G2_R0, adapter.u8x8_byte_nrf52_hw_spi, adapter.u8x8_gpio_and_delay_nrf52); u8g2_InitDisplay(&u8g2); u8g2_SetContrast(&u8g2, CONTRAST); u8g2_SetFont(&u8g2, u8g2_font_helvB10_tr); u8g2_ClearDisplay(&u8g2); } void display::on() { clear(); render(); u8g2_SetPowerSave(&u8g2, 0); } void display::off() { u8g2_SetPowerSave(&u8g2, 1); } static const uint8_t *font_for_size(const font_size &size) { if (size.get() <= 8) { return u8g2_font_helvB08_tr; } else if (size.get() <= 10) { return u8g2_font_helvB10_tr; } else if (size.get() <= 12) { return u8g2_font_helvB12_tr; } else if (size.get() <= 14) { return u8g2_font_helvB14_tr; } else if (size.get() <= 18) { return u8g2_font_helvB18_tr; } else if (size.get() <= 24) { return u8g2_font_helvB24_tr; } else if (size.get() <= 25) { return u8g2_font_fub25_tn; } else if (size.get() <= 30) { return u8g2_font_fub30_tn; } else if (size.get() <= 35) { return u8g2_font_fub35_tn; } else { return u8g2_font_fub42_tn; } } void display::draw_str(const point &bottom_left, const font_size &size, const std::string &str) { const uint8_t *font = font_for_size(size); u8g2_SetFont(&u8g2, font); u8g2_DrawStr(&u8g2, bottom_left.x, bottom_left.y, str.c_str()); } void display::clear() { u8g2_ClearBuffer(&u8g2); } void display::clear_area(const point &upper_left, const width &w, const height &h) { auto color = u8g2_GetDrawColor(&u8g2); u8g2_SetDrawColor(&u8g2, 0); draw_box(upper_left, w, h); u8g2_SetDrawColor(&u8g2, color); } void display::draw_line(const point &start, const point &end) { u8g2_DrawLine(&u8g2, start.x, start.y, end.x, end.y); } void display::draw_box(const point &upper_left, const width &w, const height &h) { u8g2_DrawBox(&u8g2, upper_left.x, upper_left.y, w.get(), h.get()); } void display::draw_frame(const point &upper_left, const width &w, const height &h) { u8g2_DrawFrame(&u8g2, upper_left.x, upper_left.y, w.get(), h.get()); } void display::render() { u8g2_SendBuffer(&u8g2); } uint8_t display::centered_x(const std::string &str, const font_size &size) { u8g2_SetFont(&u8g2, font_for_size(size)); int x = SCREEN_WIDTH / 2 - u8g2_GetStrWidth(&u8g2, str.c_str()) / 2; return x >= 0 ? x : 0; }
28.047059
116
0.685822
chacal
4a50eba294759c02582e9e879082281cc92b439c
451
cpp
C++
HackerRank/Contests/w21/kangaroo.cpp
Diggzinc/solutions-spoj
eb552311011e466039e059cce07894fea0817613
[ "MIT" ]
null
null
null
HackerRank/Contests/w21/kangaroo.cpp
Diggzinc/solutions-spoj
eb552311011e466039e059cce07894fea0817613
[ "MIT" ]
null
null
null
HackerRank/Contests/w21/kangaroo.cpp
Diggzinc/solutions-spoj
eb552311011e466039e059cce07894fea0817613
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <queue> #include <iostream> #include <algorithm> #include <bitset> using namespace std; bool isInt(double k) { return floor(abs(k)) == abs(k); } int main() { int x1, v1, x2, v2; cin >> x1 >> v1 >> x2 >> v2; double x = x1 - x2; double v = v2 - v1; if(v == 0 || x/v < 0 || !isInt(x / v)) { cout << "NO" << endl; } else { cout << "YES" << endl; } return EXIT_SUCCESS; }
13.666667
41
0.563193
Diggzinc
4a52365be3b5cff27095b4a86ff50a6f2be863fb
461
cpp
C++
NKZX_NOI_OJ/P1336.cpp
Rose2073/RoseCppSource
bdaf5de04049b07bbe0e1ef976d1fbe72520fa03
[ "Apache-2.0" ]
1
2021-04-05T16:26:00.000Z
2021-04-05T16:26:00.000Z
NKZX_NOI_OJ/P1336.cpp
Rose2073/RoseCppSource
bdaf5de04049b07bbe0e1ef976d1fbe72520fa03
[ "Apache-2.0" ]
null
null
null
NKZX_NOI_OJ/P1336.cpp
Rose2073/RoseCppSource
bdaf5de04049b07bbe0e1ef976d1fbe72520fa03
[ "Apache-2.0" ]
null
null
null
#include<cstdio> int v[101][101]; int main(){ int n,i=2,x=1,y=0; scanf("%d",&n); v[0][0]=1; while(i<n*n){ while(x>=0&&y<n) v[y++][x--]=i++;x++; if(y==n){ y--;x++; } while(x<n&&y>=0) v[y--][x++]=i++;y++; if(x==n){ x--;y++; } } for(int v1=0;v1<n;v1++){ for(int v2=0;v2<n;v2++) printf("%5d",v[v1][v2]); putchar('\n'); } return 0; }
19.208333
45
0.336226
Rose2073
4a52f9fba070f9abd284f2514ddec9f6b5fd4445
2,124
cpp
C++
Algorithms/Dijkstra.cpp
utkarsh-1997/Code-Repo
47786ae93a7b8cea100b7b7e6478f10403c33baa
[ "MIT" ]
null
null
null
Algorithms/Dijkstra.cpp
utkarsh-1997/Code-Repo
47786ae93a7b8cea100b7b7e6478f10403c33baa
[ "MIT" ]
null
null
null
Algorithms/Dijkstra.cpp
utkarsh-1997/Code-Repo
47786ae93a7b8cea100b7b7e6478f10403c33baa
[ "MIT" ]
null
null
null
// Remmber that Dijkstra's algorithm works only for positive weights. #include<bits/stdc++.h> using namespace std; void findShortestDistances(int N, int start_node, int shortestDistance[], vector<pair<int, int>> graph[]) { priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> Q; bool visited[N] = {}; // Instead of initializing distances to a "MAX" value we make use of a bool variable which checks whether the node is being visited for the first time visited[start_node] = 1; Q.push(make_pair(0, start_node)); while(!Q.empty()) { pair<int, int> P = Q.top(); Q.pop(); int curnode = P.second, curdistance = P.first; for(int i = 0; i < graph[curnode].size(); i++) { int neighbour = graph[curnode][i].second, cost = graph[curnode][i].first; if(visited[neighbour] == 1) { if(cost + curdistance < shortestDistance[neighbour]) { shortestDistance[neighbour] = cost + curdistance; Q.push(make_pair(shortestDistance[neighbour], neighbour)); } } else { shortestDistance[neighbour] = cost + curdistance; visited[neighbour] = 1; Q.push(make_pair(shortestDistance[neighbour], neighbour)); } } } for(int i = 0; i < N; i++) { if(!visited[i]) shortestDistance[i] = -1; //This node wasn't reachable! } } // Undirected graph. Graph input format: First take N - number of nodes (labelled from 0 to N-1) and M - number of edges. // Then, M lines where inputs are u, v and c, denoting an edge between u and v with weight c. int main() { int N, M; cin>>N>>M; vector<pair<int, int>> graph[N]; int u, v, c; for(int i = 0; i < M; i++) { cin>>u>>v>>c; graph[u].push_back(make_pair(c, v)); graph[v].push_back(make_pair(c, u)); } // The node where we will start from. int start_node; cin>>start_node; int shortestDistance[N]; shortestDistance[start_node] = 0; // Naturally findShortestDistances(N, start_node, shortestDistance, graph); cout<<"Printing the shortest distance of each node from starting node = "<<start_node<<"\n"; for(int i = 0; i < N; i++) cout<<shortestDistance[i]<<" "; cout<<"\n"; return 0; }
30.342857
173
0.6629
utkarsh-1997
4a55c0cf89909f5b27f1b7304408ce2e2de08c95
8,605
cc
C++
wrappers/8.1.1/vtkXMLUnstructuredDataWriterWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkXMLUnstructuredDataWriterWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkXMLUnstructuredDataWriterWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkXMLWriterWrap.h" #include "vtkXMLUnstructuredDataWriterWrap.h" #include "vtkObjectBaseWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkXMLUnstructuredDataWriterWrap::ptpl; VtkXMLUnstructuredDataWriterWrap::VtkXMLUnstructuredDataWriterWrap() { } VtkXMLUnstructuredDataWriterWrap::VtkXMLUnstructuredDataWriterWrap(vtkSmartPointer<vtkXMLUnstructuredDataWriter> _native) { native = _native; } VtkXMLUnstructuredDataWriterWrap::~VtkXMLUnstructuredDataWriterWrap() { } void VtkXMLUnstructuredDataWriterWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkXMLUnstructuredDataWriter").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("XMLUnstructuredDataWriter").ToLocalChecked(), ConstructorGetter); } void VtkXMLUnstructuredDataWriterWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkXMLUnstructuredDataWriterWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkXMLWriterWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkXMLWriterWrap::ptpl)); tpl->SetClassName(Nan::New("VtkXMLUnstructuredDataWriterWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "GetGhostLevel", GetGhostLevel); Nan::SetPrototypeMethod(tpl, "getGhostLevel", GetGhostLevel); Nan::SetPrototypeMethod(tpl, "GetNumberOfPieces", GetNumberOfPieces); Nan::SetPrototypeMethod(tpl, "getNumberOfPieces", GetNumberOfPieces); Nan::SetPrototypeMethod(tpl, "GetWritePiece", GetWritePiece); Nan::SetPrototypeMethod(tpl, "getWritePiece", GetWritePiece); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetGhostLevel", SetGhostLevel); Nan::SetPrototypeMethod(tpl, "setGhostLevel", SetGhostLevel); Nan::SetPrototypeMethod(tpl, "SetNumberOfPieces", SetNumberOfPieces); Nan::SetPrototypeMethod(tpl, "setNumberOfPieces", SetNumberOfPieces); Nan::SetPrototypeMethod(tpl, "SetWritePiece", SetWritePiece); Nan::SetPrototypeMethod(tpl, "setWritePiece", SetWritePiece); #ifdef VTK_NODE_PLUS_VTKXMLUNSTRUCTUREDDATAWRITERWRAP_INITPTPL VTK_NODE_PLUS_VTKXMLUNSTRUCTUREDDATAWRITERWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkXMLUnstructuredDataWriterWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { Nan::ThrowError("Cannot create instance of abstract class."); return; } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkXMLUnstructuredDataWriterWrap::GetGhostLevel(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLUnstructuredDataWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLUnstructuredDataWriterWrap>(info.Holder()); vtkXMLUnstructuredDataWriter *native = (vtkXMLUnstructuredDataWriter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetGhostLevel(); info.GetReturnValue().Set(Nan::New(r)); } void VtkXMLUnstructuredDataWriterWrap::GetNumberOfPieces(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLUnstructuredDataWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLUnstructuredDataWriterWrap>(info.Holder()); vtkXMLUnstructuredDataWriter *native = (vtkXMLUnstructuredDataWriter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetNumberOfPieces(); info.GetReturnValue().Set(Nan::New(r)); } void VtkXMLUnstructuredDataWriterWrap::GetWritePiece(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLUnstructuredDataWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLUnstructuredDataWriterWrap>(info.Holder()); vtkXMLUnstructuredDataWriter *native = (vtkXMLUnstructuredDataWriter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetWritePiece(); info.GetReturnValue().Set(Nan::New(r)); } void VtkXMLUnstructuredDataWriterWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLUnstructuredDataWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLUnstructuredDataWriterWrap>(info.Holder()); vtkXMLUnstructuredDataWriter *native = (vtkXMLUnstructuredDataWriter *)wrapper->native.GetPointer(); vtkXMLUnstructuredDataWriter * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkXMLUnstructuredDataWriterWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkXMLUnstructuredDataWriterWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkXMLUnstructuredDataWriterWrap *w = new VtkXMLUnstructuredDataWriterWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkXMLUnstructuredDataWriterWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLUnstructuredDataWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLUnstructuredDataWriterWrap>(info.Holder()); vtkXMLUnstructuredDataWriter *native = (vtkXMLUnstructuredDataWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkXMLUnstructuredDataWriter * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkXMLUnstructuredDataWriterWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkXMLUnstructuredDataWriterWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkXMLUnstructuredDataWriterWrap *w = new VtkXMLUnstructuredDataWriterWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLUnstructuredDataWriterWrap::SetGhostLevel(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLUnstructuredDataWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLUnstructuredDataWriterWrap>(info.Holder()); vtkXMLUnstructuredDataWriter *native = (vtkXMLUnstructuredDataWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetGhostLevel( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLUnstructuredDataWriterWrap::SetNumberOfPieces(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLUnstructuredDataWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLUnstructuredDataWriterWrap>(info.Holder()); vtkXMLUnstructuredDataWriter *native = (vtkXMLUnstructuredDataWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetNumberOfPieces( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLUnstructuredDataWriterWrap::SetWritePiece(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLUnstructuredDataWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLUnstructuredDataWriterWrap>(info.Holder()); vtkXMLUnstructuredDataWriter *native = (vtkXMLUnstructuredDataWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetWritePiece( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); }
33.352713
121
0.756886
axkibe
4a55cc0a557590cb1dd5f9c3ef87a5a2bbe8265c
10,300
cpp
C++
ExodusImport/Source/ExodusImport/Private/JsonImporter/Texture.cpp
SergeyKarpushin/ProjectExodus
8ab1212de91d9b6f983bf98a06d26bba52381b0a
[ "BSD-3-Clause" ]
null
null
null
ExodusImport/Source/ExodusImport/Private/JsonImporter/Texture.cpp
SergeyKarpushin/ProjectExodus
8ab1212de91d9b6f983bf98a06d26bba52381b0a
[ "BSD-3-Clause" ]
null
null
null
ExodusImport/Source/ExodusImport/Private/JsonImporter/Texture.cpp
SergeyKarpushin/ProjectExodus
8ab1212de91d9b6f983bf98a06d26bba52381b0a
[ "BSD-3-Clause" ]
null
null
null
#include "JsonImportPrivatePCH.h" #include "JsonImporter.h" #include "Engine/TextureCube.h" #include "Factories/TextureFactory.h" #include "UnrealUtilities.h" #include "AssetRegistryModule.h" #include "JsonObjects.h" using namespace UnrealUtilities; UTextureCube* JsonImporter::getCubemap(int32 id) const{ if (id < 0) return 0; return loadCubemap(id); } UTextureCube* JsonImporter::loadCubemap(int32 id) const{ return staticLoadResourceById<UTextureCube>(cubeIdMap, id, TEXT("cubemap")); } bool loadTextureData(ByteArray &outData, const FString &path){ FString fileSystemPath = path; FString ext = FPaths::GetExtension(fileSystemPath); if (ext.ToLower() == FString("tif")){ UE_LOG(JsonLog, Warning, TEXT("TIF image extension found! Fixing it to png: %s. Image will fail to load if no png file is present."), *fileSystemPath); ext = FString("png"); FString pathPart, namePart, extPart; FPaths::Split(fileSystemPath, pathPart, namePart, extPart); FString newBaseName = FString::Printf(TEXT("%s.%s"), *namePart, *ext); fileSystemPath = FPaths::Combine(*pathPart, *newBaseName); UE_LOG(JsonLog, Warning, TEXT("New path: %s"), *fileSystemPath); } if (!FFileHelper::LoadFileToArray(outData, *fileSystemPath)){ UE_LOG(JsonLog, Warning, TEXT("Could not load file \"%s\""), *fileSystemPath); return false; } if (outData.Num() <= 0){ UE_LOG(JsonLog, Warning, TEXT("No binary data in \"%s\""), *fileSystemPath); return false; } return true; } struct SrcPixel32{ uint8 r, g, b, a; }; struct SrcPixel32F{ float r, g, b, a; }; struct DstPixel16F{ FFloat16 b, g, r, a; }; #if 0 //Well, this doesn't work so I give up. static bool loadCompressedBinary(ByteArray &outData, const FString &filename){ ByteArray tmpData; if (!FFileHelper::LoadFileToArray(tmpData, *filename)){ UE_LOG(JsonLog, Error, TEXT("Could not load data from \"%s\""), *filename); return false; } const auto dataPtr = tmpData.GetData(); int32 dstSize = *((int32*)dataPtr); auto headerSize = sizeof(dstSize); int32 srcSize = tmpData.Num() - headerSize; outData.SetNumUninitialized(dstSize ); const auto srcPtr = dataPtr + headerSize; auto dstPtr = outData.GetData(); #if 0 return FCompression::UncompressMemory( #if (ENGINE_MAJOR_VERSION >= 4) && (ENGINE_MINOR_VERSION >= 22) NAME_Zlib, #else COMPRESS_ZLIB, #endif dstPtr, dstSize, srcPtr, srcSize, false, DEFAULT_ZLIB_BIT_WINDOW|32 //This is black magic needed to make FCompression treat the stream as gzip stream. ); #endif //Alright, this is really ugly. We're basically relying on hidden functionality in order to read GZipStream here, and it is only used for cubemap textures /* return FCompression::UncompressMemory( COMPRESS_ZLIB, dstPtr, dstSize, srcPtr, srcSize, false, DEFAULT_ZLIB_BIT_WINDOW | 32 //This is black magic needed to make FCompression treat the stream as gzip stream. ); */ return FCompression::UncompressMemory( COMPRESS_ZLIB, dstPtr, dstSize, srcPtr, srcSize, false, DEFAULT_ZLIB_BIT_WINDOW //This is black magic needed to make FCompression treat the stream as gzip stream. ); //return true; } #endif void JsonImporter::importCubemap(JsonObjPtr data, const FString &rootPath){ JsonCubemap jsonCube(data); UE_LOG(JsonLog, Log, TEXT("Cubemap: %d, %s, %s (%s), %dx%d"), jsonCube.id, *jsonCube.name, *jsonCube.assetPath, *jsonCube.exportPath, jsonCube.texParams.width, jsonCube.texParams.height); UTextureCube* existingTexture = 0; FString ext = FPaths::GetExtension(jsonCube.exportPath); UE_LOG(JsonLog, Log, TEXT("filename: %s, ext: %s, assetRootPath: %s"), *jsonCube.assetPath, *ext, *rootPath); FString textureName; FString packageName; UPackage *texturePackage = createPackage(jsonCube.name, jsonCube.assetPath, rootPath, FString("TextureCube"), &packageName, &textureName, &existingTexture); if (existingTexture){ cubeIdMap.Add(jsonCube.id, existingTexture->GetPathName()); UE_LOG(JsonLog, Warning, TEXT("Cube texture %s already exists, package %s"), *textureName, *packageName); return; } ByteArray binaryData; //well, unreal can't load 2d images for cubemaps. So, raw data is the way to go auto fullRawPath = FPaths::Combine(*assetRootPath, *jsonCube.rawPath); #if 0 if (!loadCompressedBinary(binaryData, fullRawPath)){ UE_LOG(JsonLog, Error, TEXT("Could not load compressed data from \"%s\""), *fullRawPath); return; } #else if (!FFileHelper::LoadFileToArray(binaryData, *fullRawPath)){ UE_LOG(JsonLog, Error, TEXT("Could not load data from \"%s\""), *fullRawPath); return; } #endif auto texFab = makeFactoryRootPtr<UTextureFactory>(); texFab->SuppressImportOverwriteDialog(); //const uint8* data = binaryData.GetData(); auto cubeSize = jsonCube.texParams.width; UE_LOG(JsonLog, Log, TEXT("Attempting to create package: texName %s"), *jsonCube.name); UTextureCube *cubeTex = texFab->CreateTextureCube(texturePackage, *textureName, RF_Standalone|RF_Public); ETextureSourceFormat sourceFormat = jsonCube.isHdr ? TSF_RGBA16F: TSF_BGRA8; // cubeTex->Source.Init(cubeSize, cubeSize, 6, 1, sourceFormat); cubeTex->Source.Init(cubeSize, cubeSize, 6, 1, sourceFormat); if (jsonCube.isHdr){ cubeTex->CompressionSettings = TC_HDR; } auto* lockedMip = cubeTex->Source.LockMip(0); const auto numSlices = 6; if (jsonCube.isHdr){ const SrcPixel32F *srcData = (SrcPixel32F*)binaryData.GetData(); DstPixel16F *dstData = (DstPixel16F*)lockedMip; for(int slice = 0; slice < numSlices; slice++){ auto srcSlice = srcData + cubeSize * cubeSize * slice; auto dstSlice = dstData + cubeSize * cubeSize * slice; for(int y = 0; y < cubeSize; y++){ auto srcScan = srcSlice + y * cubeSize; auto dstScan = dstSlice + y * cubeSize; for(int x = 0; x < cubeSize; x++){ dstScan[x].r.Set(srcScan[x].r); dstScan[x].g.Set(srcScan[x].g); dstScan[x].b.Set(srcScan[x].b); dstScan[x].a.Set(srcScan[x].a); //dstScan[x] = srcScan[x]; } } } } else{ const SrcPixel32 *srcData = (SrcPixel32*)binaryData.GetData(); SrcPixel32 *dstData = (SrcPixel32*)lockedMip; auto sliceSize = cubeSize * cubeSize; for(int slice = 0; slice < numSlices; slice++){ auto srcSlice = srcData + sliceSize * slice; auto dstSlice = dstData + sliceSize * slice; for(int y = 0; y < cubeSize; y++){ auto srcScan = srcSlice + y * cubeSize; auto dstScan = dstSlice + y * cubeSize; for(int x = 0; x < cubeSize; x++){ dstScan[x] = srcScan[x]; } } } } cubeTex->SRGB = jsonCube.texImportParams.initialized && jsonCube.texImportParams.sRGBTexture; //texture mipmap generation is not supported for cubemaps? cubeTex->Source.UnlockMip(0); cubeTex->MipGenSettings = TMGS_Blur1;//TMGS_NoMipmaps;//TMGS_LeaveExistingMips; //cubeTex->Source. if (cubeTex){ cubeIdMap.Add(jsonCube.id, cubeTex->GetPathName()); cubeTex->PostEditChange(); FAssetRegistryModule::AssetCreated(cubeTex); texturePackage->SetDirtyFlag(true); } } UTexture* JsonImporter::getTexture(int32 id) const{ if (id < 0) return 0; return loadTexture(id); } UTexture* JsonImporter::loadTexture(int32 id) const{ return staticLoadResourceById<UTexture>(texIdMap, id, TEXT("texture")); } void JsonImporter::importTexture(JsonObjPtr obj, const FString &rootPath){ JsonTexture jsonTex(obj); importTexture(jsonTex, rootPath); } void JsonImporter::importTexture(const JsonTexture &jsonTex, const FString &rootPath){ UE_LOG(JsonLog, Log, TEXT("Texture: %s, %s, %d x %d"), *jsonTex.path, *jsonTex.name, jsonTex.width, jsonTex.height); bool isNormalMap = false; if (jsonTex.importDataFound && jsonTex.normalMapFlag){ isNormalMap = true; } else{ isNormalMap = jsonTex.name.EndsWith(FString("_n")) || jsonTex.name.EndsWith(FString("Normals")); } if (isNormalMap){ UE_LOG(JsonLog, Log, TEXT("Texture recognized as normalmap: %s(%s)"), *jsonTex.name, *jsonTex.path); } UTexture* existingTexture = 0; FString ext = FPaths::GetExtension(jsonTex.path); UE_LOG(JsonLog, Log, TEXT("filename: %s, ext: %s, assetRootPath: %s"), *jsonTex.path, *ext, *rootPath); FString textureName; FString packageName; UPackage *texturePackage = createPackage(jsonTex.name, jsonTex.path, rootPath, FString("Texture"), &packageName, &textureName, &existingTexture); if (existingTexture){ texIdMap.Add(jsonTex.id, existingTexture->GetPathName()); UE_LOG(JsonLog, Warning, TEXT("Texutre %s already exists, package %s"), *textureName, *packageName); return; } TArray<uint8> binaryData; FString fileSystemPath = FPaths::Combine(*assetRootPath, *jsonTex.path); if (ext.ToLower() == FString("tif")){ UE_LOG(JsonLog, Warning, TEXT("TIF image extension found! Fixing it to png: %s. Image will fail to load if no png file is present."), *fileSystemPath); ext = FString("png"); FString pathPart, namePart, extPart; FPaths::Split(fileSystemPath, pathPart, namePart, extPart); FString newBaseName = FString::Printf(TEXT("%s.%s"), *namePart, *ext); fileSystemPath = FPaths::Combine(*pathPart, *newBaseName); UE_LOG(JsonLog, Warning, TEXT("New path: %s"), *fileSystemPath); } if (!FFileHelper::LoadFileToArray(binaryData, *fileSystemPath)){ UE_LOG(JsonLog, Warning, TEXT("Could not load texture %s(%s)"), *jsonTex.name, *jsonTex.path); return; } if (binaryData.Num() <= 0){ UE_LOG(JsonLog, Warning, TEXT("No binary data: %s"), *jsonTex.name); return; } UE_LOG(JsonLog, Log, TEXT("Loading tex data: %s (%d bytes)"), *jsonTex.name, binaryData.Num()); auto texFab = NewObject<UTextureFactory>(); texFab->AddToRoot(); texFab->SuppressImportOverwriteDialog(); const uint8* data = binaryData.GetData(); if (isNormalMap){ texFab->LODGroup = TEXTUREGROUP_WorldNormalMap; texFab->CompressionSettings = TC_Normalmap; //texFab->bFlipNormalMapGreenChannel = true; } UE_LOG(JsonLog, Log, TEXT("Attempting to create package: texName %s"), *jsonTex.name); UTexture *unrealTexture = (UTexture*)texFab->FactoryCreateBinary( UTexture2D::StaticClass(), texturePackage, *textureName, RF_Standalone|RF_Public, 0, *ext, data, data + binaryData.Num(), GWarn); if (unrealTexture){ texIdMap.Add(jsonTex.id, unrealTexture->GetPathName()); FAssetRegistryModule::AssetCreated(unrealTexture); texturePackage->SetDirtyFlag(true); } texFab->RemoveFromRoot(); }
33.441558
155
0.719806
SergeyKarpushin
4a682ceac4b51309d41d056459f3f2f337c6f3af
2,429
cpp
C++
src/kits/network/libnetapi/DatagramSocket.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
3
2018-05-21T15:32:32.000Z
2019-03-21T13:34:55.000Z
src/kits/network/libnetapi/DatagramSocket.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/kits/network/libnetapi/DatagramSocket.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
null
null
null
/* * Copyright 2011, Axel Dörfler, axeld@pinc-software.de. * Distributed under the terms of the MIT License. */ #include <DatagramSocket.h> //#define TRACE_SOCKET #ifdef TRACE_SOCKET # define TRACE(x...) printf(x) #else # define TRACE(x...) ; #endif BDatagramSocket::BDatagramSocket() { } BDatagramSocket::BDatagramSocket(const BNetworkAddress& peer, bigtime_t timeout) { Connect(peer, timeout); } BDatagramSocket::BDatagramSocket(const BDatagramSocket& other) : BAbstractSocket(other) { } BDatagramSocket::~BDatagramSocket() { } status_t BDatagramSocket::Bind(const BNetworkAddress& local) { return BAbstractSocket::Bind(local, SOCK_DGRAM); } status_t BDatagramSocket::Connect(const BNetworkAddress& peer, bigtime_t timeout) { return BAbstractSocket::Connect(peer, SOCK_DGRAM, timeout); } status_t BDatagramSocket::SetBroadcast(bool broadcast) { int value = broadcast ? 1 : 0; if (setsockopt(fSocket, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value)) != 0) return errno; return B_OK; } void BDatagramSocket::SetPeer(const BNetworkAddress& peer) { fPeer = peer; } size_t BDatagramSocket::MaxTransmissionSize() const { // TODO: might vary on family! return 32768; } ssize_t BDatagramSocket::SendTo(const BNetworkAddress& address, const void* buffer, size_t size) { ssize_t bytesSent = sendto(fSocket, buffer, size, 0, address, address.Length()); if (bytesSent < 0) return errno; return bytesSent; } ssize_t BDatagramSocket::ReceiveFrom(void* buffer, size_t bufferSize, BNetworkAddress& from) { socklen_t fromLength = sizeof(sockaddr_storage); ssize_t bytesReceived = recvfrom(fSocket, buffer, bufferSize, 0, from, &fromLength); if (bytesReceived < 0) return errno; return bytesReceived; } // #pragma mark - BDataIO implementation ssize_t BDatagramSocket::Read(void* buffer, size_t size) { ssize_t bytesReceived = recv(Socket(), buffer, size, 0); if (bytesReceived < 0) { TRACE("%p: BSocket::Read() error: %s\n", this, strerror(errno)); return errno; } return bytesReceived; } ssize_t BDatagramSocket::Write(const void* buffer, size_t size) { ssize_t bytesSent; if (!fIsConnected) bytesSent = sendto(Socket(), buffer, size, 0, fPeer, fPeer.Length()); else bytesSent = send(Socket(), buffer, size, 0); if (bytesSent < 0) { TRACE("%p: BDatagramSocket::Write() error: %s\n", this, strerror(errno)); return errno; } return bytesSent; }
17.47482
81
0.72499
stasinek
4a68390f3c06a0c32c5f73c1a44d7a8b2bb707bb
864
hpp
C++
tests/generator_extern.hpp
Je06jm/Matrin-Language
2aa440873f926c7fcd70e331b3619bbef5bdf5d9
[ "MIT" ]
null
null
null
tests/generator_extern.hpp
Je06jm/Matrin-Language
2aa440873f926c7fcd70e331b3619bbef5bdf5d9
[ "MIT" ]
null
null
null
tests/generator_extern.hpp
Je06jm/Matrin-Language
2aa440873f926c7fcd70e331b3619bbef5bdf5d9
[ "MIT" ]
null
null
null
#ifndef MARTIN_TEST_GENERATOR_EXTERN #define MARTIN_TEST_GENERATOR_EXTERN #include "testing.hpp" #include <generators/extern.hpp> #include "helpers/validatetree.hpp" #include "helpers/tokennode.hpp" #include "helpers/parseerror.hpp" #include "helpers/subtests.hpp" namespace Martin { class Test_generator_extern : public Test { public: std::string GetName() const override { return "Generator(Extern)"; } bool RunTest() override { SUBTEST_GENERATOR("extern 'C' let a : Int32", TreeNodeBase::Type::Misc_Extern, "extern", true, error); SUBTEST_GENERATOR("extern C let a : Int32", TreeNodeBase::Type::Misc_Extern, "extern", false, error); SUBTEST_GENERATOR("extern 'C' a", TreeNodeBase::Type::Misc_Extern, "extern", false, error); return true; } }; } #endif
29.793103
114
0.668981
Je06jm
4a777057086f534d4764f87d21c9dac7c89639e9
711
cpp
C++
EpicForceEngine/MagnumEngineLib/MagnumCore/GXTextureFilterState.cpp
MacgyverLin/MagnumEngine
975bd4504a1e84cb9698c36e06bd80c7b8ced0ff
[ "MIT" ]
1
2021-03-30T06:28:32.000Z
2021-03-30T06:28:32.000Z
EpicForceEngine/MagnumEngineLib/MagnumCore/GXTextureFilterState.cpp
MacgyverLin/MagnumEngine
975bd4504a1e84cb9698c36e06bd80c7b8ced0ff
[ "MIT" ]
null
null
null
EpicForceEngine/MagnumEngineLib/MagnumCore/GXTextureFilterState.cpp
MacgyverLin/MagnumEngine
975bd4504a1e84cb9698c36e06bd80c7b8ced0ff
[ "MIT" ]
null
null
null
#include "GXTextureFilterState.h" GXTextureFilterState::GXTextureFilterState(const GXTextureMagFilterMode &mag_, const GXTextureMinFilterMode &min_) { set(mag_, min_); } void GXTextureFilterState::set(const GXTextureMagFilterMode &mag_, const GXTextureMinFilterMode &min_) { this->mag = mag_; this->min = min_; } void GXTextureFilterState::setMagFilter(const GXTextureMagFilterMode &mag_) { this->mag = mag_; } const GXTextureMagFilterMode &GXTextureFilterState::getMagFilter() const { return this->mag; } void GXTextureFilterState::setMinFilter(const GXTextureMinFilterMode &min_) { this->min = min_; } const GXTextureMinFilterMode &GXTextureFilterState::getMinFilter() const { return this->min; }
22.21875
114
0.790436
MacgyverLin
4a7a39fd288d233b5efa5eecd67f2012b43de277
3,437
cc
C++
src/output_info.cc
artyomtugaryov/inference-engine-node
20dad9f6002600cde0daf3988492c7fa9a0370e7
[ "Apache-2.0" ]
34
2020-04-20T10:32:50.000Z
2022-01-26T22:38:36.000Z
src/output_info.cc
artyomtugaryov/inference-engine-node
20dad9f6002600cde0daf3988492c7fa9a0370e7
[ "Apache-2.0" ]
50
2020-04-20T02:48:41.000Z
2021-12-09T09:39:42.000Z
src/output_info.cc
artyomtugaryov/inference-engine-node
20dad9f6002600cde0daf3988492c7fa9a0370e7
[ "Apache-2.0" ]
10
2020-04-20T02:45:21.000Z
2022-03-13T07:09:14.000Z
#include "output_info.h" #include "utils.h" #include <napi.h> #include <uv.h> using namespace Napi; namespace ie = InferenceEngine; namespace ienodejs { Napi::FunctionReference OutputInfo::constructor; void OutputInfo::Init(const Napi::Env& env) { Napi::HandleScope scope(env); Napi::Function func = DefineClass(env, "OutputInfo", { InstanceMethod("name", &OutputInfo::Name), InstanceMethod("getPrecision", &OutputInfo::GetPrecision), InstanceMethod("setPrecision", &OutputInfo::SetPrecision), InstanceMethod("getLayout", &OutputInfo::GetLayout), InstanceMethod("getDims", &OutputInfo::GetDims), }); constructor = Napi::Persistent(func); constructor.SuppressDestruct(); } OutputInfo::OutputInfo(const Napi::CallbackInfo& info) : Napi::ObjectWrap<OutputInfo>(info) {} Napi::Object OutputInfo::NewInstance(const Napi::Env& env, const ie::DataPtr& actual) { Napi::EscapableHandleScope scope(env); Napi::Object obj = constructor.New({}); OutputInfo* info = Napi::ObjectWrap<OutputInfo>::Unwrap(obj); info->actual_ = actual; return scope.Escape(napi_value(obj)).ToObject(); } Napi::Value OutputInfo::Name(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); if (info.Length() > 0) { Napi::TypeError::New(env, "Invalid argument").ThrowAsJavaScriptException(); return Napi::Object::New(env); } return Napi::String::New(env, actual_->getName()); } Napi::Value OutputInfo::GetPrecision(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); if (info.Length() > 0) { Napi::TypeError::New(env, "Invalid argument").ThrowAsJavaScriptException(); return Napi::Object::New(env); } return Napi::String::New(env, utils::GetNameOfPrecision(actual_->getPrecision())); } void OutputInfo::SetPrecision(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); if (info.Length() != 1) { Napi::TypeError::New(env, "Wrong number of arguments") .ThrowAsJavaScriptException(); return; } if (!info[0].IsString()) { Napi::TypeError::New(env, "Wrong type of arguments") .ThrowAsJavaScriptException(); return; } std::string precision_name = info[0].ToString().Utf8Value(); if (!utils::IsValidPrecisionName(precision_name)) { Napi::TypeError::New(env, "Invalid argument").ThrowAsJavaScriptException(); return; } actual_->setPrecision(utils::GetPrecisionByName(precision_name)); } Napi::Value OutputInfo::GetLayout(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); if (info.Length() > 0) { Napi::TypeError::New(env, "Invalid argument").ThrowAsJavaScriptException(); return Napi::Object::New(env); } return Napi::String::New(env, utils::GetNameOfLayout(actual_->getLayout())); } Napi::Value OutputInfo::GetDims(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); if (info.Length() > 0) { Napi::TypeError::New(env, "Invalid argument").ThrowAsJavaScriptException(); return Napi::Object::New(env); } ie::SizeVector ie_dims = actual_->getTensorDesc().getDims(); Napi::Array js_dims = Napi::Array::New(env, ie_dims.size()); for (size_t i = 0; i < ie_dims.size(); ++i) { js_dims[i] = ie_dims[i]; } return js_dims; } } // namespace ienodejs
30.6875
80
0.650858
artyomtugaryov
4a7c118a51d53e71661d94054e6f771203ee9505
5,008
cpp
C++
third-party/Empirical/tests/Evolve/World_structure.cpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/tests/Evolve/World_structure.cpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/tests/Evolve/World_structure.cpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #define EMP_TDEBUG #include "third-party/Catch/single_include/catch2/catch.hpp" #include "emp/Evolve/World_structure.hpp" #include "emp/Evolve/World.hpp" #include <sstream> #include <iostream> TEST_CASE("Test World structure", "[Evolve]") { // SetPools (set pools on a world that is full?) emp::World<int> world; world.InjectAt(23, 0); world.InjectAt(28, 1); world.InjectAt(25, 2); SetPools(world, 3, 1); REQUIRE(world.GetSize() == 3); REQUIRE(world.GetNumOrgs() == 3); REQUIRE(!world.IsSynchronous()); REQUIRE(world.IsSpaceStructured()); REQUIRE(world.GetAttribute("PopStruct") == "Pools"); world.DoBirth(40, 1); REQUIRE(world[1] == 40); REQUIRE(world.GetNumOrgs() == 3); world.InjectAt(43, 0); REQUIRE(world[0] == 43); REQUIRE(world.GetNumOrgs() == 3); world.DoDeath(); REQUIRE(world.GetNumOrgs() == 2); world.Inject(48); REQUIRE(world.GetNumOrgs() == 3); SetPools(world, 2, 2, true); REQUIRE(world.GetSize() == 4); REQUIRE(world.GetNumOrgs() == 3); REQUIRE(world.IsSynchronous()); REQUIRE(world.IsSpaceStructured()); REQUIRE(world.GetAttribute("PopStruct") == "Pools"); world.DoBirth(42, 2); REQUIRE(world[2] != 42); REQUIRE(world.GetNextOrg(2) == 42); // Set Elites emp::World<int> world1; emp::TraitSet<int> ts1; std::function<double(int&)> fun = [](int& o){ return o > 50 ? 1.0 : 0.0;}; ts1.AddTrait(">50", fun); std::function<double(int&)> fun2 = [](int& o){ return (o % 2 == 0) ? 0.0 : 1.0;}; ts1.AddTrait("IsOdd", fun2); emp::vector<size_t> ts1_counts{ 1, 1 }; SetMapElites(world1, ts1, ts1_counts); REQUIRE(world1.GetAttribute("PopStruct") == "MapElites"); REQUIRE(world1.GetSize() == 1); REQUIRE(world1.IsSynchronous() == false); REQUIRE(world1.IsSpaceStructured() == false); world1.Inject(5); REQUIRE(world1[0] == 5); REQUIRE(world1.GetNumOrgs() == 1); world1.DoBirth(51,0); REQUIRE(world1[0] == 51); world1.DoBirth(7,0); REQUIRE(world1[0] == 51); world1.DoDeath(); REQUIRE(world1.GetNumOrgs() == 0); #ifdef EMP_TDEBUG REQUIRE(world1.GetRandomNeighborPos(0).GetIndex() == 0); #endif emp::World<int> world2; world2.Resize(10); REQUIRE(world2.GetSize() == 10); SetMapElites(world2, ts1); REQUIRE(world2.GetAttribute("PopStruct") == "MapElites"); REQUIRE(world2.GetSize() == 9); emp::World<int> world2_1; world2_1.Resize(5); world2_1.AddPhenotype(">50", fun); emp::vector<size_t> trait_counts; trait_counts.push_back(world2_1.GetSize()); SetMapElites(world2_1, trait_counts); REQUIRE(world2_1.size() == 5); emp::World<int> world3; world3.Resize(10); REQUIRE(world3.GetSize() == 10); emp::TraitSet<int> ts2; ts2.AddTrait("IsOdd", fun2); SetMapElites(world3, ts2); REQUIRE(world3.GetAttribute("PopStruct") == "MapElites"); REQUIRE(world3.GetSize() == 10); emp::World<int> world4; world4.Resize(5); world4.AddPhenotype(">50", fun); SetMapElites(world4); REQUIRE(world4.GetAttribute("PopStruct") == "MapElites"); REQUIRE(world4.GetSize() == 5); emp::World<int> world5; world5.Resize(2); world5.InjectAt(11, 0); world5.AddPhenotype("IsOdd", fun2); SetDiverseElites(world5, 2); REQUIRE(world5.GetAttribute("PopStruct") == "DiverseElites"); REQUIRE(world5.GetSize() == 2); REQUIRE(world5.IsSynchronous() == false); REQUIRE(world5.IsSpaceStructured() == false); #ifdef EMP_TDEBUG REQUIRE(world5.GetRandomNeighborPos(0).GetIndex() == 0); #endif world5.InjectAt(33, 1); REQUIRE(world5[1] == 33); REQUIRE(world5.GetNumOrgs() == 2); world5.DoDeath(); REQUIRE(world5.GetNumOrgs() == 1); REQUIRE(world5[0] == 33); world5.DoBirth(22, 0); REQUIRE(world5.GetNumOrgs() == 2); REQUIRE(world5[1] == 22); // World_MinDistInfo emp::World<int> world6; world6.InjectAt(4, 0); world6.InjectAt(7, 1); world6.InjectAt(9, 2); REQUIRE(world6.GetSize() == 3); emp::World_MinDistInfo<int> w6_distInfo(world6, ts2); REQUIRE(w6_distInfo.CalcDist(0, 1) == 1.0); REQUIRE(w6_distInfo.CalcDist(1, 2) == 0.0); // both odd REQUIRE(w6_distInfo.is_setup == false); w6_distInfo.Setup(); REQUIRE(w6_distInfo.is_setup); REQUIRE(w6_distInfo.distance.size() == world6.GetSize()); REQUIRE(w6_distInfo.CalcBin(0) == 2); REQUIRE(w6_distInfo.bin_ids[2].size() == 3); REQUIRE(w6_distInfo.bin_ids[0].size() == 0); REQUIRE(w6_distInfo.bin_ids[1].size() == 0); REQUIRE(w6_distInfo.nearest_id[0] == 1); REQUIRE(w6_distInfo.distance[0] == 1.0); REQUIRE(w6_distInfo.distance.size() == 3); REQUIRE(w6_distInfo.OK()); world6.InjectAt(11, 0); REQUIRE(w6_distInfo.distance[0] == 1.0); w6_distInfo.Update(0); REQUIRE(w6_distInfo.distance[0] == 0.0); REQUIRE(w6_distInfo.distance.size() == 3); w6_distInfo.Clear(); REQUIRE(w6_distInfo.distance.size() == 0); // WorldPosition emp::WorldPosition worldPos(1, 0); REQUIRE(worldPos.GetIndex() == 1); REQUIRE(worldPos.GetPopID() == 0); worldPos.SetActive(); REQUIRE(worldPos.IsActive()); worldPos.SetPopID(1); REQUIRE(!worldPos.IsActive()); REQUIRE(worldPos.GetPopID() == 1); worldPos.MarkInvalid(); REQUIRE(!worldPos.IsValid()); }
29.28655
82
0.689297
koellingh
4a7eef9d8a99deca886357784ee67d889e2eabc1
1,253
cpp
C++
02_Estructuras y Archivos/Practicas/T1_Contador_Hojas.cpp
vazeri/Programacion-Orientada-a-Objetos
57d1dc413956e50d31f34c0bb339b32a176f9616
[ "MIT" ]
null
null
null
02_Estructuras y Archivos/Practicas/T1_Contador_Hojas.cpp
vazeri/Programacion-Orientada-a-Objetos
57d1dc413956e50d31f34c0bb339b32a176f9616
[ "MIT" ]
null
null
null
02_Estructuras y Archivos/Practicas/T1_Contador_Hojas.cpp
vazeri/Programacion-Orientada-a-Objetos
57d1dc413956e50d31f34c0bb339b32a176f9616
[ "MIT" ]
null
null
null
//Programa que cuenta el numero d ehojas de un arbol binario #include "iostream" #include <stdio.h> #include <stdlib.h> using namespace std; struct nodo { int data; struct nodo* left; struct nodo* right; }; // Funcion que cuenta el numero de nodos hojas int conteoHojas(struct nodo* nodo) { if(nodo == NULL) return 0; if(nodo->left == NULL && nodo->right==NULL) return 1; else return conteoHojas(nodo->left)+ conteoHojas(nodo->right); } //Funcion de ayuda localiza el nuevo nodo con // la info dada y los punteros NULL izquierda y derecha struct nodo* newNodo(int data) { struct nodo* nodo = (struct nodo*) malloc(sizeof(struct nodo)); nodo->data = data; nodo->left = NULL; nodo->right = NULL; return(nodo); } int main() { //crea un arbol struct nodo *root = newNodo(1); //Raiz root->left = newNodo(2); //Hoja 1 root->right = newNodo(3); //Hoja 2 root->left->left = newNodo(4); //Hoja 3 root->left->right = newNodo(5); //obtiene el conteo de hojas del arbol creado arribita cout<<"Numero de hojas en el arbol: "<< conteoHojas(root)<<endl; getchar(); return 0; }
21.982456
66
0.597765
vazeri
4a8024e6da3f95373d1b6af2a8f0fa26527c8986
1,600
hpp
C++
src/struct/global.hpp
am1w1zz/CppLearn
16db21cb5cc9ca14e488f4f40923b756de18e354
[ "MIT" ]
null
null
null
src/struct/global.hpp
am1w1zz/CppLearn
16db21cb5cc9ca14e488f4f40923b756de18e354
[ "MIT" ]
null
null
null
src/struct/global.hpp
am1w1zz/CppLearn
16db21cb5cc9ca14e488f4f40923b756de18e354
[ "MIT" ]
null
null
null
#define stature(p) ((p) ? (p)->height : -1) #define IsRoot(x) ( ! ( (x).parent ) ) #define IsLChild(x) ( ! IsRoot(x) && ( & (x) == (x).parent->lc ) ) #define IsRChild(x) ( ! IsRoot(x) && ( & (x) == (x).parent->rc ) ) #define HasParent(x) ( ! IsRoot(x) ) #define HasLChild(x) ( (x).lc ) #define HasRChild(x) ( (x).rc ) #define HasChild(x) ( HasLChild(x) || HasRChild(x) ) #define HasBothChild(x) ( HasLChild(x) && HasRChild(x) ) #define IsLeaf(x) ( ! HasChild(x) ) #define sibling(p) ( IsLChild( * (p) ) ? (p)->parent->rc : (p)->parent->lc ) #define uncle(x) ( sibling( (x)->parent ) ) #define FromParentTo(x) ( IsRoot(x) ? this->root : ( IsLChild(x) ? (x).parent->lc : (x).parent->rc ) ) #define HeightUpdated(x) ( (x).height == 1 + max( stature( (x).lc ), stature( (x).rc ) ) ) #define Balanced(x) ( stature( (x).lc ) == stature( (x).rc ) ) //理想平衡条件 #define BalFac(x) ( stature( (x).lc ) - stature( (x).rc ) ) //平衡因子 #define AvlBalanced(x) ( ( -2 < BalFac(x) ) && ( BalFac(x) < 2 ) ) //AVL平衡条件 #define IsBlack(p) ( ! (p) || ( RB_BLACK == (p)->color ) ) //外部节点也视作黑节点 #define IsRed(p) ( ! IsBlack(p) ) //非黑即红 #define BlackHeightUpdated(x) ( /*RedBlack高度更新条件*/ \ ( stature( (x).lc ) == stature( (x).rc ) ) && \ ( (x).height == ( IsRed(& x) ? stature( (x).lc ) : stature( (x).lc ) + 1 ) ) \ ) #define tallerChild(x) ( \ stature( (x)->lc ) > stature( (x)->rc ) ? (x)->lc : ( /*左高*/ \ stature( (x)->lc ) < stature( (x)->rc ) ? (x)->rc : ( /*右高*/ \ IsLChild( * (x) ) ? (x)->lc : (x)->rc /*等高:与父亲x同侧者(zIg-zIg或zAg-zAg)优先*/ \ ) \ ) \ ) typedef enum { RB_RED, RB_BLACK} RBColor; //节点颜色
47.058824
102
0.538125
am1w1zz
4a872c16f0d2efaed39d9ec48a6428f911a45aca
25
cpp
C++
tests/test_ai.cpp
phiwen96/ph_ai
002b482829acdd1a4d95b88e20ca46b096e3f3da
[ "Apache-2.0" ]
null
null
null
tests/test_ai.cpp
phiwen96/ph_ai
002b482829acdd1a4d95b88e20ca46b096e3f3da
[ "Apache-2.0" ]
null
null
null
tests/test_ai.cpp
phiwen96/ph_ai
002b482829acdd1a4d95b88e20ca46b096e3f3da
[ "Apache-2.0" ]
null
null
null
#include "test_ai.hpp"
6.25
22
0.68
phiwen96
4a8bc55b892f1baf60332d8f1a6dcc636e392b3e
5,187
hpp
C++
src/core/GlobalHandler.hpp
FR-GRE-BDS-HPC-SW-SAGE2-GMA/ummap-io-v2
bfcd3c1bccf9a798ada3ebf6d2ed16e60ab44660
[ "Apache-2.0" ]
1
2022-01-28T16:03:04.000Z
2022-01-28T16:03:04.000Z
src/core/GlobalHandler.hpp
FR-GRE-BDS-HPC-SW-SAGE2-GMA/ummap-io-v2
bfcd3c1bccf9a798ada3ebf6d2ed16e60ab44660
[ "Apache-2.0" ]
null
null
null
src/core/GlobalHandler.hpp
FR-GRE-BDS-HPC-SW-SAGE2-GMA/ummap-io-v2
bfcd3c1bccf9a798ada3ebf6d2ed16e60ab44660
[ "Apache-2.0" ]
null
null
null
/***************************************************** * PROJECT : ummap-io-v2 * * LICENSE : Apache 2.0 * * COPYRIGHT: 2020-2021 Bull SAS All rights reserved * *****************************************************/ #ifndef UMMAP_GLOBAL_HANDLER_HPP #define UMMAP_GLOBAL_HANDLER_HPP /******************** HEADERS *********************/ //std #include <cassert> #include <map> #include <functional> //unix #include <signal.h> //internal #include "common/Debug.hpp" #include "MappingRegistry.hpp" #include "PolicyRegistry.hpp" #include "../uri/UriHandler.hpp" #include "../public-api/ummap.h" /******************** NAMESPACE *******************/ namespace ummapio { /********************* TYPES **********************/ /** * Used to track the page fault type in a readable way. **/ enum PageFaultType { /** The page fault is a read fault. **/ PAGEFAULT_READ = 0, /** The page fault is a write fault. **/ PAGEFAULT_WRITE }; /********************* CLASS **********************/ /** * The global handler is the main struct handling all the objects to make * ummap working. It is called from the C public API. **/ class GlobalHandler { public: GlobalHandler(void); ~GlobalHandler(void); void * ummap(void * addr, size_t size, size_t segmentSize, size_t storageOffset, int protection, int flags, Driver * driver, Policy * localPolicy, const std::string & policyGroup); int uunmap(void * ptr, bool sync); void flush(void * ptr, size_t size, bool evict, bool sync); void skipFirstRead(void * ptr); void registerPolicy(const std::string & name, Policy * policy); void unregisterPolicy(const std::string & name); Policy * getPolicy(const std::string & name, bool nullNotFound = false); Driver * getDriver(void * ptr); void makeDirty(void * ptr); void registerMapping(Mapping * mapping); void unregisterMapping(Mapping * mapping); bool onSegFault(void * addr, bool isWrite); void deleteAllMappings(void); UriHandler & getUriHandler(void); Mapping * getMapping(void * addr, bool crashOnNotFound = true); template <class T> int applyCow(const char * driverName, void * addr, std::function<int(Mapping * mapping, T * driver)> action); template <class T> int applySwitch(const char * driverName, void * addr, ummap_switch_clean_t cleanAction, std::function<void(T * driver)> action); void initMero(const std::string & ressourceFile, int ressourceIndex); private: /** Registry of all active mappings in use. **/ MappingRegistry mappingRegistry; /** Registry of global policies in use. **/ PolicyRegistry policyRegistry; /** URI handler to be used to build drivers and policies from strings. **/ UriHandler uriHandler; }; /******************* FUNCTION *********************/ //fault handler void setupSegfaultHandler(void); void unsetSegfaultHandler(void); void segfaultHandler(int sig, siginfo_t *si, void *context); /******************* FUNCTION *********************/ //global handler void setGlobalHandler(GlobalHandler * handler); void clearGlobalHandler(void); GlobalHandler * getGlobalhandler(void); /******************* FUNCTION *********************/ template <class T> int GlobalHandler::applyCow(const char * driverName, void * addr, std::function<int(Mapping * mapping, T * driver)> action) { //check assert(addr != NULL); //get mapping Mapping * mapping = getGlobalhandler()->getMapping(addr); assumeArg(mapping != NULL, "Fail to find the requested mapping for address %p !").arg(addr).end(); //get the driver Driver * driver = mapping->getDriver(); assume(driver != NULL, "Get an unknown NULL driver !"); //try to cast to IOC driver T * castDriver = dynamic_cast<T*>(driver); assumeArg(castDriver != NULL, "Get an invalid unknown driver type, not %1, cannot COW !").arg(driverName).end(); //call copy on write on the driver. mapping->unregisterRange(); int status = action(mapping, castDriver); mapping->registerRange(); //return return status; } template <class T> int GlobalHandler::applySwitch(const char * driverName, void * addr, ummap_switch_clean_t cleanAction, std::function<void(T * driver)> action) { //check assert(addr != NULL); //get mapping Mapping * mapping = getGlobalhandler()->getMapping(addr); assumeArg(mapping != NULL, "Fail to find the requested mapping for address %p !").arg(addr).end(); //get the driver Driver * driver = mapping->getDriver(); assume(driver != NULL, "Get an unknown NULL driver !"); //try to cast to IOC driver T * castDriver = dynamic_cast<T*>(driver); assumeArg(castDriver != NULL, "Get an invalid unknown driver type, not %1, cannot COW !").arg(driverName).end(); //call copy on write on the driver. mapping->unregisterRange(); action(castDriver); mapping->registerRange(); //if drop switch (cleanAction) { case UMMAP_NO_ACTION: break; case UMMAP_DROP_CLEAN: mapping->dropClean(); break; case UMMAP_MARK_CLEAN_DIRTY: mapping->markCleanAsDirty(); break; default: UMMAP_FATAL_ARG("Invalid clean action for switch operation, got %1").arg(cleanAction).end(); break; } //return return 0; } } #endif //UMMAP_GLOBAL_HANDLER_HPP
31.822086
182
0.6524
FR-GRE-BDS-HPC-SW-SAGE2-GMA
4a8c41ac5690b034980d7abf7071a86f261f0c11
155
cpp
C++
tests/test_array_compare.cpp
willwray/_c_array_support
6324c5623124567588c6b65ec43a7d20d05a00b0
[ "BSL-1.0" ]
3
2021-12-04T11:29:35.000Z
2021-12-09T17:16:20.000Z
tests/test_array_compare.cpp
willwray/_c_array_support
6324c5623124567588c6b65ec43a7d20d05a00b0
[ "BSL-1.0" ]
null
null
null
tests/test_array_compare.cpp
willwray/_c_array_support
6324c5623124567588c6b65ec43a7d20d05a00b0
[ "BSL-1.0" ]
1
2021-12-09T17:16:34.000Z
2021-12-09T17:16:34.000Z
#include "test_array_compare.hpp" #include <cassert> int main() { //assert( ltl::compare_three_way{}(a, A{1,0}) < 0); //std::cout << std::endl; }
15.5
55
0.606452
willwray
4a8d85fad6a16f3de67ecbf679b02aee183bf237
11,286
cpp
C++
SU2-Quantum/SU2_CFD/src/numerics/heat.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/src/numerics/heat.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/src/numerics/heat.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
1
2021-12-03T06:40:08.000Z
2021-12-03T06:40:08.000Z
/*! * \file heat.cpp * \brief Implementation of numerics classes for heat transfer. * \author F. Palacios, T. Economon * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * SU2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with SU2. If not, see <http://www.gnu.org/licenses/>. */ #include "../../include/numerics/heat.hpp" CCentSca_Heat::CCentSca_Heat(unsigned short val_nDim, unsigned short val_nVar, CConfig *config) : CNumerics(val_nDim, val_nVar, config) { implicit = (config->GetKind_TimeIntScheme_Turb() == EULER_IMPLICIT); /* A grid is defined as dynamic if there's rigid grid movement or grid deformation AND the problem is time domain */ dynamic_grid = config->GetDynamic_Grid(); MeanVelocity = new su2double [nDim]; Laminar_Viscosity_i = config->GetViscosity_FreeStreamND(); Laminar_Viscosity_j = config->GetViscosity_FreeStreamND(); Param_Kappa_4 = config->GetKappa_4th_Heat(); Diff_Lapl = new su2double [nVar]; } CCentSca_Heat::~CCentSca_Heat(void) { delete [] MeanVelocity; delete [] Diff_Lapl; } void CCentSca_Heat::ComputeResidual(su2double *val_residual, su2double **val_Jacobian_i, su2double **val_Jacobian_j, CConfig *config) { AD::StartPreacc(); AD::SetPreaccIn(V_i, nDim+3); AD::SetPreaccIn(V_j, nDim+3); AD::SetPreaccIn(Temp_i); AD::SetPreaccIn(Temp_j); AD::SetPreaccIn(Und_Lapl_i, nVar); AD::SetPreaccIn(Und_Lapl_j, nVar); AD::SetPreaccIn(Normal, nDim); if (dynamic_grid) { AD::SetPreaccIn(GridVel_i, nDim); AD::SetPreaccIn(GridVel_j, nDim); } /*--- Primitive variables at point i and j ---*/ Pressure_i = V_i[0]; Pressure_j = V_j[0]; DensityInc_i = V_i[nDim+2]; DensityInc_j = V_j[nDim+2]; BetaInc2_i = V_i[nDim+3]; BetaInc2_j = V_j[nDim+3]; /*--- Projected velocities at the current edge ---*/ ProjVelocity = 0.0; ProjVelocity_i = 0.0; ProjVelocity_j = 0.0; Area = 0.0; for (iDim = 0; iDim < nDim; iDim++) { ProjVelocity_i += V_i[iDim+1]*Normal[iDim]; ProjVelocity_j += V_j[iDim+1]*Normal[iDim]; Area += Normal[iDim]*Normal[iDim]; } Area = sqrt(Area); /*--- Computing the second order centered scheme part ---*/ ProjVelocity = 0.5*(ProjVelocity_i+ProjVelocity_j); val_residual[0] = 0.5*(Temp_i + Temp_j)*ProjVelocity; if (implicit) { val_Jacobian_i[0][0] = 0.5*ProjVelocity; val_Jacobian_j[0][0] = 0.5*ProjVelocity; } /*--- Adding artificial dissipation to stabilize the centered scheme ---*/ Diff_Lapl[0] = Und_Lapl_i[0]-Und_Lapl_j[0]; SoundSpeed_i = sqrt(ProjVelocity_i*ProjVelocity_i + (BetaInc2_i/DensityInc_i)*Area*Area); SoundSpeed_j = sqrt(ProjVelocity_j*ProjVelocity_j + (BetaInc2_j/DensityInc_j)*Area*Area); Local_Lambda_i = fabs(ProjVelocity_i)+SoundSpeed_i; Local_Lambda_j = fabs(ProjVelocity_j)+SoundSpeed_j; MeanLambda = 0.5*(Local_Lambda_i+Local_Lambda_j); val_residual[0] += -Param_Kappa_4*Diff_Lapl[0]*MeanLambda; if (implicit) { cte_0 = Param_Kappa_4*su2double(Neighbor_i+1)*MeanLambda; cte_1 = Param_Kappa_4*su2double(Neighbor_j+1)*MeanLambda; val_Jacobian_i[0][0] += cte_0; val_Jacobian_j[0][0] -= cte_1; } AD::SetPreaccOut(val_residual[0]); AD::EndPreacc(); } CUpwSca_Heat::CUpwSca_Heat(unsigned short val_nDim, unsigned short val_nVar, CConfig *config) : CNumerics(val_nDim, val_nVar, config) { implicit = (config->GetKind_TimeIntScheme_Turb() == EULER_IMPLICIT); /* A grid is defined as dynamic if there's rigid grid movement or grid deformation AND the problem is time domain */ dynamic_grid = config->GetDynamic_Grid(); Velocity_i = new su2double [nDim]; Velocity_j = new su2double [nDim]; Laminar_Viscosity_i = config->GetViscosity_FreeStreamND(); Laminar_Viscosity_j = config->GetViscosity_FreeStreamND(); } CUpwSca_Heat::~CUpwSca_Heat(void) { delete [] Velocity_i; delete [] Velocity_j; } void CUpwSca_Heat::ComputeResidual(su2double *val_residual, su2double **val_Jacobian_i, su2double **val_Jacobian_j, CConfig *config) { q_ij = 0.0; AD::StartPreacc(); AD::SetPreaccIn(V_i, nDim+1); AD::SetPreaccIn(V_j, nDim+1); AD::SetPreaccIn(Temp_i); AD::SetPreaccIn(Temp_j); AD::SetPreaccIn(Normal, nDim); if (dynamic_grid) { AD::SetPreaccIn(GridVel_i, nDim); AD::SetPreaccIn(GridVel_j, nDim); } for (iDim = 0; iDim < nDim; iDim++) { Velocity_i[iDim] = V_i[iDim+1]; Velocity_j[iDim] = V_j[iDim+1]; q_ij += 0.5*(Velocity_i[iDim]+Velocity_j[iDim])*Normal[iDim]; } a0 = 0.5*(q_ij+fabs(q_ij)); a1 = 0.5*(q_ij-fabs(q_ij)); val_residual[0] = a0*Temp_i+a1*Temp_j; if (implicit) { val_Jacobian_i[0][0] = a0; val_Jacobian_j[0][0] = a1; } AD::SetPreaccOut(val_residual[0]); AD::EndPreacc(); } CAvgGrad_Heat::CAvgGrad_Heat(unsigned short val_nDim, unsigned short val_nVar, CConfig *config) : CNumerics(val_nDim, val_nVar, config) { implicit = (config->GetKind_TimeIntScheme_Heat() == EULER_IMPLICIT); Edge_Vector = new su2double [nDim]; Proj_Mean_GradHeatVar_Normal = new su2double [nVar]; Proj_Mean_GradHeatVar_Corrected = new su2double [nVar]; Mean_GradHeatVar = new su2double* [nVar]; for (iVar = 0; iVar < nVar; iVar++) Mean_GradHeatVar[iVar] = new su2double [nDim]; } CAvgGrad_Heat::~CAvgGrad_Heat(void) { delete [] Edge_Vector; delete [] Proj_Mean_GradHeatVar_Normal; delete [] Proj_Mean_GradHeatVar_Corrected; for (iVar = 0; iVar < nVar; iVar++) delete [] Mean_GradHeatVar[iVar]; delete [] Mean_GradHeatVar; } void CAvgGrad_Heat::ComputeResidual(su2double *val_residual, su2double **Jacobian_i, su2double **Jacobian_j, CConfig *config) { AD::StartPreacc(); AD::SetPreaccIn(Coord_i, nDim); AD::SetPreaccIn(Coord_j, nDim); AD::SetPreaccIn(Normal, nDim); AD::SetPreaccIn(Temp_i); AD::SetPreaccIn(Temp_j); AD::SetPreaccIn(ConsVar_Grad_i[0],nDim); AD::SetPreaccIn(ConsVar_Grad_j[0],nDim); AD::SetPreaccIn(Thermal_Diffusivity_i); AD::SetPreaccIn(Thermal_Conductivity_j); Thermal_Diffusivity_Mean = 0.5*(Thermal_Diffusivity_i + Thermal_Diffusivity_j); /*--- Compute vector going from iPoint to jPoint ---*/ dist_ij_2 = 0; proj_vector_ij = 0; for (iDim = 0; iDim < nDim; iDim++) { Edge_Vector[iDim] = Coord_j[iDim]-Coord_i[iDim]; dist_ij_2 += Edge_Vector[iDim]*Edge_Vector[iDim]; proj_vector_ij += Edge_Vector[iDim]*Normal[iDim]; } if (dist_ij_2 == 0.0) proj_vector_ij = 0.0; else proj_vector_ij = proj_vector_ij/dist_ij_2; /*--- Mean gradient approximation. Projection of the mean gradient in the direction of the edge ---*/ for (iVar = 0; iVar < nVar; iVar++) { Proj_Mean_GradHeatVar_Normal[iVar] = 0.0; Proj_Mean_GradHeatVar_Corrected[iVar] = 0.0; for (iDim = 0; iDim < nDim; iDim++) { Mean_GradHeatVar[iVar][iDim] = 0.5*(ConsVar_Grad_i[iVar][iDim] + ConsVar_Grad_j[iVar][iDim]); Proj_Mean_GradHeatVar_Normal[iVar] += Mean_GradHeatVar[iVar][iDim]*Normal[iDim]; } Proj_Mean_GradHeatVar_Corrected[iVar] = Proj_Mean_GradHeatVar_Normal[iVar]; } val_residual[0] = Thermal_Diffusivity_Mean*Proj_Mean_GradHeatVar_Corrected[0]; /*--- For Jacobians -> Use of TSL approx. to compute derivatives of the gradients ---*/ if (implicit) { Jacobian_i[0][0] = -Thermal_Diffusivity_Mean*proj_vector_ij; Jacobian_j[0][0] = Thermal_Diffusivity_Mean*proj_vector_ij; } AD::SetPreaccOut(val_residual, nVar); AD::EndPreacc(); } CAvgGradCorrected_Heat::CAvgGradCorrected_Heat(unsigned short val_nDim, unsigned short val_nVar, CConfig *config) : CNumerics(val_nDim, val_nVar, config) { implicit = (config->GetKind_TimeIntScheme_Heat() == EULER_IMPLICIT); Edge_Vector = new su2double [nDim]; Proj_Mean_GradHeatVar_Edge = new su2double [nVar]; Proj_Mean_GradHeatVar_Kappa = new su2double [nVar]; Proj_Mean_GradHeatVar_Corrected = new su2double [nVar]; Mean_GradHeatVar = new su2double* [nVar]; for (iVar = 0; iVar < nVar; iVar++) Mean_GradHeatVar[iVar] = new su2double [nDim]; } CAvgGradCorrected_Heat::~CAvgGradCorrected_Heat(void) { delete [] Edge_Vector; delete [] Proj_Mean_GradHeatVar_Edge; delete [] Proj_Mean_GradHeatVar_Kappa; delete [] Proj_Mean_GradHeatVar_Corrected; for (iVar = 0; iVar < nVar; iVar++) delete [] Mean_GradHeatVar[iVar]; delete [] Mean_GradHeatVar; } void CAvgGradCorrected_Heat::ComputeResidual(su2double *val_residual, su2double **Jacobian_i, su2double **Jacobian_j, CConfig *config) { AD::StartPreacc(); AD::SetPreaccIn(Coord_i, nDim); AD::SetPreaccIn(Coord_j, nDim); AD::SetPreaccIn(Normal, nDim); AD::SetPreaccIn(Temp_i); AD::SetPreaccIn(Temp_j); AD::SetPreaccIn(ConsVar_Grad_i[0],nDim); AD::SetPreaccIn(ConsVar_Grad_j[0],nDim); AD::SetPreaccIn(Thermal_Diffusivity_i); AD::SetPreaccIn(Thermal_Diffusivity_j); Thermal_Diffusivity_Mean = 0.5*(Thermal_Diffusivity_i + Thermal_Diffusivity_j); /*--- Compute vector going from iPoint to jPoint ---*/ dist_ij_2 = 0; proj_vector_ij = 0; for (iDim = 0; iDim < nDim; iDim++) { Edge_Vector[iDim] = Coord_j[iDim]-Coord_i[iDim]; dist_ij_2 += Edge_Vector[iDim]*Edge_Vector[iDim]; proj_vector_ij += Edge_Vector[iDim]*Normal[iDim]; } if (dist_ij_2 == 0.0) proj_vector_ij = 0.0; else proj_vector_ij = proj_vector_ij/dist_ij_2; /*--- Mean gradient approximation. Projection of the mean gradient in the direction of the edge ---*/ for (iVar = 0; iVar < nVar; iVar++) { Proj_Mean_GradHeatVar_Edge[iVar] = 0.0; Proj_Mean_GradHeatVar_Kappa[iVar] = 0.0; for (iDim = 0; iDim < nDim; iDim++) { Mean_GradHeatVar[iVar][iDim] = 0.5*(ConsVar_Grad_i[iVar][iDim] + ConsVar_Grad_j[iVar][iDim]); Proj_Mean_GradHeatVar_Kappa[iVar] += Mean_GradHeatVar[iVar][iDim]*Normal[iDim]; Proj_Mean_GradHeatVar_Edge[iVar] += Mean_GradHeatVar[iVar][iDim]*Edge_Vector[iDim]; } Proj_Mean_GradHeatVar_Corrected[iVar] = Proj_Mean_GradHeatVar_Kappa[iVar]; Proj_Mean_GradHeatVar_Corrected[iVar] -= Proj_Mean_GradHeatVar_Edge[iVar]*proj_vector_ij - (Temp_j-Temp_i)*proj_vector_ij; } val_residual[0] = Thermal_Diffusivity_Mean*Proj_Mean_GradHeatVar_Corrected[0]; /*--- For Jacobians -> Use of TSL approx. to compute derivatives of the gradients ---*/ if (implicit) { Jacobian_i[0][0] = -Thermal_Diffusivity_Mean*proj_vector_ij; Jacobian_j[0][0] = Thermal_Diffusivity_Mean*proj_vector_ij; } AD::SetPreaccOut(val_residual, nVar); AD::EndPreacc(); }
34.941176
118
0.704235
Agony5757
4a8ec67f0a1946b8606be361352ead813c34aef7
7,215
cpp
C++
StaticLib/Sources/Game.cpp
Esentiel/dx3d
caf8423b69032518c3abeab08781190c41947b63
[ "MIT" ]
null
null
null
StaticLib/Sources/Game.cpp
Esentiel/dx3d
caf8423b69032518c3abeab08781190c41947b63
[ "MIT" ]
18
2019-09-18T15:21:03.000Z
2020-01-28T21:43:08.000Z
StaticLib/Sources/Game.cpp
Esentiel/dx3d
caf8423b69032518c3abeab08781190c41947b63
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <Windowsx.h> #include "Game.h" #include "Mesh.h" #include "FileManager.h" #include "RenderScene.h" #include "Camera.h" namespace Library { const UINT Game::DefaultScreenWidth = 1280; const UINT Game::DefaultScreenHeight = 720; Game::Game(HINSTANCE instance, const std::wstring& windowClass, const std::wstring& windowTitle, int showCommand) : mInstance(instance), mWindowClass(windowClass), mWindowTitle(windowTitle), mShowCommand(showCommand), mScreenWidth(DefaultScreenWidth), mScreenHeight(DefaultScreenHeight) { assert(m_game == nullptr); m_game = this; } Game::~Game() { } HINSTANCE Game::Instance() const { return mInstance; } HWND Game::WindowHandle() const { return mWindowHandle; } const WNDCLASSEX& Game::Window() const { return mWindow; } const std::wstring& Game::WindowClass() const { return mWindowClass; } const std::wstring& Game::WindowTitle() const { return mWindowTitle; } int Game::ScreenWidth() const { return mScreenWidth; } int Game::ScreenHeight() const { return mScreenHeight; } void Game::Run() { InitializeWindow(); Initialize(); MSG message; ZeroMemory(&message, sizeof(message)); mGameClock.Reset(); while (message.message != WM_QUIT) { if (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&message); DispatchMessage(&message); } else { mGameClock.UpdateGameTime(mGameTime); Update(mGameTime); Draw(mGameTime); } } Shutdown(); } void Game::Exit() { PostQuitMessage(0); } void Game::Initialize() { // global m_globalApp.reset(new Library::GD3DApp); g_D3D = m_globalApp.get(); // exe path g_D3D->executablePath = new wchar_t[MAX_PATH]; HMODULE hModule = GetModuleHandle(NULL); if (hModule) { GetModuleFileName(hModule, g_D3D->executablePath, sizeof(wchar_t) * MAX_PATH); } m_d3dApp.reset(new D3DApp(mWindowHandle, mScreenWidth, mScreenHeight)); m_d3dApp->Initialize(); // create test meshes std::string filePath = "../Content/models/Arissa.fbx"; uint32_t numMesh = 0; uint32_t meshID = 0; do { std::unique_ptr<Mesh> mesh(new Mesh); bool res = g_D3D->fileMgr->ReadModelFromFBX(filePath.c_str(), meshID, mesh.get(), &numMesh); if (res) { mesh->Initialize(); mesh->Scale(DirectX::XMFLOAT3(0.2f, 0.2f, 0.2f)); mesh->Rotate(DirectX::XMFLOAT3(0.0f, 0.8f, 0.0f)); g_D3D->renderScene->AddMesh(std::move(mesh)); } meshID++; } while (meshID < numMesh); // box filePath = "../Content/models/box_ddc_true.fbx"; numMesh = 0; meshID = 0; do { std::unique_ptr<Mesh> mesh(new Mesh); bool res = g_D3D->fileMgr->ReadModelFromFBX(filePath.c_str(), meshID, mesh.get(), &numMesh); if (res) { mesh->Initialize(); mesh->Scale(DirectX::XMFLOAT3(20.f, 20.f, 20.f)); mesh->Move(DirectX::XMFLOAT3(1.f, -12.f, 1.f)); mesh->SetFlag(Mesh::MeshFlags::UseSpecularReflection); g_D3D->renderScene->AddMesh(std::move(mesh)); } meshID++; } while (meshID < numMesh); // sun /*filePath = "../Content/models/sun.fbx"; numMesh = 0; meshID = 0; do { std::unique_ptr<Mesh> mesh(new Mesh); bool res = g_D3D->fileMgr->ReadModelFromFBX(filePath.c_str(), meshID, mesh.get(), &numMesh); if (res) { mesh->Initialize(); mesh->Scale(DirectX::XMFLOAT3(1.f, 1.f, 1.f)); mesh->Move(DirectX::XMFLOAT3(-20.0f, 66.0f, 76.0f)); mesh->SetFlag(Mesh::MeshFlags::UseSpecularReflection); g_D3D->renderScene->AddMesh(std::move(mesh)); } meshID++; } while (meshID < numMesh);*/ } void Game::Update(const GameTime& gameTime) { OnKeyboardInput(gameTime); auto delta = gameTime.ElapsedGameTime(); std::string deltaText = std::to_string(1.0f/delta); std::string title("FPS: "); title.insert(title.cend(), deltaText.cbegin(), deltaText.cend()); SetWindowTextA(mWindowHandle, title.c_str()); } void Game::Draw(const GameTime& gameTime) { m_d3dApp->Draw(gameTime); } void Game::OnMouseButtonDown(int x, int y) { m_mouseLastX = x; m_mouseLastY = y; } void Game::OnMouseMoved(WPARAM btnState, int x, int y) { if ((btnState & MK_RBUTTON) != 0) { float dx = DirectX::XMConvertToRadians(0.25f*static_cast<float>(x - m_mouseLastX)); float dy = DirectX::XMConvertToRadians(0.25f*static_cast<float>(y - m_mouseLastY)); g_D3D->camera->Pitch(dy); g_D3D->camera->RotateY(dx); } m_mouseLastX = x; m_mouseLastY = y; } void Game::InitializeWindow() { ZeroMemory(&mWindow, sizeof(mWindow)); mWindow.cbSize = sizeof(WNDCLASSEX); mWindow.style = CS_CLASSDC; mWindow.lpfnWndProc = WndProc; mWindow.hInstance = mInstance; mWindow.hIcon = LoadIcon(nullptr, IDI_APPLICATION); mWindow.hIconSm = LoadIcon(nullptr, IDI_APPLICATION); mWindow.hCursor = LoadCursor(nullptr, IDC_ARROW); mWindow.hbrBackground = GetSysColorBrush(COLOR_BTNFACE); mWindow.lpszClassName = mWindowClass.c_str(); RECT windowRectangle = { 0L, 0L, (LONG)mScreenWidth, (LONG)mScreenHeight }; AdjustWindowRect(&windowRectangle, WS_OVERLAPPEDWINDOW, FALSE); RegisterClassEx(&mWindow); POINT center = CenterWindow(mScreenWidth, mScreenHeight); mWindowHandle = CreateWindow(mWindowClass.c_str(), mWindowTitle.c_str(), WS_OVERLAPPEDWINDOW, center.x, center.y, windowRectangle.right - windowRectangle.left, windowRectangle.bottom - windowRectangle.top, nullptr, nullptr, mInstance, nullptr); ShowWindow(mWindowHandle, mShowCommand); UpdateWindow(mWindowHandle); } void Game::Shutdown() { delete[] g_D3D->executablePath; UnregisterClass(mWindowClass.c_str(), mWindow.hInstance); } Library::Game* Game::m_game = nullptr; LRESULT WINAPI Game::WndProc(HWND windowHandle, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DESTROY: PostQuitMessage(0); return 0; case WM_RBUTTONDOWN: Game::GetGame()->OnMouseButtonDown(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); break; case WM_MOUSEMOVE: Game::GetGame()->OnMouseMoved(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); break; } return DefWindowProc(windowHandle, message, wParam, lParam); } POINT Game::CenterWindow(int windowWidth, int windowHeight) { int screenWidth = GetSystemMetrics(SM_CXSCREEN); int screenHeight = GetSystemMetrics(SM_CYSCREEN); POINT center; center.x = (screenWidth - windowWidth) / 2; center.y = (screenHeight - windowHeight) / 2; return center; } void Game::OnKeyboardInput(const GameTime& gt) { const float dt = (float)gt.ElapsedGameTime(); if (GetAsyncKeyState('W') & 0x8000) g_D3D->camera->Walk(10.0f*dt); if (GetAsyncKeyState('S') & 0x8000) g_D3D->camera->Walk(-10.0f*dt); if (GetAsyncKeyState('A') & 0x8000) g_D3D->camera->Strafe(-10.0f*dt); if (GetAsyncKeyState('D') & 0x8000) g_D3D->camera->Strafe(10.0f*dt); g_D3D->camera->UpdateViewMatrix(); } }
24.05
247
0.660291
Esentiel
4a8f63e74471854af4ba806b8fb385a0ac512238
2,170
cpp
C++
2. Searching, Sorting and Order Statistics/mergeSort.cpp
eashwaranRaghu/Data-Structures-and-Algorithms
3aad0f1da3d95b572fbb1950c770198bd042a80f
[ "MIT" ]
6
2020-01-29T14:05:56.000Z
2021-04-24T04:37:27.000Z
2. Searching, Sorting and Order Statistics/mergeSort.cpp
eashwaranRaghu/Data-Structures-and-Algorithms
3aad0f1da3d95b572fbb1950c770198bd042a80f
[ "MIT" ]
null
null
null
2. Searching, Sorting and Order Statistics/mergeSort.cpp
eashwaranRaghu/Data-Structures-and-Algorithms
3aad0f1da3d95b572fbb1950c770198bd042a80f
[ "MIT" ]
1
2020-05-22T06:37:20.000Z
2020-05-22T06:37:20.000Z
// Created on 06-07-2019 18:33:24 by necronomicon #include <bits/stdc++.h> using namespace std; #define MP make_pair #define PB push_back #define ARR_MAX (int)1e5 //Max array length #define INF (int)1e9 //10^9 #define EPS 1e-9 //10^-9 #define MOD 1000000007 //10^9+7 #define PI 3.1415926535897932384626433832795 typedef long int int32; typedef unsigned long int uint32; typedef long long int int64; typedef unsigned long long int uint64; typedef pair<int, int> Pii; typedef vector<int> Vi; typedef vector<string> Vs; typedef vector<Pii> VPii; typedef vector<Vi> VVi; typedef map<int,int> Mii; typedef set<int> Si; typedef multimap<int,int> MMii; typedef multiset<int> MSi; typedef unordered_map<int,int> UMii; typedef unordered_set<int> USi; typedef unordered_multimap<int,int> UMMii; typedef unordered_multiset<int> UMSi; typedef priority_queue<int> PQi; typedef queue<int> Qi; typedef deque<int> DQi; void merge(Vi &v, int l, int mid, int r) { Vi u; int i=l, j=mid; while(i<mid && j<=r) { if(v[i] == v[j]) { u.push_back(v[i]); u.push_back(v[j]); i++; j++; } else if(v[i] < v[j]) { u.push_back(v[i]); i++; } else { u.push_back(v[j]); j++; } } while(i<mid) { u.push_back(v[i]); i++; } while(j <= r) { u.push_back(v[j]); j++; } for (int idx = l, idy=0; idx <= r; idx++, idy++) { v[idx] = u[idy]; } } void merge(Vi &v, int l, int r){ if(l == r) return; int mid = (l+r)/2; merge(v, l, mid); merge(v, mid+1, r); // inplace_merge(v.begin()+l, v.begin()+mid+1, v.begin()+r+1); merge(v, l, mid+1, r); } int main () { Vi v; v.push_back(3); v.push_back(-1); v.push_back(3); v.push_back(0); v.push_back(3); v.push_back(-1); v.push_back(3); v.push_back(0); merge(v, 0, v.size()-1); std::for_each(std::begin(v), std::end(v), [](int a) {cout << a << ' ';});cout << endl; return EXIT_SUCCESS; }
24.659091
91
0.541935
eashwaranRaghu
4a9350a18e915784e92cf4d9455ba65e0768aa7c
4,349
cpp
C++
roborts_planning/local_planner/src/robot_position_cost.cpp
zhaozengj/ICRA2020-JLU-TARS_GO-Navigation
ffb0ded4332c793c9fef1031e45d40aeb08f41ca
[ "BSD-3-Clause" ]
63
2020-09-23T14:31:33.000Z
2022-03-16T05:51:31.000Z
roborts_planning/local_planner/src/robot_position_cost.cpp
zhaozengj/ICRA2020-JLU-TARS_GO-Navigation
ffb0ded4332c793c9fef1031e45d40aeb08f41ca
[ "BSD-3-Clause" ]
6
2020-12-04T06:10:24.000Z
2021-06-01T08:37:05.000Z
robot2019-ros/roborts_planning/local_planner/src/robot_position_cost.cpp
junhuizhou/ROS_Learning
bb3a0c867ba2bd147bbd59176cf1224c09a63914
[ "MIT" ]
22
2020-09-23T11:31:58.000Z
2022-03-16T05:52:00.000Z
/**************************************************************************** * Copyright (C) 2019 RoboMaster. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ***************************************************************************/ #include "local_planner/robot_position_cost.h" namespace roborts_local_planner { RobotPositionCost::RobotPositionCost(const roborts_costmap::Costmap2D& cost_map) : costmap_(cost_map) { } RobotPositionCost::~RobotPositionCost() { } double RobotPositionCost::PointCost(int x, int y) { unsigned char cost = costmap_.GetCost(x, y); if(cost == LETHAL_OBSTACLE || cost == NO_INFORMATION){ return -1; } return cost; } double RobotPositionCost::LineCost(int x0, int x1, int y0, int y1) { double line_cost = 0.0; double point_cost = -1.0; for(FastLineIterator line( x0, y0, x1, y1 ); line.IsValid(); line.Advance()) { point_cost = PointCost(line.GetX(), line.GetY()); //current point's cost if(point_cost < 0){ return -1; } if(line_cost < point_cost){ line_cost = point_cost; } } return line_cost; } double RobotPositionCost::FootprintCost (const Eigen::Vector2d& position, const std::vector<Eigen::Vector2d>& footprint) { unsigned int cell_x, cell_y; if (!costmap_.World2Map(position.coeffRef(0), position.coeffRef(1), cell_x, cell_y)) { return -1.0; } if (footprint.size() < 3) { unsigned char cost = costmap_.GetCost(cell_x, cell_y); if (cost == LETHAL_OBSTACLE || cost == NO_INFORMATION /*|| cost == INSCRIBED_INFLATED_OBSTACLE*/) { return -1.0; } return cost; } unsigned int x0, x1, y0, y1; double line_cost = 0.0; double footprint_cost = 0.0; for(unsigned int i = 0; i < footprint.size() - 1; ++i) { if (!costmap_.World2Map(footprint[i].coeffRef(0), footprint[i].coeffRef(1), x0, y0)) { return -1.0; } if(!costmap_.World2Map(footprint[i + 1].coeffRef(0), footprint[i + 1].coeffRef(1), x1, y1)) { return -1.0; } line_cost = LineCost(x0, x1, y0, y1); footprint_cost = std::max(line_cost, footprint_cost); if(line_cost < 0) { return -1.0; } } if(!costmap_.World2Map(footprint.back().coeffRef(0), footprint.back().coeffRef(1), x0, y0)) { return -1.0; } if(!costmap_.World2Map(footprint.front().coeffRef(0), footprint.front().coeffRef(1), x1, y1)) { return -1.0; } line_cost = LineCost(x0, x1, y0, y1); footprint_cost = std::max(line_cost, footprint_cost); if(line_cost < 0) { return -1.0; } return footprint_cost; } double RobotPositionCost::FootprintCost(double x, double y, double theta, const std::vector<Eigen::Vector2d> &footprint_spec, double inscribed_radius, double circumscribed_radius) { double cos_th = cos(theta); double sin_th = sin(theta); std::vector<Eigen::Vector2d> oriented_footprint; for (unsigned int i = 0; i < footprint_spec.size(); ++i) { Eigen::Vector2d new_pt; new_pt.coeffRef(0) = x + (footprint_spec[i].coeffRef(0) * cos_th - footprint_spec[i].coeffRef(1) * sin_th); new_pt.coeffRef(1) = y + (footprint_spec[i].coeffRef(0) * sin_th + footprint_spec[i].coeffRef(1) * cos_th); oriented_footprint.push_back(new_pt); } Eigen::Vector2d robot_position; robot_position.coeffRef(0) = x; robot_position.coeffRef(1) = y; if(inscribed_radius==0.0){ CalculateMinAndMaxDistances(footprint_spec, inscribed_radius, circumscribed_radius); } return FootprintCost(robot_position, oriented_footprint); } } // namespace roborts_local_planner
30.412587
122
0.62957
zhaozengj
4a965868a3e81cef35a9da8dd7e8fe07489d7196
370
hpp
C++
modules/scene_manager/include/builtin_interfaces/msg/duration.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
1
2020-05-19T14:33:49.000Z
2020-05-19T14:33:49.000Z
ros2_mod_ws/install/include/builtin_interfaces/msg/duration.hpp
mintforpeople/robobo-ros2-ios-port
1a5650304bd41060925ebba41d6c861d5062bfae
[ "Apache-2.0" ]
3
2019-11-14T12:20:06.000Z
2020-08-07T13:51:10.000Z
modules/scene_manager/include/builtin_interfaces/msg/duration.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
// generated from rosidl_generator_cpp/resource/msg.hpp.em // generated code does not contain a copyright notice #ifndef BUILTIN_INTERFACES__MSG__DURATION_HPP_ #define BUILTIN_INTERFACES__MSG__DURATION_HPP_ #include "builtin_interfaces/msg/duration__struct.hpp" #include "builtin_interfaces/msg/duration__traits.hpp" #endif // BUILTIN_INTERFACES__MSG__DURATION_HPP_
33.636364
58
0.856757
Omnirobotic
4aa1d971b273de5ee8bfdfc8d46b85c913f273f2
7,063
cpp
C++
flashsim/run_bimodal.cpp
praneethyerramothu/AOSPROJECT1
1792b1c484bc35e334093b9a5c2fb4d20b3f4452
[ "BSD-4-Clause-UC" ]
6
2015-05-31T15:28:30.000Z
2022-02-10T04:39:18.000Z
flashsim/run_bimodal.cpp
praneethyerramothu/AOSPROJECT1
1792b1c484bc35e334093b9a5c2fb4d20b3f4452
[ "BSD-4-Clause-UC" ]
null
null
null
flashsim/run_bimodal.cpp
praneethyerramothu/AOSPROJECT1
1792b1c484bc35e334093b9a5c2fb4d20b3f4452
[ "BSD-4-Clause-UC" ]
6
2015-03-23T02:49:28.000Z
2018-10-30T06:44:40.000Z
/* FlashSim is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. */ /* FlashSim is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ /* You should have received a copy of the GNU General Public License * along with FlashSim. If not, see <http://www.gnu.org/licenses/>. */ /****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/types.h> #include <string.h> #include <iostream> #include <vector> #include <algorithm> #include <math.h> #include "ssd.h" using namespace ssd; /** * Benchmark plan * 1. The number of writes should be the size of the device simulated. * 2. Trim a designated area. E.g. 256MB, measure the time it takes to perform the trim with the implemented FTLs. * 3. Measure the time required to overwrite the area and compare with the other FTLs. * 4. Create a report with shows the differences in response time using CDF's. * * Test assumes a 6GB SSD, with Block-size 64 and Page size 2048 bytes. */ int main(int argc, char **argv){ long vaddr; double arrive_time; load_config(); print_config(NULL); Ssd ssd; printf("INITIALIZING SSD Bimodal\n"); srandom(1); int preIO = SSD_SIZE * PACKAGE_SIZE * DIE_SIZE * PLANE_SIZE * BLOCK_SIZE; if (FTL_IMPLEMENTATION == 0) // PAGE preIO -= 16*BLOCK_SIZE; if (FTL_IMPLEMENTATION == 1) // BAST preIO -= (BAST_LOG_PAGE_LIMIT*BLOCK_SIZE)*2; if (FTL_IMPLEMENTATION == 2) // FAST preIO -= (FAST_LOG_PAGE_LIMIT*BLOCK_SIZE)*1.1; if (FTL_IMPLEMENTATION > 2) // DFTL BIFTL preIO -= 512; int deviceSize = 3145216; if (preIO > deviceSize) preIO = deviceSize; printf("Writes %i pages for startup out of %i total pages.\n", preIO, SSD_SIZE * PACKAGE_SIZE * DIE_SIZE * PLANE_SIZE * BLOCK_SIZE); double start_time = 0; double timeMultiplier = 10000; double read_time = 0; double write_time = 0; double trim_time = 0; unsigned long num_reads = 0; unsigned long num_writes = 0; unsigned long num_trims = 0; std::vector<double> avgsTrim; std::vector<double> avgsWrite1; std::vector<double> avgsRead1; std::vector<double> avgsRead2; std::vector<double> avgsRead3; std::vector<double> avgsTrim2; std::vector<double> avgsWrite2; std::vector<double> avgsRead4; std::vector<double> avgsWrite3; avgsTrim.reserve(1024*64); avgsWrite1.reserve(1024*64); avgsRead1.reserve(1024*64); avgsRead2.reserve(1024*64); avgsRead3.reserve(1024*64); avgsTrim2.reserve(1024*64); avgsWrite2.reserve(1024*64); avgsRead4.reserve(1024*64); avgsWrite3.reserve(1024*64); // Reset statistics ssd.reset_statistics(); // 1. Write random to the size of the device srand(1); double afterFormatStartTime = 0; //for (int i=0; i<preIO/3*2;i++) for (int i=0; i<preIO*1.1;i++) //for (int i=0; i<700000;i++) { long int r = random()%preIO; double d = ssd.event_arrive(WRITE, r, 1, afterFormatStartTime); afterFormatStartTime += d; if (i % 10000 == 0) printf("Wrote %i %f\n", i,d ); } start_time = afterFormatStartTime; // Reset statistics ssd.reset_statistics(); // 2. Trim an area. ( We let in be 512MB (offset 131072 pages or 2048 blocks) into the address space, and then 256MB (1024 blocks or 65536 pages) ) int startTrim = 2048*64; //131072 int endTrim = 3072*64; //196608 /* Test 1 */ for (int i=startTrim; i<endTrim;i++) { trim_time = ssd.event_arrive(TRIM, i, 1, ((start_time+arrive_time)*timeMultiplier)); avgsTrim.push_back(trim_time); num_trims++; arrive_time += trim_time; if (i % 1000 == 0) printf("Trim: %i %f\n", i, trim_time); } for (int i=startTrim; i<endTrim;i++) { trim_time = ssd.event_arrive(READ, i, 1, ((start_time+arrive_time)*timeMultiplier)); avgsRead1.push_back(trim_time); num_trims++; arrive_time += trim_time; if (i % 1000 == 0) printf("Read: %i %f\n", i, trim_time); } for (int i=startTrim; i<endTrim;i++) { trim_time = ssd.event_arrive(READ, i, 1, ((start_time+arrive_time)*timeMultiplier)); avgsRead2.push_back(trim_time); num_trims++; arrive_time += trim_time; if (i % 1000 == 0) printf("Read: %i %f\n", i, trim_time); } for (int i=startTrim; i<endTrim;i++) { trim_time = ssd.event_arrive(WRITE, i, 1, ((start_time+arrive_time)*timeMultiplier)); avgsWrite1.push_back(trim_time); num_trims++; arrive_time += trim_time; if (i % 1000 == 0) printf("Write: %i %f\n", i, trim_time); } for (int i=startTrim; i<endTrim;i++) { trim_time = ssd.event_arrive(READ, i, 1, ((start_time+arrive_time)*timeMultiplier)); avgsRead3.push_back(trim_time); num_trims++; arrive_time += trim_time; if (i % 1000 == 0) printf("Read: %i %f\n", i, trim_time); } /* Test 1 */ for (int i=startTrim; i<endTrim;i++) { trim_time = ssd.event_arrive(TRIM, i, 1, ((start_time+arrive_time)*timeMultiplier)); avgsTrim2.push_back(trim_time); num_trims++; arrive_time += trim_time; if (trim_time > 400) printf("Trim: %i %f\n", i, trim_time); } for (int i=startTrim; i<endTrim;i++) { trim_time = ssd.event_arrive(WRITE, i, 1, ((start_time+arrive_time)*timeMultiplier)); avgsWrite2.push_back(trim_time); num_trims++; arrive_time += trim_time; if (i % 1000 == 0) printf("Write: %i %f\n", i, trim_time); } for (int i=startTrim; i<endTrim;i++) { trim_time = ssd.event_arrive(READ, i, 1, ((start_time+arrive_time)*timeMultiplier)); avgsRead4.push_back(trim_time); num_trims++; arrive_time += trim_time; if (i % 1000 == 0) printf("Read: %i %f\n", i, trim_time); } // // 1. Write random to the size of the device // for (int i=0; i<700000;i++) // { // long int r = (random()%preIO-200000)+200000; // double d = ssd.event_arrive(WRITE, r, 1, afterFormatStartTime); // afterFormatStartTime += d; // // if (i % 10000 == 0) // printf("Wrote %i %f\n", i,d ); // } // // for (int i=startTrim; i<endTrim;i++) // { // // trim_time = ssd.event_arrive(WRITE, i, 1, ((start_time+arrive_time)*timeMultiplier)); // avgsWrite3.push_back(trim_time); // num_trims++; // // arrive_time += trim_time; // // if (i % 1000 == 0) // printf("Write: %i %f\n", i, trim_time); // // } ssd.print_ftl_statistics(); FILE *logFile = NULL; if ((logFile = fopen("output.log", "w")) == NULL) { printf("Output file cannot be written to.\n"); exit(-1); } fprintf(logFile, "Trim;Read1;Read2;Write1;Read3;Trim2;Write2;Read4;Write3\n"); for (size_t i=0;i<avgsTrim.size();i++) { fprintf(logFile, "%f;%f;%f;%f;%f;%f;%f;%f\n", avgsTrim[i],avgsRead1[i], avgsRead2[i], avgsWrite1[i], avgsRead3[i], avgsTrim2[i], avgsWrite2[i], avgsRead4[i]); } fclose(logFile); ssd.print_ftl_statistics(); ssd.print_statistics(); printf("Finished.\n"); return 0; }
23.622074
160
0.665015
praneethyerramothu
4aa6d314a3832c719990129e6bdfbd5b8b7d7c12
3,835
cpp
C++
Firmware/graphics/platform/gs_platform_layer.cpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
39
2019-10-23T12:06:16.000Z
2022-01-26T04:28:29.000Z
Firmware/graphics/platform/gs_platform_layer.cpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
20
2020-03-21T20:21:46.000Z
2021-11-19T14:34:03.000Z
Firmware/graphics/platform/gs_platform_layer.cpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
7
2019-10-18T09:44:10.000Z
2021-06-11T13:05:16.000Z
#include "gs_platform_layer.hpp" #include <logger/logger_service.hpp> #include <lvgl.h> #include <utils/CallbackConnector.hpp> #include <utils/CoroUtils.hpp> #if defined(USE_HARDWARE_DISPLAY_BACKEND) #include <app_timer.h> #include <nrf_drv_clock.h> namespace { APP_TIMER_DEF(m_gfxEllapsedTimerId); } namespace Graphics { #endif #if defined USE_HARDWARE_DISPLAY_BACKEND PlatformBackend::PlatformBackend() noexcept : m_hardwareDisplayDriver{std::make_unique<TDisplayDriver>()} {}; void PlatformBackend::platformDependentInit(lv_disp_drv_t* _displayDriver) noexcept { m_hardwareDisplayDriver->initialize(); auto hardwareDriverCallback = cbc::obtain_connector( [this](lv_disp_drv_t* _displayDriver, const lv_area_t* _fillArea, lv_color_t* _colorFill) { m_hardwareDisplayDriver->fillRectangle( _fillArea->x1, _fillArea->y1, _fillArea->x2, _fillArea->y2, reinterpret_cast<std::uint16_t*>(_colorFill)); }); auto waitCallback = cbc::obtain_connector([](lv_disp_drv_t* disp_drv) { CoroUtils::CoroQueueMainLoop::GetInstance().processQueue(); Simple::Lib::ExecuteLaterPool::Instance().processQueue(); }); if (!_displayDriver) return; _displayDriver->flush_cb = hardwareDriverCallback; _displayDriver->wait_cb = waitCallback; m_hardwareDisplayDriver->onRectArreaFilled.connect( [this, _displayDriver] { lv_disp_flush_ready(_displayDriver); }); } void PlatformBackend::initPlatformGfxTimer() noexcept { ret_code_t errorCode{}; auto gfxTimerCallback = cbc::obtain_connector([this](void* _pContext) { lv_tick_inc(LvglNotificationTime); }); errorCode = app_timer_create(&m_gfxEllapsedTimerId, APP_TIMER_MODE_REPEATED, gfxTimerCallback); APP_ERROR_CHECK(errorCode); errorCode = app_timer_start(m_gfxEllapsedTimerId, APP_TIMER_TICKS(LvglNotificationTime), nullptr); APP_ERROR_CHECK(errorCode); } void PlatformBackend::executeLvTaskHandler() noexcept { if (!m_hardwareDisplayDriver->isInitialized()) return; lv_task_handler(); } } // namespace Graphics #endif #if defined USE_SDL_BACKEND #include <chrono> #include <thread> #include <lv_drivers/indev/keyboard.h> #include <lv_drivers/indev/mouse.h> #include <lv_drivers/sdl/sdl.h> #include <lvgl/lvgl.h> #include <fmt/format.h> namespace Graphics { PlatformBackend::PlatformBackend() noexcept = default; void PlatformBackend::platformDependentInit(lv_disp_drv_t* _displayDriver) noexcept { sdl_init(); _displayDriver->flush_cb = sdl_display_flush; } void PlatformBackend::initPlatformGfxTimer() noexcept { indevPlatformInit(); } void PlatformBackend::indevPlatformInit() noexcept { lv_indev_drv_init(&m_indevDriver); m_indevDriver.type = LV_INDEV_TYPE_POINTER; m_indevDriver.read_cb = sdl_mouse_read; lv_indev_drv_register(&m_indevDriver); auto memoryMonitorTask = cbc::obtain_connector([this](lv_timer_t* _param) { memoryMonitor(_param); }); lv_timer_create(memoryMonitorTask, 10, nullptr); } void PlatformBackend::memoryMonitor(lv_timer_t* _param) noexcept { static_cast<void>(_param); lv_mem_monitor_t moninor{}; lv_mem_monitor(&moninor); LOG_DEBUG_ENDL(fmt::format( "Used: {} , {}% fragmentation: {}, biggest free: {}", static_cast<std::uint32_t>(moninor.total_size - moninor.free_size), static_cast<std::uint32_t>(moninor.used_pct), static_cast<std::uint32_t>(moninor.frag_pct), static_cast<std::uint32_t>(moninor.free_biggest_size))); } void PlatformBackend::executeLvTaskHandler() noexcept { lv_task_handler(); std::this_thread::sleep_for(std::chrono::milliseconds(LvglNotificationTime)); } } // namespace Graphics #endif
26.631944
99
0.727249
ValentiWorkLearning
4aa940f73668fe3f41ec8125687e703e20a846a7
2,236
cpp
C++
src/world.cpp
dgraves/RayTracerChallenge
c052f1f270354c46c60abdcce303fe9314181b3c
[ "MIT" ]
null
null
null
src/world.cpp
dgraves/RayTracerChallenge
c052f1f270354c46c60abdcce303fe9314181b3c
[ "MIT" ]
null
null
null
src/world.cpp
dgraves/RayTracerChallenge
c052f1f270354c46c60abdcce303fe9314181b3c
[ "MIT" ]
null
null
null
/* ** Copyright(c) 2020-2021 Dustin Graves ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this softwareand associated documentation files(the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and /or sell ** copies of the Software, and to permit persons to whom the Software is ** furnished to do so, subject to the following conditions : ** ** The above copyright notice and this permission notice shall be included in all ** copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** SOFTWARE. */ #include "world.h" #include "color.h" #include "material.h" #include "matrix44.h" #include "point.h" #include "sphere.h" #include <cassert> namespace rtc { Intersections World::Intersect(const Ray& ray) const { Intersections::Values values{}; for (const auto& object : objects_) { assert(object && "World::Intersect attempted to process an invalid object"); object->Intersect(ray, values); } return Intersections{ std::move(values), true }; } World World::GetDefault() { return World{ { PointLight{ rtc::Point{ -10.0, 10.0, -10.0 }, rtc::Color{ 1.0, 1.0, 1.0} } }, { Sphere::Create( rtc::Material{ rtc::Color{ 0.8, 1.0, 0.6 }, rtc::Material::GetDefaultAmbient(), 0.7, 0.2, rtc::Material::GetDefaultShininess() }), Sphere::Create(rtc::Matrix44::Scaling(0.5, 0.5, 0.5)) } }; } }
33.878788
90
0.620304
dgraves
4aacbff9375b6d8d19ebc76ada72545850832f9e
2,031
cpp
C++
Homework/2. HW/3/Vehicle.cpp
Ignatoff/FMI-OOP-2018
a84c250e4b6d2df3135708a2fbe0447b9533858a
[ "MIT" ]
3
2018-03-20T18:28:53.000Z
2018-06-06T17:29:13.000Z
Homework/2. HW/3/Vehicle.cpp
Ignatoff/FMI-OOP-2018
a84c250e4b6d2df3135708a2fbe0447b9533858a
[ "MIT" ]
null
null
null
Homework/2. HW/3/Vehicle.cpp
Ignatoff/FMI-OOP-2018
a84c250e4b6d2df3135708a2fbe0447b9533858a
[ "MIT" ]
null
null
null
#include "Vehicle.h" #include <cstring> #include<iostream> Vehicle::Vehicle() : year(0), mileage(0) { make = new char{ '\0' }; model = new char{ '\0' }; color = new char{ '\0' }; } Vehicle::Vehicle(const Vehicle & rhs) : year(rhs.year), mileage(rhs.mileage) { this->make = new char[strlen(rhs.make) + 1]; strcpy(this->make, rhs.make); this->model = new char[strlen(rhs.model) + 1]; strcpy(this->model, rhs.model); this->color = new char[strlen(rhs.color) + 1]; strcpy(this->color, rhs.color); } Vehicle::Vehicle(const char * make, const char * model, const char * color, const int & year, const int & mileage) { setYear(year); setMileage(mileage); this->make = new char[strlen(make) + 1]; strcpy(this->make, make); this->model = new char[strlen(model) + 1]; strcpy(this->model, model); this->color = new char[strlen(color) + 1]; strcpy(this->color, color); } Vehicle & Vehicle::operator=(const Vehicle & rhs) { if (this != &rhs) { setYear(rhs.year); setMileage(rhs.mileage); setModel(rhs.model); setMake(rhs.make); setColor(rhs.color); } return *this; } Vehicle::~Vehicle() { delete[] make; delete[] model; delete[] color; } void Vehicle::setMake(const char * make) { delete[] this->make; this->make = new char[strlen(make) + 1]; strcpy(this->make, make); } void Vehicle::setModel(const char * model) { delete[] this->model; this->model = new char[strlen(model) + 1]; strcpy(this->model, model); } void Vehicle::setColor(const char * color) { delete[] this->color; this->color = new char[strlen(color) + 1]; strcpy(this->color, color); } void Vehicle::setYear(const int & year) { this->year = year; } void Vehicle::setMileage(const int & mileage) { this->mileage = mileage; } const char * Vehicle::getMake() const { return make; } const char * Vehicle::getModel() const { return model; } const char * Vehicle::getColor() const { return color; } const int & Vehicle::getYear() const { return year; } const int & Vehicle::getMileage() const { return mileage; }
17.815789
114
0.655342
Ignatoff
4aad6aafb42d5e06d25a3b10cdab0872126cb6be
1,372
cpp
C++
src/process_handler.cpp
bbkgl/ljstack
79acebbed7502b5d9b81223c4b0bf6514072752d
[ "MIT" ]
1
2020-06-06T10:14:27.000Z
2020-06-06T10:14:27.000Z
src/process_handler.cpp
bbkgl/ljstack
79acebbed7502b5d9b81223c4b0bf6514072752d
[ "MIT" ]
null
null
null
src/process_handler.cpp
bbkgl/ljstack
79acebbed7502b5d9b81223c4b0bf6514072752d
[ "MIT" ]
null
null
null
#include "process_handler.h" #include <sys/ptrace.h> #include <iostream> #include "utils.h" namespace ljstack { ProcessHandler::ProcessHandler(pid_t pid) { pid_ = pid; elf_file_ = "/proc/" + std::to_string(pid) + "/exe"; mem_file_ = "/proc/" + std::to_string(pid) + "/mem"; maps_file_ = "/proc/" + std::to_string(pid) + "/maps"; mem_fd_ = open(mem_file_.c_str(), O_RDONLY); status_ = RUNING; if (mem_fd_ < 0) { LOG_ERR("Can't open %s, maybe the process %d not exist!", mem_file_.c_str(), pid_); exit(-1); } get_elf_type(); } ProcessHandler::~ProcessHandler() { close(mem_fd_); } int ProcessHandler::attach() { if (-1 == ptrace(PTRACE_ATTACH, pid_, nullptr, nullptr)) { LOG_ERR("attach process (%d) failed (%s)!", pid_, strerror(errno)); return -1; } if (!wait4stop()) { LOG_ERR("wait process (%d) failed (%s)!", pid_, strerror(errno)); return -1; } status_ = STOP; return 0; } int ProcessHandler::detach() { if (-1 == ptrace(PTRACE_DETACH, pid_, nullptr, nullptr)) { LOG_ERR("detach process (%d) failed (%s)!", pid_, strerror(errno)); return -1; } status_ = RUNING; return 0; } }
29.191489
95
0.526239
bbkgl
4ab0e3bd0172dd4e7325ce797ee16e0e14d5f017
224
cpp
C++
aoj/introduction/IntroductIonToProgramming/1_1_D_Watch/Main.cpp
KoKumagai/exercises
256b226d3e094f9f67352d75619b392a168eb4d1
[ "MIT" ]
null
null
null
aoj/introduction/IntroductIonToProgramming/1_1_D_Watch/Main.cpp
KoKumagai/exercises
256b226d3e094f9f67352d75619b392a168eb4d1
[ "MIT" ]
null
null
null
aoj/introduction/IntroductIonToProgramming/1_1_D_Watch/Main.cpp
KoKumagai/exercises
256b226d3e094f9f67352d75619b392a168eb4d1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int x; cin >> x; int h, m, s; h = x / 60 / 60; m = x / 60 % 60; s = x % 60; cout << h << ":" << m << ":" << s << endl; return 0; }
11.2
46
0.388393
KoKumagai
4ab20887ada5fa6851c4b411bf107d28cf0b99bd
4,964
cpp
C++
test/ui/test-notebook.cpp
antonvw/wex
c4c41c660c9967623093a1b407af034c59a56be8
[ "MIT" ]
3
2020-03-01T06:30:30.000Z
2021-05-01T05:11:48.000Z
test/ui/test-notebook.cpp
antonvw/wex
c4c41c660c9967623093a1b407af034c59a56be8
[ "MIT" ]
96
2020-01-18T18:25:48.000Z
2022-03-26T12:26:50.000Z
test/ui/test-notebook.cpp
antonvw/wex
c4c41c660c9967623093a1b407af034c59a56be8
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Name: test-notebook.cpp // Purpose: Implementation for wex unit testing // Author: Anton van Wezenbeek // Copyright: (c) 2021 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wex/defs.h> #include <wex/notebook.h> #include "test.h" TEST_CASE("wex::notebook") { auto* notebook = new wex::notebook(); frame()->pane_add(notebook); auto* page1 = new wxWindow(frame(), wxID_ANY); auto* page2 = new wxWindow(frame(), wxID_ANY); auto* page3 = new wxWindow(frame(), wxID_ANY); auto* page4 = new wxWindow(frame(), wxID_ANY); auto* page5 = new wxWindow(frame(), wxID_ANY); REQUIRE( notebook->add_page(wex::data::notebook().page(page1).key("key1")) != nullptr); REQUIRE( notebook->add_page(wex::data::notebook().page(page2).key("key2")) != nullptr); REQUIRE( notebook->add_page(wex::data::notebook().page(page3).key("key3")) != nullptr); // pages: 0,1,2 keys: key1, key2, key3 pages page1,page2,page3. SUBCASE("access") { REQUIRE(notebook->key_by_page(page1) == "key1"); REQUIRE(notebook->page_by_key("key1") == page1); REQUIRE(notebook->page_index_by_key("key1") == 0); REQUIRE(notebook->page_index_by_key("xxx") == wxNOT_FOUND); } SUBCASE("change") { REQUIRE(notebook->set_page_text("key1", "keyx", "hello")); REQUIRE(notebook->page_by_key("keyx") == page1); // pages: 0,1,2 keys: keyx, key2, key3 pages page1, page2,page3. REQUIRE(notebook->page_index_by_key("key1") == wxNOT_FOUND); REQUIRE(notebook->delete_page("keyx")); REQUIRE(notebook->page_by_key("keyx") == nullptr); REQUIRE(notebook->delete_page("key2")); REQUIRE(!notebook->delete_page("xxx")); // pages: 0 keys: key3 pages:page3. } SUBCASE("insert") { REQUIRE( notebook->insert_page(wex::data::notebook().page(page4).key("KEY1")) != nullptr); REQUIRE( notebook->insert_page(wex::data::notebook().page(page5).key("KEY0")) != nullptr); // pages: 0,1,2 keys: KEY0, KEY1, key3 pages: page5,page4,page3. REQUIRE(notebook->page_index_by_key("KEY0") == 0); REQUIRE(notebook->page_index_by_key("KEY1") == 1); REQUIRE(notebook->set_selection("KEY1") == page4); REQUIRE(notebook->current_page_key() == "KEY1"); REQUIRE(notebook->set_selection("key3") == page3); REQUIRE(notebook->current_page_key() == "key3"); REQUIRE(notebook->set_selection("XXX") == nullptr); REQUIRE(notebook->current_page_key() == "key3"); REQUIRE(notebook->change_selection("KEY1") == "key3"); REQUIRE(notebook->current_page_key() == "KEY1"); REQUIRE(notebook->change_selection("key3") == "KEY1"); REQUIRE(notebook->current_page_key() == "key3"); REQUIRE(notebook->change_selection("XXX") == std::string()); REQUIRE(notebook->current_page_key() == "key3"); REQUIRE(notebook->delete_page("KEY0")); REQUIRE(notebook->delete_page("KEY1")); REQUIRE(notebook->delete_page("key3")); REQUIRE(notebook->GetPageCount() == 2); // 5 - 3 } SUBCASE("for_each") { REQUIRE(notebook->DeleteAllPages()); auto* stc_x = new ui_stc(); auto* stc_y = new ui_stc(); auto* stc_z = new ui_stc(); REQUIRE( notebook->add_page(wex::data::notebook().page(stc_x).key("key1")) != nullptr); REQUIRE( notebook->add_page(wex::data::notebook().page(stc_y).key("key2")) != nullptr); REQUIRE( notebook->add_page(wex::data::notebook().page(stc_z).key("key3")) != nullptr); REQUIRE(notebook->for_each<ui_stc>(wex::ID_ALL_STC_SET_LEXER)); REQUIRE(notebook->for_each<ui_stc>(wex::ID_ALL_STC_SET_LEXER_THEME)); REQUIRE(notebook->for_each<ui_stc>(wex::ID_ALL_STC_SYNC)); REQUIRE(notebook->for_each<ui_stc>(wex::ID_ALL_CONFIG_GET)); REQUIRE(notebook->for_each<ui_stc>(wex::ID_ALL_SAVE)); REQUIRE(notebook->for_each<ui_stc>(wex::ID_ALL_CLOSE_OTHERS)); REQUIRE(notebook->GetPageCount() == 1); REQUIRE(notebook->for_each<ui_stc>(wex::ID_ALL_CLOSE)); REQUIRE(notebook->GetPageCount() == 0); } SUBCASE("rearrange") { notebook->rearrange(wxLEFT); notebook->rearrange(wxBOTTOM); } SUBCASE("split") { REQUIRE(notebook->DeleteAllPages()); auto* pagev = new wxWindow(frame(), wxID_ANY); REQUIRE( notebook->add_page(wex::data::notebook().page(pagev).key("keyv")) != nullptr); // split having only one page REQUIRE(notebook->split("keyv", wxRIGHT)); auto* pagew = new wxWindow(frame(), wxID_ANY); REQUIRE( notebook->add_page(wex::data::notebook().page(pagew).key("keyw")) != nullptr); // split using incorrect key REQUIRE(!notebook->split("err", wxRIGHT)); REQUIRE(notebook->split("keyv", wxRIGHT)); REQUIRE(notebook->GetPageCount() == 2); } }
33.540541
80
0.628727
antonvw
4ab3c0991c7152a8eea98c164081f70e628cd900
3,436
cpp
C++
Atom/src/Atom/Renderer/Renderer.cpp
NikiNatov/Atom
027082f32708589b9005fb2356142cdef20f453f
[ "Apache-2.0" ]
null
null
null
Atom/src/Atom/Renderer/Renderer.cpp
NikiNatov/Atom
027082f32708589b9005fb2356142cdef20f453f
[ "Apache-2.0" ]
null
null
null
Atom/src/Atom/Renderer/Renderer.cpp
NikiNatov/Atom
027082f32708589b9005fb2356142cdef20f453f
[ "Apache-2.0" ]
null
null
null
#include "atompch.h" #include "Renderer.h" namespace Atom { Scope<Renderer> Renderer::ms_Instance = CreateScope<Renderer>(); // ----------------------------------------------------------------------------------------------------------------------------- void Renderer::Initialize() { // Create adapter ms_Instance->m_Adapter = Adapter::CreateAdapter(AdapterPreference::HighPerformance); ATOM_ENGINE_INFO("GPU: {0}", ms_Instance->m_Adapter->GetDescription()); ATOM_ENGINE_INFO("Video Memory: {0} MB", MB(ms_Instance->m_Adapter->GetVideoMemory())); ATOM_ENGINE_INFO("System Memory: {0} MB", MB(ms_Instance->m_Adapter->GetSystemMemory())); ATOM_ENGINE_INFO("Shared Memory: {0} MB", MB(ms_Instance->m_Adapter->GetSharedMemory())); // Create device ms_Instance->m_Device = Device::CreateDevice(ms_Instance->m_Adapter.get()); // Create command queue CommandQueueDesc commandQueueDesc = {}; commandQueueDesc.Priority = CommandQueuePriority::Normal; commandQueueDesc.Type = CommandListType::Direct; ms_Instance->m_GraphicsQueue = CommandQueue::CreateCommandQueue(ms_Instance->m_Device.get(), commandQueueDesc); // Create allocators for (u32 i = 0; i < FRAME_COUNT; i++) { ms_Instance->m_FrameAllocators[i] = CommandAllocator::CreateCommandAllocator(ms_Instance->m_Device.get(), CommandListType::Direct); } // Create command list ms_Instance->m_GraphicsCommandList = GraphicsCommandList::CreateGraphicsCommandList(ms_Instance->m_Device.get(), CommandListType::Direct, ms_Instance->m_FrameAllocators[0].get()); } // ----------------------------------------------------------------------------------------------------------------------------- void Renderer::BeginFrame() { u32 frameIndex = ms_Instance->m_CurrentFrameIndex; // Wait for the GPU to catch up ms_Instance->m_GraphicsQueue->WaitForFenceValue(ms_Instance->m_FrameFenceValues[frameIndex]); // Reset the current frame command allocator ms_Instance->m_FrameAllocators[frameIndex]->Reset(); // Reset the graphics command list with the current frame allocator ms_Instance->m_GraphicsCommandList->Reset(ms_Instance->m_FrameAllocators[frameIndex].get()); } // ----------------------------------------------------------------------------------------------------------------------------- void Renderer::EndFrame() { // Close the command list ms_Instance->m_GraphicsCommandList->Close(); // Execute the commands, signal the command queue and update the frame's fence value ms_Instance->m_GraphicsQueue->ExecuteCommandList(ms_Instance->m_GraphicsCommandList.get()); ms_Instance->m_FrameFenceValues[ms_Instance->m_CurrentFrameIndex] = ms_Instance->m_GraphicsQueue->Signal(); // Increment frame index ms_Instance->m_CurrentFrameIndex = (ms_Instance->m_CurrentFrameIndex + 1) % FRAME_COUNT; } // ----------------------------------------------------------------------------------------------------------------------------- void Renderer::Flush() { for (u32 i = 0; i < FRAME_COUNT; i++) ms_Instance->m_GraphicsQueue->WaitForFenceValue(ms_Instance->m_FrameFenceValues[i]); ms_Instance->m_CurrentFrameIndex = 0; } }
45.813333
187
0.584109
NikiNatov
4ab6661ddb728ef72d31e0e534d84893b2031b53
16,687
cpp
C++
src/duyebase/public/duye_cfg_mgr.cpp
tencupofkaiwater/duye
72257379f91e7a0db5ffefbb7e7a74dc0a255f67
[ "Unlicense" ]
null
null
null
src/duyebase/public/duye_cfg_mgr.cpp
tencupofkaiwater/duye
72257379f91e7a0db5ffefbb7e7a74dc0a255f67
[ "Unlicense" ]
null
null
null
src/duyebase/public/duye_cfg_mgr.cpp
tencupofkaiwater/duye
72257379f91e7a0db5ffefbb7e7a74dc0a255f67
[ "Unlicense" ]
null
null
null
/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file duye_cfg_mgr.cpp * @version * @brief * @author duye * @date 2014-09-28 * @note * * 1. 2014-09-28 duye Created this file */ #include <string> #include <list> #include <duye_logger.h> #include <duye_helper.h> #include <duye_cfg_mgr.h> namespace duye { static const int8* DUYE_LOG_PREFIX = "duye.public.cfgmgr"; CfgMgr::CfgMgr() {} CfgMgr::~CfgMgr() {} CfgMgr& CfgMgr::ins() { static CfgMgr ins; return ins; } bool CfgMgr::load(const std::string& filePath) { m_cfgFilePath = filePath; if (!m_cfgDoc.loadFile(m_cfgFilePath)) { DUYE_ERROR("load configuration file %s failed:%s, line:%d", m_cfgFilePath.c_str(), m_cfgDoc.errorDesc(), m_cfgDoc.errorRow()); return false; } return true; } bool CfgMgr::setValue(const std::string& path, const bool value, const std::string& attName) { return setText(path, StrHelper::toStr(value), attName); } bool CfgMgr::setValue(const std::string& path, const bool value) { return setText(path, StrHelper::toStr(value), ""); } bool CfgMgr::setValue(const std::string& path, const int32 value, const std::string& attName) { return setText(path, StrHelper::toStr(value), attName); } bool CfgMgr::setValue(const std::string& path, const int32 value) { return setText(path, StrHelper::toStr(value), ""); } bool CfgMgr::setValue(const std::string& path, const int64 value, const std::string& attName) { return setText(path, StrHelper::toStr(value), attName); } bool CfgMgr::setValue(const std::string& path, const int64 value) { return setText(path, StrHelper::toStr(value), ""); } bool CfgMgr::setValue(const std::string& path, const uint32 value, const std::string& attName) { return setText(path, StrHelper::toStr(value), attName); } bool CfgMgr::setValue(const std::string& path, const uint32 value) { return setText(path, StrHelper::toStr(value), ""); } bool CfgMgr::setValue(const std::string& path, const uint64 value, const std::string& attName) { return setText(path, StrHelper::toStr(value), attName); } bool CfgMgr::setValue(const std::string& path, const uint64 value) { return setText(path, StrHelper::toStr(value), ""); } bool CfgMgr::setValue(const std::string& path, const int8* value, const std::string& attName) { return setText(path, StrHelper::toStr(value), attName); } bool CfgMgr::setValue(const std::string& path, const int8* value) { return setText(path, StrHelper::toStr(value), ""); } bool CfgMgr::setValue(const std::string& path, const std::string& value, const std::string& attName) { return setText(path, value, attName); } bool CfgMgr::setValue(const std::string& path, const std::string& value) { return setText(path, value, ""); } bool CfgMgr::getValue(const std::string& path, bool& value, const std::string& attName) { if (attName.empty()) return false; std::string text = getText(path, attName); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } value = StrHelper::toBool(text); return true; } bool CfgMgr::getValue(const std::string& path, bool& value) { std::string text = getText(path, ""); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } value = StrHelper::toBool(text); return true; } bool CfgMgr::getValue(const std::string& path, int16& value, const std::string& attName) { if (attName.empty()) return false; std::string text = getText(path, attName); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } if (!StrHelper::isNums(text)) { DUYE_ERROR("content isn't number"); return false; } value = (int32)StrHelper::toInt(text); return true; } bool CfgMgr::getValue(const std::string& path, int16& value) { std::string text = getText(path, ""); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } if (!StrHelper::isNums(text)) { DUYE_ERROR("content isn't number"); return false; } value = (int32)StrHelper::toInt(text); return true; } bool CfgMgr::getValue(const std::string& path, int32& value, const std::string& attName) { if (attName.empty()) return false; std::string text = getText(path, attName); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } if (!StrHelper::isNums(text)) { DUYE_ERROR("content isn't number"); return false; } value = (int32)StrHelper::toInt(text); return true; } bool CfgMgr::getValue(const std::string& path, int32& value) { std::string text = getText(path, ""); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } if (!StrHelper::isNums(text)) { DUYE_ERROR("content isn't number"); return false; } value = (int32)StrHelper::toInt(text); return true; } bool CfgMgr::getValue(const std::string& path, int64& value, const std::string& attName) { if (attName.empty()) return false; std::string text = getText(path, attName); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } if (!StrHelper::isNums(text)) { DUYE_ERROR("content isn't number"); return false; } value = (int64)StrHelper::toInt(text); return true; } bool CfgMgr::getValue(const std::string& path, int64& value) { std::string text = getText(path, ""); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } if (!StrHelper::isNums(text)) { DUYE_ERROR("content isn't number"); return false; } value = (int64)StrHelper::toInt(text); return true; } bool CfgMgr::getValue(const std::string& path, uint16& value, const std::string& attName) { if (attName.empty()) return false; std::string text = getText(path, attName); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } if (!StrHelper::isNums(text)) { DUYE_ERROR("content isn't number"); return false; } value = (uint32)StrHelper::toInt(text); return true; } bool CfgMgr::getValue(const std::string& path, uint16& value) { std::string text = getText(path, ""); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } if (!StrHelper::isNums(text)) { DUYE_ERROR("content isn't number"); return false; } value = (uint32)StrHelper::toInt(text); return true; } bool CfgMgr::getValue(const std::string& path, uint32& value, const std::string& attName) { if (attName.empty()) return false; std::string text = getText(path, attName); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } if (!StrHelper::isNums(text)) { DUYE_ERROR("content isn't number"); return false; } value = (uint32)StrHelper::toInt(text); return true; } bool CfgMgr::getValue(const std::string& path, uint32& value) { std::string text = getText(path, ""); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } if (!StrHelper::isNums(text)) { DUYE_ERROR("content isn't number"); return false; } value = (uint32)StrHelper::toInt(text); return true; } bool CfgMgr::getValue(const std::string& path, uint64& value, const std::string& attName) { if (attName.empty()) return false; std::string text = getText(path, attName); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } if (!StrHelper::isNums(text)) { DUYE_ERROR("content isn't number"); return false; } value = (uint64)StrHelper::toInt(text); return true; } bool CfgMgr::getValue(const std::string& path, uint64& value) { std::string text = getText(path, ""); if (text.empty()) { DUYE_ERROR("content is empty"); return false; } if (!StrHelper::isNums(text)) { DUYE_ERROR("content isn't number"); return false; } value = (uint64)StrHelper::toInt(text); return true; } bool CfgMgr::getValue(const std::string& path, std::string& value, const std::string& attName) { if (attName.empty()) return false; std::string text = getText(path, attName); // if (text.empty()) { // DUYE_ERROR("content is empty"); // return false; // } value = text; return true; } bool CfgMgr::getValue(const std::string& path, std::string& value) { std::string text = getText(path, ""); // if (text.empty()) { // DUYE_ERROR("content is empty"); // return false; // } value = text; return true; } std::string CfgMgr::getValue(const std::string& path, const std::string& attName) { if (attName.empty()) { DUYE_ERROR("input 'attName' is empty"); return ""; } return getText(path, attName); } std::string CfgMgr::getValue(const int8* path, const int8* attName) { if (!attName || strlen(attName) == 0) { DUYE_ERROR("input attName == null or is empty"); return ""; } return getText(path, attName); } std::string CfgMgr::getValue(const std::string& path) { return getText(path, ""); } std::string CfgMgr::getValue(const int8* path) { if (!path) { DUYE_ERROR("input path == null"); return ""; } return getText(path, ""); } bool CfgMgr::getNodes(const std::string& path, const std::list<std::string>& attrList, ParamNodeList& nodeList) { DUYE_TRACE("path : %s", path.c_str()); std::list<duye::NodeAndNamePair> node_and_name_list; if (!parsePath(path, node_and_name_list)) return false; std::list<NodeAndNamePair>::const_iterator iter = node_and_name_list.begin(); for (; iter != node_and_name_list.end(); ++iter) { DUYE_TRACE("node:%s, name:%s", iter->node.c_str(), iter->name.c_str()); if (iter->node == node_and_name_list.back().node) { DUYE_TRACE("last node:%s", iter->node.c_str()); if (iter->node.empty() || !iter->name.empty()) { DUYE_ERROR("path(%s) error:last node not need name value", path.c_str()); } } else if (iter->node.empty() || iter->name.empty()) { DUYE_ERROR("path(%s) error:node or name is empty", path.c_str()); return false; } } if (node_and_name_list.empty()) { DUYE_TRACE("node_and_name_list is empty"); return false; } return getNodeList(node_and_name_list, attrList, nodeList); } bool CfgMgr::save() { return true; } void CfgMgr::toString(std::string& outString) { //m_cfgDoc.print(); } const std::string& CfgMgr::getConfPath() const { return m_cfgFilePath; } std::string CfgMgr::getText(const std::string& path, const std::string& attName) { std::list<duye::NodeAndNamePair> node_and_name_list; if (!parsePath(path, node_and_name_list)) return ""; std::list<NodeAndNamePair>::const_iterator iter = node_and_name_list.begin(); for (; iter != node_and_name_list.end(); ++iter) { if (iter->node.empty() || iter->name.empty()) { DUYE_ERROR("path(%s) error:node or name is empty", path.c_str()); return ""; } } XmlElement* node = getNode(node_and_name_list); if (!node) { DUYE_ERROR("getNode() == null, by path:'%s'", path.c_str()); return ""; } if (attName.empty()) { DUYE_INFO("getText"); const int8* text = node->getText(); if (text) { return text; } else { return ""; } } else { DUYE_INFO("getAttribute"); const std::string* value = node->attribute(attName); if (value) { return *value; } else { return ""; } } return ""; } bool CfgMgr::setText(const std::string& path, const std::string& val, const std::string& attName) { std::list<duye::NodeAndNamePair> node_and_name_list; if (!parsePath(path, node_and_name_list)) return false; std::list<NodeAndNamePair>::const_iterator iter = node_and_name_list.begin(); for (; iter != node_and_name_list.end(); ++iter) { if (iter->node.empty() || iter->name.empty()) { DUYE_ERROR("path(%s) error:node or name is empty", path.c_str()); return ""; } } XmlElement* node = getNode(node_and_name_list); if (!node) return false; if (attName.empty()) { node->setText(val.c_str()); } else { node->setAttribute(attName, val); } m_cfgDoc.saveFile(m_cfgFilePath); return true; } bool CfgMgr::parsePath(const std::string& path, std::list<duye::NodeAndNamePair>& nodeAndNameList) { std::list<std::string> node_list; StrHelper::split(path, '.', node_list); if (node_list.empty()) { DUYE_ERROR("parse path by '.' error"); return false; } std::list<std::string>::iterator iter = node_list.begin(); for (; iter != node_list.end(); ++iter) { std::vector<std::string> node_name_vec; StrHelper::split(*iter, ':', node_name_vec); if (node_name_vec.size() == 1) { nodeAndNameList.push_back(NodeAndNamePair(node_name_vec[0], "")); } else if (node_name_vec.size() == 2) { nodeAndNameList.push_back(NodeAndNamePair(node_name_vec[0], node_name_vec[1])); } else { DUYE_ERROR("parse path:'%s' by ':' to get node and name error", path.c_str()); return false; } } return true; } XmlElement* CfgMgr::getNode(const std::list<duye::NodeAndNamePair>& nodeAndNameList) { XmlElement* root = m_cfgDoc.rootElement(); if (root == NULL) { DUYE_ERROR("root == NULL"); return NULL; } XmlElement* node = root->firstChildElement(); if (node == NULL) { DUYE_ERROR("FirstChildElement == NULL"); return NULL; } XmlElement* found_node = node; uint32 depth = nodeAndNameList.size(); uint32 curr_depth = 0; std::list<NodeAndNamePair>::const_iterator pair_iter = nodeAndNameList.begin(); for (; pair_iter != nodeAndNameList.end(); ++pair_iter) { curr_depth++; if (pair_iter->node.empty() || pair_iter->name.empty()) { DUYE_ERROR("node or name is empty"); break; } DUYE_TRACE("node:%s, name:%s", pair_iter->node.c_str(), pair_iter->name.c_str()); found_node = recursion(found_node, pair_iter->node, pair_iter->name); if (!found_node) { DUYE_ERROR("found_node == null"); break; } else if (curr_depth != depth) { found_node = found_node->firstChildElement(); } } return found_node; } bool CfgMgr::getNodeList(const std::list<duye::NodeAndNamePair>& nodeAndNameList, const std::list<std::string>& attrList, ParamNodeList& nodeList) { DUYE_TRACE("in %s", __FUNCTION__); XmlElement* root = m_cfgDoc.rootElement(); if (root == NULL) { DUYE_ERROR("root == NULL"); return false; } XmlElement* node = root->firstChildElement(); if (node == NULL) { DUYE_ERROR("FirstChildElement == NULL"); return false; } XmlElement* found_node = node; bool judge_name = true; uint32 depth = nodeAndNameList.size(); uint32 curr_depth = 0; std::list<NodeAndNamePair>::const_iterator iter = nodeAndNameList.begin(); for (; iter != nodeAndNameList.end(); ++iter) { curr_depth++; if (iter->name.empty()) { judge_name = false; } DUYE_TRACE("node:%s, name:%s", iter->node.c_str(), iter->name.c_str()); found_node = recursion(found_node, iter->node, iter->name, judge_name); if (!found_node) { break; } else if (curr_depth != depth) { found_node = found_node->firstChildElement(); } } if (found_node) { uint32 cnt = 1; std::string last_node_name = nodeAndNameList.back().node; while (found_node) { if (found_node->value() != last_node_name) { found_node = found_node->nextSiblingElement(); continue; } DUYE_TRACE("%d. get attr in node:%s", cnt++, last_node_name.c_str()); ParamNode param_node; std::list<std::string>::const_iterator attr_iter = attrList.begin(); for (; attr_iter != attrList.end(); ++attr_iter) { const int8* value = found_node->attribute(attr_iter->c_str()); if (value) { param_node.addPair(*attr_iter, value); DUYE_TRACE("add pair(%s, %s)", attr_iter->c_str(), value); } } nodeList.push_back(param_node); found_node = found_node->nextSiblingElement(); } } else { DUYE_ERROR("found_node == null"); return false; } return true; } XmlElement* CfgMgr::recursion(XmlElement* node, const std::string& node_name, const std::string& name_attr, bool judge_name) { if (!node) { DUYE_ERROR("node == null"); return NULL; } if (judge_name && name_attr.empty()) { DUYE_ERROR("judge_name == true, but name_attr is empty"); return NULL; } if (node->value() != node_name) { return recursion(node->nextSiblingElement(), node_name, name_attr, judge_name); } else if (judge_name) { const int8* value = node->attribute("name"); if (value == NULL) { DUYE_ERROR("node->attribute('name') = null"); return NULL; } DUYE_TRACE("node->attribute('name') = %s, name_attr=%s", value, name_attr.c_str()); if (value != name_attr) { DUYE_TRACE("node->attribute('name') = %s, input:%s, unmatch", value, name_attr.c_str()); return recursion(node->nextSiblingElement(), node_name, name_attr, judge_name); } } DUYE_TRACE("find node = %s", node_name.c_str()); return node; } }
23.703125
148
0.657997
tencupofkaiwater
4aba81f25f6ba8e2bae7ed7617f927368fa53d63
591
cpp
C++
Source/Number Theory/prime factorization log(n).cpp
Nadim-Mahmud/Competitive-Programming
3f88ef395a334e2c8ca450f912f8ebbe1c3dd584
[ "MIT" ]
7
2019-11-09T09:08:41.000Z
2022-03-04T13:29:32.000Z
Source/Number Theory/prime factorization log(n).cpp
Nadim-Mahmud/Competitive-Programming-Template
3f88ef395a334e2c8ca450f912f8ebbe1c3dd584
[ "MIT" ]
null
null
null
Source/Number Theory/prime factorization log(n).cpp
Nadim-Mahmud/Competitive-Programming-Template
3f88ef395a334e2c8ca450f912f8ebbe1c3dd584
[ "MIT" ]
3
2019-12-30T13:56:06.000Z
2022-03-04T13:29:34.000Z
/** Description : prime factorization Complexity : O(log n) Limitation : memory complexity O(n) so it works up to 10^7 */ const int N = 10000000; int lp[N+1]; vector<int> pr; void sieve(){ int i,j; for (i=2; i<=N; ++i) { if (lp[i] == 0) { lp[i] = i; pr.push_back (i); } for (j=0; j<(int)pr.size() && pr[j]<=lp[i] && i*pr[j]<=N; ++j) lp[i*pr[j]] = pr[j]; } } vector<int> prime_fact(int n){ vector<int> pf; while (n != 1){ pf.push_back(lp[n]); n = n / lp[n]; } return pf; }
19.064516
70
0.458545
Nadim-Mahmud
3858015b65a9eaad1922c5efee9c70e3194cf41f
1,927
cpp
C++
String/ReverseString_bytedace.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
String/ReverseString_bytedace.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
String/ReverseString_bytedace.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
/* *********************************************************************** > File Name: ReverseString_bytedace.cpp > Author: zzy > Mail: 942744575@qq.com > Created Time: Mon 05 Aug 2019 02:45:41 PM CST ********************************************************************** */ #include <stdio.h> #include <vector> #include <string> #include <stdio.h> #include <climits> #include <iostream> #include <gtest/gtest.h> using std::vector; using std::string; /* * 给定一个字符串,逐个翻转字符串中的每个单词。 * 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 * 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 * */ class Solution { public: enum SpaceStat{ NOT_NEED = 0, CAN_USE = 1, USED = 2, }; void reverseWords_r(string &s, int begin, int end) { while (begin <= end) { std::swap(s[begin++] , s[end--]); } } string reverseWords(string s) { int length = s.length(); int vaild = 0; std::vector<int> indexs; SpaceStat stat = NOT_NEED; for (int i = 0; i < length; ++i) { // 循环去掉多余的空格 if (s[i] != ' ') { s[vaild++] = s[i]; stat = SpaceStat::CAN_USE; } else if (stat == SpaceStat::CAN_USE) { s[vaild++] = s[i]; stat = SpaceStat::USED; } } if (s[vaild-1] == ' ') { // 最后的一个空格去掉, vaild 就是有效的字符串长度 vaild --; } std::cout << s.substr(0, vaild) << " length: " << vaild <<"\n"; int begin = 0, end = 0; for (int i = 0; i <= vaild; ++i) { if (i == vaild) { reverseWords_r(s, begin, vaild - 1); } else if (s[i] == ' ') { end = i - 1; reverseWords_r(s, begin, end); begin = i + 1; } } reverseWords_r(s, 0, vaild-1); return s.substr(0, vaild); } }; TEST(testCase,test0) { } int main(int argc, char* argv[]) { Solution s; std::string s1 = " hello world xx "; std::string s2 = "the sky is blue"; std::cout << s.reverseWords(s1) << "\n"; std::cout << s.reverseWords(s2) << "\n"; testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }
21.651685
74
0.533472
obviouskkk
385eb1c3ef8438880fecd93e92cd77b0f9bc0935
512
cpp
C++
leetcode/887. Super Egg Drop/s1.cpp
zhuohuwu0603/leetcode_cpp_lzl124631x
6a579328810ef4651de00fde0505934d3028d9c7
[ "Fair" ]
787
2017-05-12T05:19:57.000Z
2022-03-30T12:19:52.000Z
leetcode/887. Super Egg Drop/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
8
2020-03-16T05:55:38.000Z
2022-03-09T17:19:17.000Z
leetcode/887. Super Egg Drop/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
247
2017-04-30T15:07:50.000Z
2022-03-30T09:58:57.000Z
// OJ: https://leetcode.com/problems/super-egg-drop/ // Author: github.com/lzl124631x // Time: O(SK) where S is the result. // Space: O(K) // Ref: https://leetcode.com/problems/super-egg-drop/discuss/159508/easy-to-understand class Solution { public: int superEggDrop(int K, int N) { int step = 0; vector<int> dp(K + 1); for (; dp[K] < N; ++step) { for (int k = K; k > 0; --k) { dp[k] += 1 + dp[k - 1]; } } return step; } };
28.444444
86
0.517578
zhuohuwu0603
38602916c390743cea63142bc34a6b82cc056873
498
cpp
C++
Talon/source/Talon/Window/Button.cpp
afradley/Pteron
7bb1c8de010a175e4a22dfcf93aa696b12b317f4
[ "MIT" ]
null
null
null
Talon/source/Talon/Window/Button.cpp
afradley/Pteron
7bb1c8de010a175e4a22dfcf93aa696b12b317f4
[ "MIT" ]
null
null
null
Talon/source/Talon/Window/Button.cpp
afradley/Pteron
7bb1c8de010a175e4a22dfcf93aa696b12b317f4
[ "MIT" ]
null
null
null
#include <windows.h> #include "Button.h" namespace Talon { static const WindowParams DefaultParams { 0, L"Button", nullptr, BS_PUSHBUTTON /*| BS_ICON*/ | WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, nullptr, nullptr }; Button::Button(Window* parent) : Control(DefaultParams, parent) { } Button::~Button() { } void Button::HandleCommand(WPARAM wParam) { Control::HandleCommand(wParam); switch ((HIWORD(wParam))) { case BN_CLICKED: { break; } } } }
11.581395
54
0.62249
afradley
3869daa791a5f42ddfbea1636d01fb0ec4e4f1e4
1,266
hpp
C++
includes/InstanceManager.hpp
razerx100/Sol
c9d7da09207aada805be277a9cc2ab2d0f9d4e02
[ "MIT" ]
null
null
null
includes/InstanceManager.hpp
razerx100/Sol
c9d7da09207aada805be277a9cc2ab2d0f9d4e02
[ "MIT" ]
null
null
null
includes/InstanceManager.hpp
razerx100/Sol
c9d7da09207aada805be277a9cc2ab2d0f9d4e02
[ "MIT" ]
null
null
null
#ifndef __STATIC_INSTANCES_HPP__ #define __STATIC_INSTANCES_HPP__ #include <InputManager.hpp> #include <Window.hpp> #include <GraphicsEngine.hpp> #include <IApp.hpp> #include <ObjectManager.hpp> #include <IModelContainer.hpp> class AppInst : public _ObjectManager<IApp, AppInst> { public: static void Init(); }; enum class IOType { Pluto }; class IOInst : public _ObjectManager<InputManager, IOInst> { public: static void Init(IOType type = IOType::Pluto); }; enum class WindowType { Luna }; class WindowInst : public _ObjectManager<Window, WindowInst> { public: static void Init( int width, int height, InputManager* ioMan, const char* name, WindowType type = WindowType::Luna ); }; enum class RendererType { Terra, Gaia }; class RendererInst : public _ObjectManager<GraphicsEngine, RendererInst> { public: static void Init( const char* appName, void* windowHandle, void* moduleHandle, std::uint32_t width, std::uint32_t height, RendererType type = RendererType::Gaia, std::uint8_t bufferCount = 2u ); static void SetAPI(RendererType type) noexcept; }; class ModelContInst : public _ObjectManager<IModelContainer, ModelContInst> { public: static void Init(); }; #endif
21.1
78
0.71564
razerx100
386d47a5616cd4f31fcc547986f6f5d00dc2a198
794
cpp
C++
src/engine/graphics/opengl/buffers/vertexArray.cpp
Overpeek/Overpeek-Engine
3df11072378ba870033a19cd09fb332bcc4c466d
[ "MIT" ]
13
2020-01-10T16:36:46.000Z
2021-08-09T09:24:47.000Z
src/engine/graphics/opengl/buffers/vertexArray.cpp
Overpeek/Overpeek-Engine
3df11072378ba870033a19cd09fb332bcc4c466d
[ "MIT" ]
1
2020-01-16T11:03:49.000Z
2020-01-16T11:11:15.000Z
src/engine/graphics/opengl/buffers/vertexArray.cpp
Overpeek/Overpeek-Engine
3df11072378ba870033a19cd09fb332bcc4c466d
[ "MIT" ]
1
2020-02-06T21:22:47.000Z
2020-02-06T21:22:47.000Z
#include "vertexArray.hpp" #include "engine/internal_libs.hpp" #include "buffer.hpp" #include "engine/graphics/opengl/gl_include.hpp" namespace oe::graphics { VertexArray::VertexArray() { glGenVertexArrays(1, &p_id); bind(); } VertexArray::~VertexArray() { for (VertexBuffer* v : p_buffers) delete v; glDeleteVertexArrays(1, &p_id); } void VertexArray::addBuffer(VertexBuffer* buffer, unsigned int location) { p_buffers.push_back(buffer); bind(); buffer->bind(); glEnableVertexAttribArray(location); glVertexAttribPointer(location, buffer->getComponentsPerVertex(), GL_FLOAT, GL_FALSE, 0, 0); } void VertexArray::bind() { glBindVertexArray(p_id); } void VertexArray::unbind() { glBindVertexArray(0); } }
18.045455
95
0.677582
Overpeek
386ee5f01779736e0803db46170e666f413690e8
531
hh
C++
inc/Powierzchnia.hh
lukasz-pawlos/Dron
27d0a0d5c30e7dd0bb3d74dd8bdf940bca96d430
[ "MIT" ]
null
null
null
inc/Powierzchnia.hh
lukasz-pawlos/Dron
27d0a0d5c30e7dd0bb3d74dd8bdf940bca96d430
[ "MIT" ]
null
null
null
inc/Powierzchnia.hh
lukasz-pawlos/Dron
27d0a0d5c30e7dd0bb3d74dd8bdf940bca96d430
[ "MIT" ]
null
null
null
#ifndef POWIERZCHNIA_HH #define POWIERZCHNIA_HH #include <iostream> #include "Dr3D_gnuplot_api.hh" #include "SWektor.hh" #include "MacierzOb.hh" using std::vector; using drawNS::Point3D; using drawNS::APIGnuPlot3D; using std::cout; using std::endl; class Powierzchnia { protected: int ID = -1; std::shared_ptr<drawNS::Draw3DAPI> api; public: virtual void Rysuj() ; void ustaw_api(std::shared_ptr<drawNS::Draw3DAPI> API) {api =API;}; std::shared_ptr<drawNS::Draw3DAPI> daj_api() const {return api;}; }; #endif
14.75
67
0.723164
lukasz-pawlos
38734a9a563b82ace9dee057d6950e39d47bb710
98,151
hpp
C++
contrib/TAMM/src/tamm/tamm_utils.hpp
smferdous1/gfcc
e7112c0dd60566266728e4d51ea8d30aea4b775d
[ "MIT" ]
null
null
null
contrib/TAMM/src/tamm/tamm_utils.hpp
smferdous1/gfcc
e7112c0dd60566266728e4d51ea8d30aea4b775d
[ "MIT" ]
null
null
null
contrib/TAMM/src/tamm/tamm_utils.hpp
smferdous1/gfcc
e7112c0dd60566266728e4d51ea8d30aea4b775d
[ "MIT" ]
null
null
null
#ifndef TAMM_TAMM_UTILS_HPP_ #define TAMM_TAMM_UTILS_HPP_ #include <vector> #include <chrono> #include <random> #include <fstream> #include <type_traits> #include <iomanip> #include <hdf5.h> #define IO_ISIRREG 1 namespace tamm { // From integer type to integer type template <typename from> constexpr typename std::enable_if<std::is_integral<from>::value && std::is_integral<int64_t>::value, int64_t>::type cd_ncast(const from& value) { return static_cast<int64_t>(value & (static_cast<typename std::make_unsigned<from>::type>(-1))); } /** * @brief Overload of << operator for printing Tensor blocks * * @tparam T template type for Tensor element type * @param [in] os output stream * @param [in] vec vector to be printed * @returns the reference to input output stream with vector elements printed * out */ template<typename T> std::ostream& operator<<(std::ostream& os, std::vector<T>& vec) { os << "["; for(auto& x : vec) os << x << ","; os << "]";// << std::endl; return os; } template <typename Arg, typename... Args> void print_varlist(Arg&& arg, Args&&... args) { std::cout << std::forward<Arg>(arg); ((std::cout << ',' << std::forward<Args>(args)), ...); std::cout << std::endl; } template<typename T> double compute_tensor_size(const Tensor<T>& tensor) { auto lt = tensor(); double size = 0; for(auto it : tensor.loop_nest()) { auto blockid = internal::translate_blockid(it, lt); if(!tensor.is_non_zero(blockid)) continue; size += tensor.block_size(blockid); } return size; } template<typename T> MPI_Datatype mpi_type(){ using std::is_same_v; if constexpr(is_same_v<int, T>) return MPI_INT; if constexpr(is_same_v<int64_t, T>) return MPI_INT64_T; else if constexpr(is_same_v<float, T>) return MPI_FLOAT; else if constexpr(is_same_v<double, T>) return MPI_DOUBLE; else if constexpr(is_same_v<std::complex<float>, T>) return MPI_COMPLEX; else if constexpr(is_same_v<std::complex<double>, T>) return MPI_DOUBLE_COMPLEX; } /** * @brief Prints a Tensor object * * @tparam T template type for Tensor element type * @param [in] tensor input Tensor object */ template<typename T> void print_tensor(const Tensor<T>& tensor, std::string filename="") { std::stringstream tstring; auto lt = tensor(); int ndims = tensor.num_modes(); std::vector<int64_t> dims; for(auto tis: tensor.tiled_index_spaces()) dims.push_back(tis.index_space().num_indices()); tstring << "tensor dims = " << dims << std::endl; tstring << "actual tensor size = " << tensor.size() << std::endl; for(auto it : tensor.loop_nest()) { auto blockid = internal::translate_blockid(it, lt); if(!tensor.is_non_zero(blockid)) continue; TAMM_SIZE size = tensor.block_size(blockid); std::vector<T> buf(size); tensor.get(blockid, buf); auto bdims = tensor.block_dims(blockid); auto boffsets = tensor.block_offsets(blockid); tstring << "blockid: " << blockid << ", "; tstring << "block_offsets: " << boffsets << ", "; tstring << "bdims: " << bdims << ", size: " << size << std::endl; for(TAMM_SIZE i = 0; i < size; i++) { if(i%6==0) tstring << "\n"; if constexpr(tamm::internal::is_complex_v<T>) { if(buf[i].real() > 0.0000000000001 || buf[i].real() < -0.0000000000001) tstring << std::fixed << std::setw( 10 ) << std::setprecision(10) << buf[i] << " "; } else { if(buf[i] > 0.0000000000001 || buf[i] < -0.0000000000001) tstring << std::fixed << std::setw( 10 ) << std::setprecision(10) << buf[i] << " "; } } tstring << std::endl; } if(!filename.empty()){ std::ofstream tos(filename+".txt", std::ios::out); if(!tos) std::cerr << "Error opening file " << filename << std::endl; tos << tstring.str() << std::endl; tos.close(); } else std::cout << tstring.str(); } template<typename T> void print_tensor_all(const Tensor<T>& tensor, std::string filename="") { std::stringstream tstring; auto lt = tensor(); int ndims = tensor.num_modes(); std::vector<int64_t> dims; for(auto tis: tensor.tiled_index_spaces()) dims.push_back(tis.index_space().num_indices()); tstring << "tensor dims = " << dims << std::endl; tstring << "actual tensor size = " << tensor.size() << std::endl; for(auto it : tensor.loop_nest()) { auto blockid = internal::translate_blockid(it, lt); if(!tensor.is_non_zero(blockid)) continue; TAMM_SIZE size = tensor.block_size(blockid); std::vector<T> buf(size); tensor.get(blockid, buf); auto bdims = tensor.block_dims(blockid); auto boffsets = tensor.block_offsets(blockid); tstring << "blockid: " << blockid << ", "; tstring << "block_offsets: " << boffsets << ", "; tstring << "bdims: " << bdims << ", size: " << size << std::endl; for(TAMM_SIZE i = 0; i < size; i++) { if(i%6==0) tstring << "\n"; tstring << std::fixed << std::setw( 10 ) << std::setprecision(10) << buf[i] << " "; } tstring << std::endl; } if(!filename.empty()){ std::ofstream tos(filename+".txt", std::ios::out); if(!tos) std::cerr << "Error opening file " << filename << std::endl; tos << tstring.str() << std::endl; tos.close(); } else std::cout << tstring.str(); } /** * @brief Print values in tensor greater than given threshold * * @tparam T template type for Tensor element type * @param [in] tensor input Tensor object * @param [in] printol given threshold [default=0.05] * * @warning This function only works sequentially */ template<typename T> void print_max_above_threshold(const Tensor<T>& tensor, double printtol=0.05) { auto lt = tensor(); for(auto it : tensor.loop_nest()) { auto blockid = internal::translate_blockid(it, lt); if(!tensor.is_non_zero(blockid)) continue; TAMM_SIZE size = tensor.block_size(blockid); std::vector<T> buf(size); tensor.get(blockid, buf); auto bdims = tensor.block_dims(blockid); for(TAMM_SIZE i = 0; i < size; i++) { if constexpr(tamm::internal::is_complex_v<T>) { if(std::fabs(buf[i].real()) > printtol) std::cout << buf[i] << std::endl; } else { if(std::fabs(buf[i]) > printtol) std::cout << buf[i] << std::endl; } } std::cout << std::endl; } } /** * @brief Get the scalar value from the Tensor * * @tparam T template type for Tensor element type * @param [in] tensor input Tensor object * @returns a scalar value in type T * * @warning This function only works with scalar (zero dimensional) Tensor * objects */ template<typename T> T get_scalar(Tensor<T>& tensor) { T scalar; EXPECTS(tensor.num_modes() == 0); tensor.get({}, {&scalar, 1}); return scalar; } template<typename TensorType> ExecutionContext& get_ec(LabeledTensor<TensorType> ltensor) { return *(ltensor.tensor().execution_context()); } /** * @brief Update input LabeledTensor object with a lambda function * * @tparam T template type for Tensor element type * @tparam Func template type for the lambda function * @param [in] labeled_tensor tensor slice to be updated * @param [in] lambda function for updating the tensor */ template<typename T, typename Func> void update_tensor(Tensor<T> tensor, Func lambda) { update_tensor(tensor(),lambda); } template<typename T, typename Func> void update_tensor(LabeledTensor<T> labeled_tensor, Func lambda) { LabelLoopNest loop_nest{labeled_tensor.labels()}; for(const auto& itval : loop_nest) { const IndexVector blockid = internal::translate_blockid(itval, labeled_tensor); size_t size = labeled_tensor.tensor().block_size(blockid); std::vector<T> buf(size); labeled_tensor.tensor().get(blockid, buf); lambda(blockid, buf); labeled_tensor.tensor().put(blockid, buf); } } /** * @brief Update input LabeledTensor object with a lambda function * * @tparam T template type for Tensor element type * @tparam Func template type for the lambda function * @param [in] labeled_tensor tensor slice to be updated * @param [in] lambda function for updating the tensor */ template<typename T, typename Func> void update_tensor_general(Tensor<T> tensor, Func lambda) { update_tensor_general(tensor(),lambda); } template<typename T, typename Func> void update_tensor_general(LabeledTensor<T> labeled_tensor, Func lambda) { LabelLoopNest loop_nest{labeled_tensor.labels()}; for(const auto& itval : loop_nest) { const IndexVector blockid = internal::translate_blockid(itval, labeled_tensor); size_t size = labeled_tensor.tensor().block_size(blockid); std::vector<T> buf(size); labeled_tensor.tensor().get(blockid, buf); lambda(labeled_tensor.tensor(), blockid, buf); labeled_tensor.tensor().put(blockid, buf); } } /** * @brief Construct an ExecutionContext object * * @returns an Execution context * @todo there is possible memory leak as distribution will not be unallocated * when Execution context is destructed */ /*inline ExecutionContext make_execution_context() { ProcGroup* pg = new ProcGroup {ProcGroup::create_coll(GA_MPI_Comm())}; auto* pMM = MemoryManagerGA::create_coll(*pg); Distribution_NW* dist = new Distribution_NW(); RuntimeEngine* re = new RuntimeEngine{}; ExecutionContext *ec = new ExecutionContext(*pg, dist, pMM, re); return *ec; } */ /** * @brief method for getting the sum of the values on the diagonal * * @returns sum of the diagonal values * @warning only defined for NxN tensors */ template<typename TensorType> TensorType trace(Tensor<TensorType> tensor) { return trace(tensor()); } template<typename TensorType> TensorType trace(LabeledTensor<TensorType> ltensor) { ExecutionContext& ec = get_ec(ltensor); TensorType lsumd = 0; TensorType gsumd = 0; Tensor<TensorType> tensor = ltensor.tensor(); // Defined only for NxN tensors EXPECTS(tensor.num_modes() == 2); auto gettrace = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); if(blockid[0] == blockid[1]) { const TAMM_SIZE size = tensor.block_size(blockid); std::vector<TensorType> buf(size); tensor.get(blockid, buf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); auto dim = block_dims[0]; auto offset = block_offset[0]; size_t i = 0; for(auto p = offset; p < offset + dim; p++, i++) { lsumd += buf[i * dim + i]; } } }; block_for(ec, ltensor, gettrace); MPI_Allreduce(&lsumd, &gsumd, 1, mpi_type<TensorType>(), MPI_SUM, ec.pg().comm()); return gsumd; } /** * @brief method for getting the diagonal values in a Tensor * * @returns the diagonal values * @warning only defined for NxN tensors */ template<typename TensorType> std::vector<TensorType> diagonal(Tensor<TensorType> tensor) { return diagonal(tensor()); } template<typename TensorType> std::vector<TensorType> diagonal(LabeledTensor<TensorType> ltensor) { ExecutionContext& ec = get_ec(ltensor); Tensor<TensorType> tensor = ltensor.tensor(); // Defined only for NxN tensors EXPECTS(tensor.num_modes() == 2); LabelLoopNest loop_nest{ltensor.labels()}; std::vector<TensorType> dest; for(const IndexVector& bid : loop_nest) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); if(blockid[0] == blockid[1]) { const TAMM_SIZE size = tensor.block_size(blockid); std::vector<TensorType> buf(size); tensor.get(blockid, buf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); auto dim = block_dims[0]; auto offset = block_offset[0]; size_t i = 0; for(auto p = offset; p < offset + dim; p++, i++) { dest.push_back(buf[i * dim + i]); } } } return dest; } /** * @brief uses a function to fill in elements of a tensor * * @tparam TensorType the type of the elements in the tensor * @param ltensor tensor to operate on * @param func function to fill in the tensor with */ template<typename TensorType> void fill_tensor(Tensor<TensorType> tensor, std::function<void(const IndexVector&, span<TensorType>)> func) { fill_tensor(tensor(),func); } template<typename TensorType> void fill_tensor(LabeledTensor<TensorType> ltensor, std::function<void(const IndexVector&, span<TensorType>)> func) { ExecutionContext& ec = get_ec(ltensor); Tensor<TensorType> tensor = ltensor.tensor(); auto lambda = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<TensorType> dbuf(dsize); // tensor.get(blockid, dbuf); func(blockid,dbuf); tensor.put(blockid, dbuf); }; block_for(ec, ltensor, lambda); } template<typename TensorType> void fill_sparse_tensor(Tensor<TensorType> tensor, std::function<void(const IndexVector&, span<TensorType>)> func) { fill_sparse_tensor(tensor(),func); } template<typename TensorType> void fill_sparse_tensor(LabeledTensor<TensorType> ltensor, std::function<void(const IndexVector&, span<TensorType>)> func) { ExecutionContext& ec = get_ec(ltensor); Tensor<TensorType> tensor = ltensor.tensor(); auto lambda = [&](const IndexVector& bid) { const tamm::TAMM_SIZE dsize = tensor.block_size(bid); const IndexVector blockid = internal::translate_sparse_blockid(bid, ltensor); std::vector<TensorType> dbuf(dsize); // tensor.get(blockid, dbuf); func(blockid,dbuf); tensor.put(bid, dbuf); }; block_for(ec, ltensor, lambda); } template<typename TensorType> std::tuple<int, int> get_subgroup_info(ExecutionContext& gec, Tensor<TensorType> tensor, MPI_Comm &subcomm,int nagg_hint=0) { int nranks = gec.pg().size().value(); long double nelements = 1; //Heuristic: Use 1 agg for every 14gb const long double ne_mb = 131072 * 14.0; const int ndims = tensor.num_modes(); for (auto i=0;i<ndims;i++) nelements *= tensor.tiled_index_spaces()[i].index_space().num_indices(); // nelements = tensor.size(); int nagg = (nelements / (ne_mb * 1024) ) + 1; // const int nnodes = GA_Cluster_nnodes(); const int ppn = GA_Cluster_nprocs(0); const int avail_nodes = std::min(nranks/ppn + 1,GA_Cluster_nnodes()); if(nagg > avail_nodes) nagg = avail_nodes; if(nagg_hint > 0) nagg = nagg_hint; int subranks = nagg * ppn; if(subranks > nranks) subranks = nranks; //TODO: following does not work if gec was created via MPI_Group_incl. MPI_Group group; //, world_group; // MPI_Comm_group(GA_MPI_Comm(), &world_group); auto comm = gec.pg().comm(); MPI_Comm_group(comm,&group); int ranks[subranks]; //,ranks_world[subranks]; for (int i = 0; i < subranks; i++) ranks[i] = i; // MPI_Group_translate_ranks(group, subranks, ranks, world_group, ranks_world); MPI_Group subgroup; MPI_Group_incl(group,subranks,ranks,&subgroup); MPI_Comm_create(comm,subgroup,&subcomm); return std::make_tuple(nagg,ppn); } /** * @brief convert tamm tensor to N-D GA * * @tparam TensorType the type of the elements in the tensor * @param ec ExecutionContext * @param tensor tamm tensor handle * @return GA handle */ template<typename TensorType> int tamm_to_ga(ExecutionContext& ec, Tensor<TensorType>& tensor) { int ndims = tensor.num_modes(); std::vector<int64_t> dims; std::vector<int64_t> chnks(ndims,-1); for(auto tis: tensor.tiled_index_spaces()) dims.push_back(tis.index_space().num_indices()); auto ga_eltype = to_ga_eltype(tensor_element_type<TensorType>()); int ga_tens = NGA_Create64(ga_eltype,ndims,&dims[0],const_cast<char*>("iotemp"),&chnks[0]); //GA_Zero(ga_tens); //convert tamm tensor to GA auto tamm_ga_lambda = [&](const IndexVector& bid){ const IndexVector blockid = internal::translate_blockid(bid, tensor()); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<int64_t> lo(ndims),hi(ndims),ld(ndims-1); for(size_t i=0;i<ndims;i++) lo[i] = cd_ncast<size_t>(block_offset[i]); for(size_t i=0;i<ndims;i++) hi[i] = cd_ncast<size_t>(block_offset[i] + block_dims[i]-1); for(size_t i=1;i<ndims;i++) ld[i-1] = cd_ncast<size_t>(block_dims[i]); std::vector<TensorType> sbuf(dsize); tensor.get(blockid, sbuf); NGA_Put64(ga_tens,&lo[0],&hi[0],&sbuf[0],&ld[0]); }; block_for(ec, tensor(), tamm_ga_lambda); return ga_tens; } //For dense->dlpno template<typename TensorType> int tamm_to_ga2(ExecutionContext& ec, Tensor<TensorType>& tensor) { int ndims = tensor.num_modes(); std::vector<int64_t> dims; std::vector<int64_t> chnks(ndims,-1); for(auto tis: tensor.tiled_index_spaces()) dims.push_back(tis.index_space().num_indices()); auto ga_eltype = to_ga_eltype(tensor_element_type<TensorType>()); int ga_tens = NGA_Create64(ga_eltype,ndims,&dims[0],const_cast<char*>("iotemp"),&chnks[0]); //GA_Zero(ga_tens); //convert tamm tensor to GA auto tamm_ga_lambda = [&](const IndexVector& bid){ const IndexVector blockid = internal::translate_blockid(bid, tensor()); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<int64_t> lo(ndims),hi(ndims),ld(ndims-1); for(size_t i=0;i<ndims-1;i++) lo[i] = cd_ncast<size_t>(block_offset[i]); for(size_t i=0;i<ndims-1;i++) hi[i] = cd_ncast<size_t>(block_offset[i] + block_dims[i]-1); for(size_t i=1;i<ndims-1;i++) ld[i-1] = cd_ncast<size_t>(block_dims[i]); std::vector<TensorType> sbuf(dsize); tensor.get(blockid, sbuf); NGA_Put64(ga_tens,&lo[0],&hi[0],&sbuf[0],&ld[0]); }; block_for(ec, tensor(), tamm_ga_lambda); return ga_tens; } template<typename T> hid_t get_hdf5_dt() { using std::is_same_v; if constexpr(is_same_v<int, T>) return H5T_NATIVE_INT; if constexpr(is_same_v<int64_t, T>) return H5T_NATIVE_LLONG; else if constexpr(is_same_v<float, T>) return H5T_NATIVE_FLOAT; else if constexpr(is_same_v<double, T>) return H5T_NATIVE_DOUBLE; else if constexpr (is_same_v<std::complex<float>, T>) { typedef struct { float re; /*real part*/ float im; /*imaginary part*/ } complex_t; hid_t complex_id = H5Tcreate(H5T_COMPOUND, sizeof(complex_t)); H5Tinsert(complex_id, "real", HOFFSET(complex_t, re), H5T_NATIVE_FLOAT); H5Tinsert(complex_id, "imaginary", HOFFSET(complex_t, im), H5T_NATIVE_FLOAT); return complex_id; } else if constexpr (is_same_v<std::complex<double>, T>) { typedef struct { double re; /*real part*/ double im; /*imaginary part*/ } complex_t; hid_t complex_id = H5Tcreate(H5T_COMPOUND, sizeof(complex_t)); H5Tinsert(complex_id, "real", HOFFSET(complex_t, re), H5T_NATIVE_DOUBLE); H5Tinsert(complex_id, "imaginary", HOFFSET(complex_t, im), H5T_NATIVE_DOUBLE); return complex_id; } } /** * @brief write tensor to disk using HDF5 * * @tparam TensorType the type of the elements in the tensor * @param tensor to write to disk * @param filename to write to disk */ template<typename TensorType> void write_to_disk(Tensor<TensorType> tensor, const std::string& filename, bool tammio=true, bool profile=false, int nagg_hint=0) { ExecutionContext& gec = get_ec(tensor()); auto io_t1 = std::chrono::high_resolution_clock::now(); MPI_Comm io_comm; int rank = gec.pg().rank().value(); auto [nagg,ppn] = get_subgroup_info(gec,tensor,io_comm,nagg_hint); int ga_tens; if(!tammio) ga_tens = tamm_to_ga(gec,tensor); size_t ndims = tensor.num_modes(); const std::string nppn = std::to_string(nagg) + "n," + std::to_string(ppn) + "ppn"; if(rank == 0 && profile) std::cout << "write to disk using: " << nppn << std::endl; int64_t tensor_size; int ndim=1,itype; ga_tens = tensor.ga_handle(); NGA_Inquire64(ga_tens,&itype,&ndim,&tensor_size); // tensor_size = 1; // for(auto tis: tensor.tiled_index_spaces()) tensor_size = tensor_size * (tis.index_space().num_indices()); hid_t hdf5_dt = get_hdf5_dt<TensorType>(); if(io_comm != MPI_COMM_NULL) { ProcGroup pg = ProcGroup {ProcGroup::create_coll(io_comm)}; ExecutionContext ec{pg, DistributionKind::nw, MemoryManagerKind::ga}; auto ltensor = tensor(); LabelLoopNest loop_nest{ltensor.labels()}; int ierr; // MPI_File fh; MPI_Info info; // MPI_Status status; hsize_t file_offset; MPI_Info_create(&info); MPI_Info_set(info,"cb_nodes",std::to_string(nagg).c_str()); // MPI_File_open(io_comm, filename.c_str(), MPI_MODE_CREATE|MPI_MODE_WRONLY, // info, &fh); /* set the file access template for parallel IO access */ auto acc_template = H5Pcreate(H5P_FILE_ACCESS); // ierr = H5Pset_sieve_buf_size(acc_template, 262144); // ierr = H5Pset_alignment(acc_template, 524288, 262144); // ierr = MPI_Info_set(info, "access_style", "write_once"); // ierr = MPI_Info_set(info, "collective_buffering", "true"); // ierr = MPI_Info_set(info, "cb_block_size", "1048576"); // ierr = MPI_Info_set(info, "cb_buffer_size", "4194304"); /* tell the HDF5 library that we want to use MPI-IO to do the writing */ ierr = H5Pset_fapl_mpio(acc_template, io_comm, info); auto file_identifier = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, acc_template); /* release the file access template */ ierr = H5Pclose(acc_template); ierr = MPI_Info_free(&info); int tensor_rank = 1; hsize_t dimens_1d = tensor_size; auto dataspace = H5Screate_simple(tensor_rank, &dimens_1d, NULL); /* create a dataset collectively */ auto dataset = H5Dcreate(file_identifier, "tensor", hdf5_dt, dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); /* create a file dataspace independently */ auto file_dataspace = H5Dget_space (dataset); /* Create and write additional metadata */ // std::vector<int> attr_dims{11,29,42}; // hsize_t attr_size = attr_dims.size(); // auto attr_dataspace = H5Screate_simple(1, &attr_size, NULL); // auto attr_dataset = H5Dcreate(file_identifier, "attr", H5T_NATIVE_INT, attr_dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); // H5Dwrite(attr_dataset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, attr_dims.data()); // H5Dclose(attr_dataset); // H5Sclose(attr_dataspace); hid_t xfer_plist; /* set up the collective transfer properties list */ xfer_plist = H5Pcreate (H5P_DATASET_XFER); auto ret=H5Pset_dxpl_mpio(xfer_plist, H5FD_MPIO_INDEPENDENT); if(/*is_irreg &&*/ tammio){ auto lambda = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); file_offset = 0; for(const IndexVector& pbid : loop_nest) { bool is_zero = !tensor.is_non_zero(pbid); if(pbid==blockid) { if(is_zero) return; break; } if(is_zero) continue; file_offset += tensor.block_size(pbid); } // const tamm::TAMM_SIZE hsize_t dsize = tensor.block_size(blockid); std::vector<TensorType> dbuf(dsize); tensor.get(blockid, dbuf); // std::cout << "WRITE: rank, file_offset, size = " << rank << "," << file_offset << ", " << dsize << std::endl; hsize_t stride = 1; herr_t ret=H5Sselect_hyperslab(file_dataspace, H5S_SELECT_SET, &file_offset, &stride, &dsize, NULL); //stride=NULL? // /* create a memory dataspace independently */ auto mem_dataspace = H5Screate_simple (tensor_rank, &dsize, NULL); // /* write data independently */ ret = H5Dwrite(dataset, hdf5_dt, mem_dataspace, file_dataspace, xfer_plist, dbuf.data()); H5Sclose(mem_dataspace); }; block_for(ec, ltensor, lambda); } else{ //N-D GA auto ga_write_lambda = [&](const IndexVector& bid){ const IndexVector blockid = internal::translate_blockid(bid, ltensor); file_offset = 0; for(const IndexVector& pbid : loop_nest) { bool is_zero = !tensor.is_non_zero(pbid); if(pbid==blockid) { if(is_zero) return; break; } if(is_zero) continue; file_offset += tensor.block_size(pbid); } // file_offset = file_offset*sizeof(TensorType); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); hsize_t dsize = tensor.block_size(blockid); std::vector<int64_t> lo(ndims),hi(ndims),ld(ndims-1); for(size_t i=0;i<ndims;i++) lo[i] = cd_ncast<size_t>(block_offset[i]); for(size_t i=0;i<ndims;i++) hi[i] = cd_ncast<size_t>(block_offset[i] + block_dims[i]-1); for(size_t i=1;i<ndims;i++) ld[i-1] = cd_ncast<size_t>(block_dims[i]); std::vector<TensorType> sbuf(dsize); NGA_Get64(ga_tens,&lo[0],&hi[0],&sbuf[0],&ld[0]); // MPI_File_write_at(fh,file_offset,reinterpret_cast<void*>(&sbuf[0]), // static_cast<int>(dsize),mpi_type<TensorType>(),&status); hsize_t stride = 1; herr_t ret=H5Sselect_hyperslab(file_dataspace, H5S_SELECT_SET, &file_offset, &stride, &dsize, NULL); //stride=NULL? // /* create a memory dataspace independently */ auto mem_dataspace = H5Screate_simple (tensor_rank, &dsize, NULL); // /* write data independently */ ret = H5Dwrite(dataset, hdf5_dt, mem_dataspace, file_dataspace, xfer_plist, sbuf.data()); H5Sclose(mem_dataspace); }; block_for(ec, ltensor, ga_write_lambda); } H5Sclose(file_dataspace); // H5Sclose(mem_dataspace); H5Pclose(xfer_plist); H5Dclose(dataset); H5Sclose(dataspace); H5Fclose(file_identifier); ec.flush_and_sync(); //MemoryManagerGA::destroy_coll(mgr); MPI_Comm_free(&io_comm); pg.destroy_coll(); } gec.pg().barrier(); if(!tammio) NGA_Destroy(ga_tens); auto io_t2 = std::chrono::high_resolution_clock::now(); double io_time = std::chrono::duration_cast<std::chrono::duration<double>>((io_t2 - io_t1)).count(); if(rank == 0 && profile) std::cout << "Time for writing " << filename << " to disk (" << nppn << "): " << io_time << " secs" << std::endl; } /** * @brief write tensor to disk using MPI-IO * * @tparam TensorType the type of the elements in the tensor * @param tensor to write to disk * @param filename to write to disk */ template<typename TensorType> void write_to_disk_mpiio(Tensor<TensorType> tensor, const std::string& filename, bool tammio=true, bool profile=false, int nagg_hint=0) { ExecutionContext& gec = get_ec(tensor()); auto io_t1 = std::chrono::high_resolution_clock::now(); MPI_Comm io_comm; int rank = gec.pg().rank().value(); auto [nagg,ppn] = get_subgroup_info(gec,tensor,io_comm,nagg_hint); int ga_tens; if(!tammio) ga_tens = tamm_to_ga(gec,tensor); size_t ndims = tensor.num_modes(); const std::string nppn = std::to_string(nagg) + "n," + std::to_string(ppn) + "ppn"; if(rank == 0 && profile) std::cout << "write to disk using: " << nppn << std::endl; if(io_comm != MPI_COMM_NULL) { ProcGroup pg = ProcGroup {ProcGroup::create_coll(io_comm)}; ExecutionContext ec{pg, DistributionKind::nw, MemoryManagerKind::ga}; MPI_File fh; MPI_Info info; MPI_Status status; MPI_Offset file_offset; MPI_Info_create(&info); // MPI_Info_set(info,"romio_cb_write", "enable"); // MPI_Info_set(info,"striping_unit","4194304"); MPI_Info_set(info,"cb_nodes",std::to_string(nagg).c_str()); MPI_File_open(io_comm, filename.c_str(), MPI_MODE_CREATE|MPI_MODE_WRONLY, info, &fh); MPI_Info_free(&info); auto ltensor = tensor(); LabelLoopNest loop_nest{ltensor.labels()}; // auto tis_dims = tensor.tiled_index_spaces(); // bool is_irreg = false; // for (auto x:tis_dims) // is_irreg = is_irreg || !tis_dims[0].input_tile_sizes().empty(); if(/*is_irreg &&*/ tammio){ auto lambda = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); file_offset = 0; for(const IndexVector& pbid : loop_nest) { if(pbid==blockid) break; file_offset += tensor.block_size(pbid); } file_offset = file_offset*sizeof(TensorType); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<TensorType> dbuf(dsize); tensor.get(blockid, dbuf); MPI_File_write_at(fh,file_offset,reinterpret_cast<void*>(&dbuf[0]), static_cast<int>(dsize),mpi_type<TensorType>(),&status); }; block_for(ec, ltensor, lambda); } else{ if(false) { //this is for a writing the tamm tensor using the underlying (1D) GA handle, works when unit tiled only. int ndim,itype; int64_t dsize; ga_tens = tensor.ga_handle(); NGA_Inquire64(ga_tens,&itype,&ndim,&dsize); const int64_t nranks = ec.pg().size().value(); const int64_t my_rank = ec.pg().rank().value(); int64_t bal_block_size = static_cast<int64_t>(std::ceil(dsize/(1.0*nranks))); int64_t block_size = bal_block_size; if(my_rank == nranks-1) block_size = dsize - block_size*(nranks-1); std::vector<TensorType> dbuf(block_size); int64_t lo = my_rank*block_size; if(my_rank == nranks-1) lo = my_rank*bal_block_size; int64_t hi = cd_ncast<size_t>(lo+block_size-1); int64_t ld = -1; // std::cout << "rank, dsize, block_size: " << my_rank << ":" << dsize << ":" << block_size << std::endl; //std::cout << "rank, ndim, lo, hi: " << my_rank << ":" << ndim << " --> " << lo << ":" << hi << std::endl; NGA_Get64(ga_tens,&lo,&hi,&dbuf[0],&ld); MPI_File_write_at(fh,static_cast<int>(lo)*sizeof(TensorType),reinterpret_cast<void*>(&dbuf[0]), static_cast<int>(block_size),mpi_type<TensorType>(),&status); } else { //N-D GA auto ga_write_lambda = [&](const IndexVector& bid){ const IndexVector blockid = internal::translate_blockid(bid, ltensor); file_offset = 0; for(const IndexVector& pbid : loop_nest) { if(pbid==blockid) break; file_offset += tensor.block_size(pbid); } file_offset = file_offset*sizeof(TensorType); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<int64_t> lo(ndims),hi(ndims),ld(ndims-1); for(size_t i=0;i<ndims;i++) lo[i] = cd_ncast<size_t>(block_offset[i]); for(size_t i=0;i<ndims;i++) hi[i] = cd_ncast<size_t>(block_offset[i] + block_dims[i]-1); for(size_t i=1;i<ndims;i++) ld[i-1] = cd_ncast<size_t>(block_dims[i]); std::vector<TensorType> sbuf(dsize); NGA_Get64(ga_tens,&lo[0],&hi[0],&sbuf[0],&ld[0]); MPI_File_write_at(fh,file_offset,reinterpret_cast<void*>(&sbuf[0]), static_cast<int>(dsize),mpi_type<TensorType>(),&status); }; block_for(ec, ltensor, ga_write_lambda); } } ec.flush_and_sync(); //MemoryManagerGA::destroy_coll(mgr); MPI_Comm_free(&io_comm); pg.destroy_coll(); MPI_File_close(&fh); } gec.pg().barrier(); if(!tammio) NGA_Destroy(ga_tens); auto io_t2 = std::chrono::high_resolution_clock::now(); double io_time = std::chrono::duration_cast<std::chrono::duration<double>>((io_t2 - io_t1)).count(); if(rank == 0 && profile) std::cout << "Time for writing " << filename << " to disk (" << nppn << "): " << io_time << " secs" << std::endl; } /** * @brief convert N-D GA to a tamm tensor * * @tparam TensorType the type of the elements in the tensor * @param ec ExecutionContext * @param tensor tamm tensor handle * @param ga_tens GA handle */ template<typename TensorType> void ga_to_tamm(ExecutionContext& ec, Tensor<TensorType>& tensor, int ga_tens) { size_t ndims = tensor.num_modes(); //convert ga to tamm tensor auto ga_tamm_lambda = [&](const IndexVector& bid){ const IndexVector blockid = internal::translate_blockid(bid, tensor()); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<int64_t> lo(ndims),hi(ndims),ld(ndims-1); for(size_t i=0;i<ndims;i++) lo[i] = cd_ncast<size_t>(block_offset[i]); for(size_t i=0;i<ndims;i++) hi[i] = cd_ncast<size_t>(block_offset[i] + block_dims[i]-1); for(size_t i=1;i<ndims;i++) ld[i-1] = cd_ncast<size_t>(block_dims[i]); std::vector<TensorType> sbuf(dsize); NGA_Get64(ga_tens,&lo[0],&hi[0],&sbuf[0],&ld[0]); tensor.put(blockid, sbuf); }; block_for(ec, tensor(), ga_tamm_lambda); // NGA_Destroy(ga_tens); } //For dlpno->dense template<typename TensorType> void ga_to_tamm2(ExecutionContext& ec, Tensor<TensorType>& tensor, int ga_tens) { size_t ndims = tensor.num_modes(); //convert ga to tamm tensor auto ga_tamm_lambda = [&](const IndexVector& bid){ const IndexVector blockid = internal::translate_blockid(bid, tensor()); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<int64_t> lo(ndims),hi(ndims),ld(ndims-1); for(size_t i=0;i<ndims-1;i++) lo[i] = cd_ncast<size_t>(block_offset[i]); for(size_t i=0;i<ndims-1;i++) hi[i] = cd_ncast<size_t>(block_offset[i] + block_dims[i]-1); for(size_t i=1;i<ndims-1;i++) ld[i-1] = cd_ncast<size_t>(block_dims[i]); std::vector<TensorType> sbuf(dsize); NGA_Get64(ga_tens,&lo[0],&hi[0],&sbuf[0],&ld[0]); tensor.put(blockid, sbuf); }; block_for(ec, tensor(), ga_tamm_lambda); // NGA_Destroy(ga_tens); } /** * @brief retile a tamm tensor * * @param stensor source tensor * @param dtensor tensor after retiling. * Assumed to be created & allocated using the new tiled index space. */ template<typename TensorType> void retile_tamm_tensor(Tensor<TensorType> stensor, Tensor<TensorType>& dtensor, std::string tname="") { auto io_t1 = std::chrono::high_resolution_clock::now(); ExecutionContext& ec = get_ec(stensor()); int rank = ec.pg().rank().value(); int ga_tens = tamm_to_ga(ec,stensor); ga_to_tamm(ec, dtensor, ga_tens); NGA_Destroy(ga_tens); auto io_t2 = std::chrono::high_resolution_clock::now(); double rt_time = std::chrono::duration_cast<std::chrono::duration<double>>((io_t2 - io_t1)).count(); if(rank == 0 && !tname.empty()) std::cout << "Time to re-tile " << tname << " tensor: " << rt_time << " secs" << std::endl; } /** * @brief read tensor from disk using HDF5 * * @tparam TensorType the type of the elements in the tensor * @param tensor to read into * @param filename to read from disk */ template<typename TensorType> void read_from_disk(Tensor<TensorType> tensor, const std::string& filename, bool tammio=true, Tensor<TensorType> wtensor={}, bool profile=false, int nagg_hint=0) { ExecutionContext& gec = get_ec(tensor()); auto io_t1 = std::chrono::high_resolution_clock::now(); MPI_Comm io_comm; int rank = gec.pg().rank().value(); auto [nagg,ppn] = get_subgroup_info(gec,tensor,io_comm,nagg_hint); const std::string nppn = std::to_string(nagg) + "n," + std::to_string(ppn) + "ppn"; if(rank == 0 && profile) std::cout << "read from disk using: " << nppn << std::endl; int ga_tens; if(!tammio) { auto tis_dims = tensor.tiled_index_spaces(); int ndims = tensor.num_modes(); std::vector<int64_t> dims; std::vector<int64_t> chnks(ndims,-1); for(auto tis: tis_dims) dims.push_back(tis.index_space().num_indices()); ga_tens = NGA_Create64(to_ga_eltype(tensor_element_type<TensorType>()), ndims,&dims[0],const_cast<char*>("iotemp"),&chnks[0]); } hid_t hdf5_dt = get_hdf5_dt<TensorType>(); if(io_comm != MPI_COMM_NULL) { auto tensor_back = tensor; ProcGroup pg = ProcGroup {ProcGroup::create_coll(io_comm)}; ExecutionContext ec{pg, DistributionKind::nw, MemoryManagerKind::ga}; if(wtensor.num_modes()>0) tensor = wtensor; auto ltensor = tensor(); LabelLoopNest loop_nest{ltensor.labels()}; int ierr; // MPI_File fh; MPI_Info info; // MPI_Status status; hsize_t file_offset; MPI_Info_create(&info); // MPI_Info_set(info,"romio_cb_read", "enable"); // MPI_Info_set(info,"striping_unit","4194304"); MPI_Info_set(info,"cb_nodes",std::to_string(nagg).c_str()); // MPI_File_open(ec.pg().comm(), filename.c_str(), MPI_MODE_RDONLY, // info, &fh); /* set the file access template for parallel IO access */ auto acc_template = H5Pcreate(H5P_FILE_ACCESS); /* tell the HDF5 library that we want to use MPI-IO to do the reading */ ierr = H5Pset_fapl_mpio(acc_template, io_comm, info); auto file_identifier = H5Fopen(filename.c_str(), H5F_ACC_RDONLY, acc_template); /* release the file access template */ ierr = H5Pclose(acc_template); ierr = MPI_Info_free(&info); int tensor_rank = 1; // hsize_t dimens_1d = tensor_size; /* create a dataset collectively */ auto dataset = H5Dopen(file_identifier, "tensor", H5P_DEFAULT); /* create a file dataspace independently */ auto file_dataspace = H5Dget_space (dataset); /* Read additional metadata */ // std::vector<int> attr_dims(3); // auto attr_dataset = H5Dopen(file_identifier, "attr", H5P_DEFAULT); // H5Dread(attr_dataset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, attr_dims.data()); // H5Dclose(attr_dataset); hid_t xfer_plist; /* set up the collective transfer properties list */ xfer_plist = H5Pcreate (H5P_DATASET_XFER); auto ret=H5Pset_dxpl_mpio(xfer_plist, H5FD_MPIO_INDEPENDENT); if(/*is_irreg &&*/ tammio) { auto lambda = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); file_offset = 0; for(const IndexVector& pbid : loop_nest) { bool is_zero = !tensor.is_non_zero(pbid); if(pbid==blockid) { if(is_zero) return; break; } if(is_zero) continue; file_offset += tensor.block_size(pbid); } // file_offset = file_offset*sizeof(TensorType); hsize_t dsize = tensor.block_size(blockid); std::vector<TensorType> dbuf(dsize); // std::cout << "READ: rank, file_offset, size = " << rank << "," << file_offset << ", " << dsize << std::endl; hsize_t stride = 1; herr_t ret=H5Sselect_hyperslab(file_dataspace, H5S_SELECT_SET, &file_offset, &stride, &dsize, NULL); //stride=NULL? // /* create a memory dataspace independently */ auto mem_dataspace = H5Screate_simple (tensor_rank, &dsize, NULL); // MPI_File_read_at(fh,file_offset,reinterpret_cast<void*>(&dbuf[0]), // static_cast<int>(dsize),mpi_type<TensorType>(),&status); // /* read data independently */ ret = H5Dread(dataset, hdf5_dt, mem_dataspace, file_dataspace, xfer_plist, dbuf.data()); tensor.put(blockid,dbuf); H5Sclose(mem_dataspace); }; block_for(ec, ltensor, lambda); } else { auto ga_read_lambda = [&](const IndexVector& bid){ const IndexVector blockid = internal::translate_blockid(bid, tensor()); file_offset = 0; for(const IndexVector& pbid : loop_nest) { bool is_zero = !tensor.is_non_zero(pbid); if(pbid==blockid) { if(is_zero) return; break; } if(is_zero) continue; file_offset += tensor.block_size(pbid); } // file_offset = file_offset*sizeof(TensorType); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); hsize_t dsize = tensor.block_size(blockid); size_t ndims = block_dims.size(); std::vector<int64_t> lo(ndims),hi(ndims),ld(ndims-1); for(size_t i=0;i<ndims;i++) lo[i] = cd_ncast<size_t>(block_offset[i]); for(size_t i=0;i<ndims;i++) hi[i] = cd_ncast<size_t>(block_offset[i] + block_dims[i]-1); for(size_t i=1;i<ndims;i++) ld[i-1] = cd_ncast<size_t>(block_dims[i]); std::vector<TensorType> sbuf(dsize); // MPI_File_read_at(fh,file_offset,reinterpret_cast<void*>(&sbuf[0]), // static_cast<int>(dsize),mpi_type<TensorType>(),&status); hsize_t stride = 1; herr_t ret=H5Sselect_hyperslab(file_dataspace, H5S_SELECT_SET, &file_offset, &stride, &dsize, NULL); //stride=NULL? // /* create a memory dataspace independently */ auto mem_dataspace = H5Screate_simple (tensor_rank, &dsize, NULL); // MPI_File_read_at(fh,file_offset,reinterpret_cast<void*>(&dbuf[0]), // static_cast<int>(dsize),mpi_type<TensorType>(),&status); // /* read data independently */ ret = H5Dread(dataset, hdf5_dt, mem_dataspace, file_dataspace, xfer_plist, sbuf.data()); NGA_Put64(ga_tens,&lo[0],&hi[0],&sbuf[0],&ld[0]); }; block_for(ec, tensor(), ga_read_lambda); } H5Sclose(file_dataspace); // H5Sclose(mem_dataspace); H5Pclose(xfer_plist); H5Dclose(dataset); H5Fclose(file_identifier); ec.flush_and_sync(); //MemoryManagerGA::destroy_coll(mgr); MPI_Comm_free(&io_comm); pg.destroy_coll(); // MPI_File_close(&fh); tensor = tensor_back; } gec.pg().barrier(); if(!tammio){ ga_to_tamm(gec,tensor,ga_tens); NGA_Destroy(ga_tens); } auto io_t2 = std::chrono::high_resolution_clock::now(); double io_time = std::chrono::duration_cast<std::chrono::duration<double>>((io_t2 - io_t1)).count(); if(rank == 0 && profile) std::cout << "Time for reading " << filename << " from disk (" << nppn << "): " << io_time << " secs" << std::endl; } /** * @brief read tensor from disk using MPI-IO * * @tparam TensorType the type of the elements in the tensor * @param tensor to read into * @param filename to read from disk */ template<typename TensorType> void read_from_disk_mpiio(Tensor<TensorType> tensor, const std::string& filename, bool tammio=true, Tensor<TensorType> wtensor={}, bool profile=false, int nagg_hint=0) { ExecutionContext& gec = get_ec(tensor()); auto io_t1 = std::chrono::high_resolution_clock::now(); MPI_Comm io_comm; int rank = gec.pg().rank().value(); auto [nagg,ppn] = get_subgroup_info(gec,tensor,io_comm,nagg_hint); const std::string nppn = std::to_string(nagg) + "n," + std::to_string(ppn) + "ppn"; if(rank == 0 && profile) std::cout << "read from disk using: " << nppn << std::endl; int ga_tens; if(!tammio) { auto tis_dims = tensor.tiled_index_spaces(); int ndims = tensor.num_modes(); std::vector<int64_t> dims; std::vector<int64_t> chnks(ndims,-1); for(auto tis: tis_dims) dims.push_back(tis.index_space().num_indices()); ga_tens = NGA_Create64(to_ga_eltype(tensor_element_type<TensorType>()), ndims,&dims[0],const_cast<char*>("iotemp"),&chnks[0]); } if(io_comm != MPI_COMM_NULL) { auto tensor_back = tensor; ProcGroup pg = ProcGroup {ProcGroup::create_coll(io_comm)}; ExecutionContext ec{pg, DistributionKind::nw, MemoryManagerKind::ga}; MPI_File fh; MPI_Info info; MPI_Status status; MPI_Offset file_offset; MPI_Info_create(&info); // MPI_Info_set(info,"romio_cb_read", "enable"); // MPI_Info_set(info,"striping_unit","4194304"); MPI_Info_set(info,"cb_nodes",std::to_string(nagg).c_str()); MPI_File_open(ec.pg().comm(), filename.c_str(), MPI_MODE_RDONLY, info, &fh); MPI_Info_free(&info); if(wtensor.num_modes()>0) tensor = wtensor; auto ltensor = tensor(); LabelLoopNest loop_nest{ltensor.labels()}; // auto tis_dims = tensor.tiled_index_spaces(); // bool is_irreg = false; // for (auto x:tis_dims) // is_irreg = is_irreg || !tis_dims[0].input_tile_sizes().empty(); if(/*is_irreg &&*/ tammio) { auto lambda = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); file_offset = 0; for(const IndexVector& pbid : loop_nest) { if(pbid==blockid) break; file_offset += tensor.block_size(pbid); } file_offset = file_offset*sizeof(TensorType); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<TensorType> dbuf(dsize); MPI_File_read_at(fh,file_offset,reinterpret_cast<void*>(&dbuf[0]), static_cast<int>(dsize),mpi_type<TensorType>(),&status); tensor.put(blockid,dbuf); }; block_for(ec, ltensor, lambda); } else { if(false) { //this is for a writing the tamm tensor using the underlying (1D) GA handle, works when unit tiled only. int ndim,itype; int64_t dsize; ga_tens = tensor.ga_handle(); // const int64_t dsize = std::accumulate(std::begin(dims), std::end(dims), 1, std::multiplies<int64_t>()); NGA_Inquire64(ga_tens,&itype,&ndim,&dsize); const int64_t nranks = ec.pg().size().value(); const int64_t my_rank = ec.pg().rank().value(); int64_t bal_block_size = static_cast<int64_t>(std::ceil(dsize/(1.0*nranks))); int64_t block_size = bal_block_size; if(my_rank == nranks-1) block_size = dsize - block_size*(nranks-1); std::vector<TensorType> dbuf(block_size); int64_t lo = my_rank*block_size; if(my_rank == nranks-1) lo = my_rank*bal_block_size; int64_t hi = cd_ncast<size_t>(lo+block_size-1); int64_t ld = -1; MPI_File_read_at(fh,static_cast<int>(lo)*sizeof(TensorType),reinterpret_cast<void*>(&dbuf[0]), static_cast<int>(block_size),mpi_type<TensorType>(),&status); NGA_Put64(ga_tens,&lo,&hi,&dbuf[0],&ld); } else { auto ga_read_lambda = [&](const IndexVector& bid){ const IndexVector blockid = internal::translate_blockid(bid, tensor()); file_offset = 0; for(const IndexVector& pbid : loop_nest) { if(pbid==blockid) break; file_offset += tensor.block_size(pbid); } file_offset = file_offset*sizeof(TensorType); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); size_t ndims = block_dims.size(); std::vector<int64_t> lo(ndims),hi(ndims),ld(ndims-1); for(size_t i=0;i<ndims;i++) lo[i] = cd_ncast<size_t>(block_offset[i]); for(size_t i=0;i<ndims;i++) hi[i] = cd_ncast<size_t>(block_offset[i] + block_dims[i]-1); for(size_t i=1;i<ndims;i++) ld[i-1] = cd_ncast<size_t>(block_dims[i]); std::vector<TensorType> sbuf(dsize); MPI_File_read_at(fh,file_offset,reinterpret_cast<void*>(&sbuf[0]), static_cast<int>(dsize),mpi_type<TensorType>(),&status); NGA_Put64(ga_tens,&lo[0],&hi[0],&sbuf[0],&ld[0]); }; block_for(ec, tensor(), ga_read_lambda); } } ec.flush_and_sync(); //MemoryManagerGA::destroy_coll(mgr); MPI_Comm_free(&io_comm); pg.destroy_coll(); MPI_File_close(&fh); tensor = tensor_back; } gec.pg().barrier(); if(!tammio){ ga_to_tamm(gec,tensor,ga_tens); NGA_Destroy(ga_tens); } auto io_t2 = std::chrono::high_resolution_clock::now(); double io_time = std::chrono::duration_cast<std::chrono::duration<double>>((io_t2 - io_t1)).count(); if(rank == 0 && profile) std::cout << "Time for reading " << filename << " from disk (" << nppn << "): " << io_time << " secs" << std::endl; } template<typename T> void dlpno_to_dense(Tensor<T> src, Tensor<T> dst){ //T1_dlpno(a_ii, ii) -> T1_dense(a, i) //T2_dlpno(a_ij, b_ij, ij) -> T2_dense(a, b, i, j) bool is_2D = src.num_modes() == 2; ExecutionContext& ec = get_ec(src()); int ga_src = tamm_to_ga(ec,src); if(is_2D) ga_to_tamm(ec, dst, ga_src); else ga_to_tamm2(ec, dst, ga_src); NGA_Destroy(ga_src); } template<typename T> void dense_to_dlpno(Tensor<T> src, Tensor<T> dst){ //T1_dense(a, i) -> T1_dlpno(a_ii, ii) //T2_dense(a, b, i, j) -> T2_dlpno(a_ij, b_ij, ij) bool is_2D = src.num_modes() == 2; ExecutionContext& ec = get_ec(src()); int ga_src; if(is_2D) ga_src = tamm_to_ga(ec,src); else ga_src = tamm_to_ga2(ec,src); ga_to_tamm(ec, dst, ga_src); NGA_Destroy(ga_src); } /** * @brief applies a function elementwise to a tensor * * @tparam TensorType the type of the elements in the tensor * @param ltensor tensor to operate on * @param func function to be applied to each element */ template<typename TensorType> void apply_ewise_ip(LabeledTensor<TensorType> ltensor, std::function<TensorType(TensorType)> func) { ExecutionContext& gec = get_ec(ltensor); Tensor<TensorType> tensor = ltensor.tensor(); MPI_Comm sub_comm; get_subgroup_info(gec,tensor,sub_comm); if(sub_comm != MPI_COMM_NULL) { ProcGroup pg = ProcGroup {ProcGroup::create_coll(sub_comm)}; ExecutionContext ec{pg, DistributionKind::nw, MemoryManagerKind::ga}; auto lambda = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<TensorType> dbuf(dsize); tensor.get(blockid, dbuf); for(size_t c = 0; c < dsize; c++) dbuf[c] = func(dbuf[c]); tensor.put(blockid, dbuf); }; block_for(ec, ltensor, lambda); ec.flush_and_sync(); //MemoryManagerGA::destroy_coll(mgr); MPI_Comm_free(&sub_comm); pg.destroy_coll(); } gec.pg().barrier(); } // Several convenience functions using apply_ewise_ip. // These routines update the tensor in-place template<typename TensorType> void conj_ip(LabeledTensor<TensorType> ltensor) { std::function<TensorType(TensorType)> func = [&](TensorType a) { return std::conj(a); }; apply_ewise_ip(ltensor, func); } template<typename TensorType> void conj_ip(Tensor<TensorType> tensor) { conj_ip(tensor()); } template<typename TensorType> void scale_ip(LabeledTensor<TensorType> ltensor, TensorType alpha) { std::function<TensorType(TensorType)> func = [&](TensorType a) { return alpha * a; }; apply_ewise_ip(ltensor, func); } template<typename TensorType> void scale_ip(Tensor<TensorType> tensor, TensorType alpha) { scale_ip(tensor(),alpha); } /** * @brief applies a function elementwise to a tensor, returns a new tensor * * @tparam TensorType the type of the elements in the tensor * @param oltensor original tensor * @param func function to be applied to each element * @return resulting tensor after applying func to original tensor */ template<typename TensorType> Tensor<TensorType> apply_ewise(LabeledTensor<TensorType> oltensor, std::function<TensorType(TensorType)> func, bool is_lt=true) { ExecutionContext& ec = get_ec(oltensor); Tensor<TensorType> otensor = oltensor.tensor(); Tensor<TensorType> tensor{oltensor.labels()}; LabeledTensor<TensorType> ltensor = tensor(); Tensor<TensorType>::allocate(&ec,tensor); //if(is_lt) Scheduler{ec}(ltensor = oltensor).execute(); auto lambda = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, oltensor); const tamm::TAMM_SIZE dsize = tensor.block_size(bid); std::vector<TensorType> dbuf(dsize); otensor.get(blockid, dbuf); for(size_t c = 0; c < dsize; c++) dbuf[c] = func(dbuf[c]); tensor.put(bid, dbuf); }; block_for(ec, ltensor, lambda); return tensor; } // Several convenience functions using apply_ewise // These routines return a new tensor template<typename TensorType> Tensor<TensorType> conj(LabeledTensor<TensorType> ltensor, bool is_lt = true) { std::function<TensorType(TensorType)> func = [&](TensorType a) { return std::conj(a); }; return apply_ewise(ltensor, func, is_lt); } template<typename TensorType> Tensor<TensorType> conj(Tensor<TensorType> tensor) { return conj(tensor(), false); } template<typename TensorType> Tensor<TensorType> square(LabeledTensor<TensorType> ltensor, bool is_lt = true) { std::function<TensorType(TensorType)> func = [&](TensorType a) { return a * a; }; return apply_ewise(ltensor, func, is_lt); } template<typename TensorType> Tensor<TensorType> square(Tensor<TensorType> tensor) { return square(tensor(), false); } template<typename TensorType> Tensor<TensorType> log10(LabeledTensor<TensorType> ltensor, bool is_lt = true) { std::function<TensorType(TensorType)> func = [&](TensorType a) { return std::log10(a); }; return apply_ewise(ltensor, func, is_lt); } template<typename TensorType> Tensor<TensorType> log10(Tensor<TensorType> tensor) { return log10(tensor(), false); } template<typename TensorType> Tensor<TensorType> log(LabeledTensor<TensorType> ltensor, bool is_lt = true) { std::function<TensorType(TensorType)> func = [&](TensorType a) { return std::log(a); }; return apply_ewise(ltensor, func, is_lt); } template<typename TensorType> Tensor<TensorType> log(Tensor<TensorType> tensor) { return log(tensor(), false); } template<typename TensorType> Tensor<TensorType> einverse(LabeledTensor<TensorType> ltensor, bool is_lt = true) { std::function<TensorType(TensorType)> func = [&](TensorType a) { return 1 / a; }; return apply_ewise(ltensor, func, is_lt); } template<typename TensorType> Tensor<TensorType> einverse(Tensor<TensorType> tensor) { return einverse(tensor(), false); } template<typename TensorType> Tensor<TensorType> pow(LabeledTensor<TensorType> ltensor, TensorType alpha, bool is_lt = true) { std::function<TensorType(TensorType)> func = [&](TensorType a) { return std::pow(a, alpha); }; return apply_ewise(ltensor, func, is_lt); } template<typename TensorType> Tensor<TensorType> pow(Tensor<TensorType> tensor, TensorType alpha) { return pow(tensor(),alpha, false); } template<typename TensorType> Tensor<TensorType> scale(LabeledTensor<TensorType> ltensor, TensorType alpha, bool is_lt = true) { std::function<TensorType(TensorType)> func = [&](TensorType a) { return alpha * a; }; return apply_ewise(ltensor, func, is_lt); } template<typename TensorType> Tensor<TensorType> scale(Tensor<TensorType> tensor, TensorType alpha) { return scale(tensor(),alpha, false); } template<typename TensorType> Tensor<TensorType> sqrt(LabeledTensor<TensorType> ltensor, bool is_lt = true) { std::function<TensorType(TensorType)> func = [&](TensorType a) { return std::sqrt(a); }; return apply_ewise(ltensor, func, is_lt); } template<typename TensorType> Tensor<TensorType> sqrt(Tensor<TensorType> tensor) { return sqrt(tensor(), false); } template<typename TensorType> void random_ip(LabeledTensor<TensorType> ltensor, bool is_lt = true) { //std::random_device random_device; std::default_random_engine generator; std::uniform_real_distribution<TensorType> tensor_rand_dist(0.0,1.0); std::function<TensorType(TensorType)> func = [&](TensorType a) { return tensor_rand_dist(generator); }; apply_ewise_ip(ltensor, func); } template<typename TensorType> void random_ip(Tensor<TensorType> tensor) { random_ip(tensor(), false); } template<typename TensorType> TensorType sum(LabeledTensor<TensorType> ltensor) { ExecutionContext& gec = get_ec(ltensor); TensorType lsumsq = 0; TensorType gsumsq = 0; Tensor<TensorType> tensor = ltensor.tensor(); MPI_Comm sub_comm; int rank = gec.pg().rank().value(); get_subgroup_info(gec,tensor,sub_comm); if(sub_comm != MPI_COMM_NULL) { ProcGroup pg = ProcGroup {ProcGroup::create_coll(sub_comm)}; ExecutionContext ec{pg, DistributionKind::nw, MemoryManagerKind::ga}; auto getnorm = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<TensorType> dbuf(dsize); tensor.get(blockid, dbuf); if constexpr(std::is_same_v<TensorType, std::complex<double>> || std::is_same_v<TensorType, std::complex<float>>) for(auto val : dbuf) lsumsq += val; }; block_for(ec, ltensor, getnorm); ec.flush_and_sync(); //MemoryManagerGA::destroy_coll(mgr); MPI_Comm_free(&sub_comm); pg.destroy_coll(); } gec.pg().barrier(); MPI_Allreduce(&lsumsq, &gsumsq, 1, mpi_type<TensorType>(), MPI_SUM, gec.pg().comm()); return gsumsq; } template<typename TensorType> TensorType sum(Tensor<TensorType> tensor) { return sum(tensor()); } template<typename TensorType> TensorType norm_unused(LabeledTensor<TensorType> ltensor) { ExecutionContext& ec = get_ec(ltensor); Scheduler sch{ec}; Tensor<TensorType> nval{}; sch.allocate(nval); if constexpr(internal::is_complex_v<TensorType>){ auto ltconj = tamm::conj(ltensor); sch(nval() = ltconj() * ltensor).deallocate(ltconj).execute(); } else sch(nval() = ltensor * ltensor).execute(); auto rval = get_scalar(nval); sch.deallocate(nval).execute(); return std::sqrt(rval); } template<typename TensorType> TensorType norm(Tensor<TensorType> tensor) { return norm(tensor()); } template<typename TensorType> TensorType norm(LabeledTensor<TensorType> ltensor) { ExecutionContext& gec = get_ec(ltensor); TensorType lsumsq = 0; TensorType gsumsq = 0; Tensor<TensorType> tensor = ltensor.tensor(); MPI_Comm sub_comm; int rank = gec.pg().rank().value(); get_subgroup_info(gec,tensor,sub_comm); if(sub_comm != MPI_COMM_NULL) { ProcGroup pg = ProcGroup {ProcGroup::create_coll(sub_comm)}; ExecutionContext ec{pg, DistributionKind::nw, MemoryManagerKind::ga}; auto getnorm = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<TensorType> dbuf(dsize); tensor.get(blockid, dbuf); if constexpr(std::is_same_v<TensorType, std::complex<double>> || std::is_same_v<TensorType, std::complex<float>>) for(TensorType val : dbuf) lsumsq += val * std::conj(val); else for(TensorType val : dbuf) lsumsq += val * val; }; block_for(ec, ltensor, getnorm); ec.flush_and_sync(); //MemoryManagerGA::destroy_coll(mgr); MPI_Comm_free(&sub_comm); pg.destroy_coll(); } gec.pg().barrier(); MPI_Allreduce(&lsumsq, &gsumsq, 1, mpi_type<TensorType>(), MPI_SUM, gec.pg().comm()); return std::sqrt(gsumsq); } template<typename TensorType> void gf_peak_coord(int nmodes, std::vector<TensorType> dbuf, std::vector<size_t> block_dims, std::vector<size_t> block_offset, double threshold, double x_norm_sq, int rank, std::ostringstream& spfe){ size_t c = 0; if(nmodes == 1) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++, c++) { auto val = dbuf[c]; double lv = 0; if constexpr(std::is_same_v<TensorType, std::complex<double>> || std::is_same_v<TensorType, std::complex<float>>) lv = std::real(val * std::conj(val)); else lv = val * val; size_t x1 = i; double weight = lv/x_norm_sq; if(weight>threshold) spfe << " coord. = (" << x1 << "), wt. = " << weight << std::endl; } } else if(nmodes == 2) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++, c++) { auto val = dbuf[c]; double lv = 0; if constexpr(std::is_same_v<TensorType, std::complex<double>> || std::is_same_v<TensorType, std::complex<float>>) lv = std::real(val * std::conj(val)); else lv = val * val; size_t x1 = i; size_t x2 = j; double weight = lv/x_norm_sq; if(weight>threshold){ spfe << " coord. = (" << x1 << "," << x2 << "), wt. = " << weight << std::endl; } } } } else if(nmodes == 3) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++) { for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2]; k++, c++) { auto val = dbuf[c]; double lv = 0; if constexpr(std::is_same_v<TensorType, std::complex<double>> || std::is_same_v<TensorType, std::complex<float>>) lv = std::real(val * std::conj(val)); else lv = val * val; //if(lv>threshold) { size_t x1 = i; size_t x2 = j; size_t x3 = k; double weight = lv/x_norm_sq; if(weight>threshold) spfe << " coord. = (" << x1 << "," << x2 << "," << x3 << "), wt. = " << weight << std::endl; } } } } else if(nmodes == 4) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++) { for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2]; k++) { for(size_t l = block_offset[3]; l < block_offset[3] + block_dims[3]; l++, c++) { auto val = dbuf[c]; double lv = 0; if constexpr(std::is_same_v<TensorType, std::complex<double>> || std::is_same_v<TensorType, std::complex<float>>) lv = std::real(val * std::conj(val)); else lv = val * val; size_t x1 = i; size_t x2 = j; size_t x3 = k; size_t x4 = l; double weight = lv/x_norm_sq; if(weight>threshold) spfe << " coord. = (" << x1 << "," << x2 << "," << x3 << "," << x4 << "), wt. = " << weight << std::endl; } } } } } else if(nmodes == 5) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++) { for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2]; k++) { for(size_t l = block_offset[3]; l < block_offset[3] + block_dims[3]; l++) { for(size_t m = block_offset[4]; m < block_offset[4] + block_dims[4]; m++, c++) { auto val = dbuf[c]; double lv = 0; if constexpr(std::is_same_v<TensorType, std::complex<double>> || std::is_same_v<TensorType, std::complex<float>>) lv = std::real(val * std::conj(val)); else lv = val * val; // if(lv>threshold) { size_t x1 = i; size_t x2 = j; size_t x3 = k; size_t x4 = l; size_t x5 = m; double weight = lv/x_norm_sq; if(weight>threshold) spfe << " coord. = (" << x1 << "," << x2 << "," << x3 << "," << x4 << "," << x5 << "), wt. = " << weight << std::endl; } } } } } } } template<typename TensorType> void gf_peak(Tensor<TensorType> tensor, double threshold, double x_norm_sq, std::ostringstream& spfe) { return gf_peak(tensor(),threshold,x_norm_sq,spfe); } template<typename TensorType> void gf_peak(LabeledTensor<TensorType> ltensor, double threshold, double x_norm_sq, std::ostringstream& spfe) { ExecutionContext& gec = get_ec(ltensor); Tensor<TensorType> tensor = ltensor.tensor(); MPI_Comm sub_comm; int rank = gec.pg().rank().value(); get_subgroup_info(gec,tensor,sub_comm); if(sub_comm != MPI_COMM_NULL) { ProcGroup pg = ProcGroup {ProcGroup::create_coll(sub_comm)}; ExecutionContext ec{pg, DistributionKind::nw, MemoryManagerKind::ga}; auto nmodes = tensor.num_modes(); auto getnorm = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<TensorType> dbuf(dsize); tensor.get(blockid, dbuf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); gf_peak_coord(nmodes,dbuf,block_dims,block_offset,threshold,x_norm_sq,rank,spfe); }; block_for(ec, ltensor, getnorm); ec.flush_and_sync(); //MemoryManagerGA::destroy_coll(mgr); MPI_Comm_free(&sub_comm); pg.destroy_coll(); } gec.pg().barrier(); } // returns max_element, blockids, coordinates of max element in the block template<typename TensorType> std::tuple<TensorType, IndexVector, std::vector<size_t>> max_element(Tensor<TensorType> tensor) { return max_element(tensor()); } template<typename TensorType> std::tuple<TensorType, IndexVector, std::vector<size_t>> max_element(LabeledTensor<TensorType> ltensor) { ExecutionContext& ec = get_ec(ltensor); TensorType max = 0.0; Tensor<TensorType> tensor = ltensor.tensor(); auto nmodes = tensor.num_modes(); // Works for only upto 6D tensors EXPECTS(tensor.num_modes() <= 6); IndexVector maxblockid(nmodes); std::vector<size_t> bfuv(nmodes); std::vector<TensorType> lmax(2, 0); std::vector<TensorType> gmax(2, 0); auto getmax = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<TensorType> dbuf(dsize); tensor.get(blockid, dbuf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); size_t c = 0; if(nmodes == 1) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++, c++) { if(lmax[0] < dbuf[c]) { lmax[0] = dbuf[c]; lmax[1] = GA_Nodeid(); bfuv[0] = i - block_offset[0]; maxblockid = {blockid[0]}; } } } else if(nmodes == 2) { auto dimi = block_offset[0] + block_dims[0]; auto dimj = block_offset[1] + block_dims[1]; for(size_t i = block_offset[0]; i < dimi; i++) { for(size_t j = block_offset[1]; j < dimj; j++, c++) { if(lmax[0] < dbuf[c]) { lmax[0] = dbuf[c]; lmax[1] = GA_Nodeid(); bfuv[0] = i - block_offset[0]; bfuv[1] = j - block_offset[1]; maxblockid = {blockid[0], blockid[1]}; } } } } else if(nmodes == 3) { auto dimi = block_offset[0] + block_dims[0]; auto dimj = block_offset[1] + block_dims[1]; auto dimk = block_offset[2] + block_dims[2]; for(size_t i = block_offset[0]; i < dimi; i++) { for(size_t j = block_offset[1]; j < dimj; j++) { for(size_t k = block_offset[2]; k < dimk; k++, c++) { if(lmax[0] < dbuf[c]) { lmax[0] = dbuf[c]; lmax[1] = GA_Nodeid(); bfuv[0] = i - block_offset[0]; bfuv[1] = j - block_offset[1]; bfuv[2] = k - block_offset[2]; maxblockid = {blockid[0], blockid[1], blockid[2]}; } } } } } else if(nmodes == 4) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++) { for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2]; k++) { for(size_t l = block_offset[3]; l < block_offset[3] + block_dims[3]; l++, c++) { if(lmax[0] < dbuf[c]) { lmax[0] = dbuf[c]; lmax[1] = GA_Nodeid(); bfuv[0] = i - block_offset[0]; bfuv[1] = j - block_offset[1]; bfuv[2] = k - block_offset[2]; bfuv[3] = l - block_offset[3]; maxblockid = {blockid[0], blockid[1], blockid[2], blockid[3]}; } } } } } } else if(nmodes == 5) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++) { for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2]; k++) { for(size_t l = block_offset[3]; l < block_offset[3] + block_dims[3]; l++) { for(size_t m = block_offset[4]; m < block_offset[4] + block_dims[4]; m++, c++) { if(lmax[0] < dbuf[c]) { lmax[0] = dbuf[c]; lmax[1] = GA_Nodeid(); bfuv[0] = i - block_offset[0]; bfuv[1] = j - block_offset[1]; bfuv[2] = k - block_offset[2]; bfuv[3] = l - block_offset[3]; bfuv[4] = m - block_offset[4]; maxblockid = {blockid[0], blockid[1], blockid[2], blockid[3], blockid[4]}; } } } } } } } else if(nmodes == 6) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++) { for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2]; k++) { for(size_t l = block_offset[3]; l < block_offset[3] + block_dims[3]; l++) { for(size_t m = block_offset[4]; m < block_offset[4] + block_dims[4]; m++) { for(size_t n = block_offset[5]; n < block_offset[5] + block_dims[5]; n++, c++) { if(lmax[0] < dbuf[c]) { lmax[0] = dbuf[c]; lmax[1] = GA_Nodeid(); bfuv[0] = i - block_offset[0]; bfuv[1] = j - block_offset[1]; bfuv[2] = k - block_offset[2]; bfuv[3] = l - block_offset[3]; bfuv[4] = m - block_offset[4]; bfuv[5] = n - block_offset[5]; maxblockid = {blockid[0], blockid[1], blockid[2], blockid[3], blockid[4], blockid[5]}; } } } } } } } } }; block_for(ec, ltensor, getmax); MPI_Allreduce(lmax.data(), gmax.data(), 1, MPI_2DOUBLE_PRECISION, MPI_MAXLOC, ec.pg().comm()); MPI_Bcast(maxblockid.data(), 2, MPI_UNSIGNED, gmax[1], ec.pg().comm()); MPI_Bcast(bfuv.data(), 2, MPI_UNSIGNED_LONG, gmax[1], ec.pg().comm()); return std::make_tuple(gmax[0], maxblockid, bfuv); } // returns min_element, blockids, coordinates of min element in the block template<typename TensorType> std::tuple<TensorType, IndexVector, std::vector<size_t>> min_element(Tensor<TensorType> tensor) { return min_element(tensor()); } template<typename TensorType> std::tuple<TensorType, IndexVector, std::vector<size_t>> min_element(LabeledTensor<TensorType> ltensor) { ExecutionContext& ec = get_ec(ltensor); TensorType min = 0.0; Tensor<TensorType> tensor = ltensor.tensor(); auto nmodes = tensor.num_modes(); // Works for only upto 6D tensors EXPECTS(tensor.num_modes() <= 6); IndexVector minblockid(nmodes); std::vector<size_t> bfuv(2); std::vector<TensorType> lmin(2, 0); std::vector<TensorType> gmin(2, 0); auto getmin = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); std::vector<TensorType> dbuf(dsize); tensor.get(blockid, dbuf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); size_t c = 0; if(nmodes == 1) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++, c++) { if(lmin[0] > dbuf[c]) { lmin[0] = dbuf[c]; lmin[1] = GA_Nodeid(); bfuv[0] = i - block_offset[0]; minblockid = {blockid[0]}; } } } else if(nmodes == 2) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++, c++) { if(lmin[0] > dbuf[c]) { lmin[0] = dbuf[c]; lmin[1] = GA_Nodeid(); bfuv[0] = i - block_offset[0]; bfuv[1] = j - block_offset[1]; minblockid = {blockid[0], blockid[1]}; } } } } else if(nmodes == 3) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++) { for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2]; k++, c++) { if(lmin[0] > dbuf[c]) { lmin[0] = dbuf[c]; lmin[1] = GA_Nodeid(); bfuv[0] = i - block_offset[0]; bfuv[1] = j - block_offset[1]; bfuv[2] = k - block_offset[2]; minblockid = {blockid[0], blockid[1], blockid[2]}; } } } } } else if(nmodes == 4) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++) { for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2]; k++) { for(size_t l = block_offset[3]; l < block_offset[3] + block_dims[3]; l++, c++) { if(lmin[0] > dbuf[c]) { lmin[0] = dbuf[c]; lmin[1] = GA_Nodeid(); bfuv[0] = i - block_offset[0]; bfuv[1] = j - block_offset[1]; bfuv[2] = k - block_offset[2]; bfuv[3] = l - block_offset[3]; minblockid = {blockid[0], blockid[1], blockid[2], blockid[3]}; } } } } } } else if(nmodes == 5) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++) { for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2]; k++) { for(size_t l = block_offset[3]; l < block_offset[3] + block_dims[3]; l++) { for(size_t m = block_offset[4]; m < block_offset[4] + block_dims[4]; m++, c++) { if(lmin[0] > dbuf[c]) { lmin[0] = dbuf[c]; lmin[1] = GA_Nodeid(); bfuv[0] = i - block_offset[0]; bfuv[1] = j - block_offset[1]; bfuv[2] = k - block_offset[2]; bfuv[3] = l - block_offset[3]; bfuv[4] = m - block_offset[4]; minblockid = {blockid[0], blockid[1], blockid[2], blockid[3], blockid[4]}; } } } } } } } else if(nmodes == 6) { for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++) { for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2]; k++) { for(size_t l = block_offset[3]; l < block_offset[3] + block_dims[3]; l++) { for(size_t m = block_offset[4]; m < block_offset[4] + block_dims[4]; m++) { for(size_t n = block_offset[5]; n < block_offset[5] + block_dims[5]; n++, c++) { if(lmin[0] > dbuf[c]) { lmin[0] = dbuf[c]; lmin[1] = GA_Nodeid(); bfuv[0] = i - block_offset[0]; bfuv[1] = j - block_offset[1]; bfuv[2] = k - block_offset[2]; bfuv[3] = l - block_offset[3]; bfuv[4] = m - block_offset[4]; bfuv[5] = n - block_offset[5]; minblockid = {blockid[0], blockid[1], blockid[2], blockid[3], blockid[4], blockid[5]}; } } } } } } } } }; block_for(ec, ltensor, getmin); MPI_Allreduce(lmin.data(), gmin.data(), 1, MPI_2DOUBLE_PRECISION, MPI_MINLOC, ec.pg().comm()); MPI_Bcast(minblockid.data(), 2, MPI_UNSIGNED, gmin[1], ec.pg().comm()); MPI_Bcast(bfuv.data(), 2, MPI_UNSIGNED_LONG, gmin[1], ec.pg().comm()); return std::make_tuple(gmin[0], minblockid, bfuv); } // following is when tamm tensor is a 2D GA irreg // template<typename TensorType> // Tensor<TensorType> to_block_cyclic_tensor(ProcGrid pg, Tensor<TensorType> tensor) // { // EXPECTS(tensor.num_modes() == 2); // LabeledTensor<TensorType> ltensor = tensor(); // ExecutionContext& ec = get_ec(ltensor); // auto tis = tensor.tiled_index_spaces(); // const bool is_irreg_tis1 = !tis[0].input_tile_sizes().empty(); // const bool is_irreg_tis2 = !tis[1].input_tile_sizes().empty(); // std::vector<Tile> tiles1 = // is_irreg_tis1? tis_dims[0].input_tile_sizes() // : std::vector<Tile>{tis_dims[0].input_tile_size()}; // std::vector<Tile> tiles2 = // is_irreg_tis2? tis_dims[1].input_tile_sizes() // : std::vector<Tile>{tis_dims[1].input_tile_size()}; // //Choose tile size based on tile sizes of regular tensor // //TODO: Can user provide tilesize for block-cylic tensor? // Tile max_t1 = is_irreg_tis1? *max_element(tiles1.begin(), tiles1.end()) : tiles1[0]; // Tile max_t2 = is_irreg_tis2? *max_element(tiles2.begin(), tiles2.end()) : tiles2[0]; // TiledIndexSpace t1{range(tis[0].index_space().num_indices()),max_t1}; // TiledIndexSpace t2{range(tis[1].index_space().num_indices()),max_t2}; // Tensor<TensorType> bc_tensor{pg,{t1,t2}}; // Tensor<TensorType>::allocate(&ec,bc_tensor); // GA_Copy(tensor.ga_handle(),bc_tensor.ga_handle()); // //caller is responsible for deallocating bc_tensor // return bc_tensor; // } template<typename TensorType> std::tuple<TensorType*,int64_t> access_local_block_cyclic_buffer(Tensor<TensorType> tensor) { EXPECTS(tensor.num_modes() == 2); int gah = tensor.ga_handle(); ExecutionContext& ec = get_ec(tensor()); TensorType* lbufptr; int64_t lbufsize; NGA_Access_block_segment64(gah, ec.pg().rank().value(), reinterpret_cast<void*>(&lbufptr), &lbufsize); return std::make_tuple(lbufptr,lbufsize); } template<typename TensorType> Tensor<TensorType> to_block_cyclic_tensor(Tensor<TensorType> tensor, ProcGrid pg, std::vector<int64_t> tilesizes) { EXPECTS(tensor.num_modes() == 2); LabeledTensor<TensorType> ltensor = tensor(); ExecutionContext& ec = get_ec(ltensor); auto tis = tensor.tiled_index_spaces(); const bool is_irreg_tis1 = !tis[0].input_tile_sizes().empty(); const bool is_irreg_tis2 = !tis[1].input_tile_sizes().empty(); std::vector<Tile> tiles1 = is_irreg_tis1? tis[0].input_tile_sizes() : std::vector<Tile>{tis[0].input_tile_size()}; std::vector<Tile> tiles2 = is_irreg_tis2? tis[1].input_tile_sizes() : std::vector<Tile>{tis[1].input_tile_size()}; //Choose tile size based on tile sizes of regular tensor //TODO: Can user provide tilesize for block-cylic tensor? Tile max_t1 = is_irreg_tis1? *max_element(tiles1.begin(), tiles1.end()) : tiles1[0]; Tile max_t2 = is_irreg_tis2? *max_element(tiles2.begin(), tiles2.end()) : tiles2[0]; if(!tilesizes.empty()) { EXPECTS(tilesizes.size() == 2); max_t1 = static_cast<Tile>(tilesizes[0]); max_t2 = static_cast<Tile>(tilesizes[1]); } TiledIndexSpace t1{range(tis[0].index_space().num_indices()),max_t1}; TiledIndexSpace t2{range(tis[1].index_space().num_indices()),max_t2}; Tensor<TensorType> bc_tensor{pg,{t1,t2}}; Tensor<TensorType>::allocate(&ec,bc_tensor); int bc_tensor_gah = bc_tensor.ga_handle(); //convert regular 2D tamm tensor to block cyclic tamm tensor auto copy_to_bc = [&](const IndexVector& bid){ const IndexVector blockid = internal::translate_blockid(bid, ltensor); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); int64_t lo[2] = {cd_ncast<size_t>(block_offset[0]), cd_ncast<size_t>(block_offset[1])}; int64_t hi[2] = {cd_ncast<size_t>(block_offset[0] + block_dims[0]-1), cd_ncast<size_t>(block_offset[1] + block_dims[1]-1)}; int64_t ld = cd_ncast<size_t>(block_dims[1]); std::vector<TensorType> sbuf(dsize); tensor.get(blockid, sbuf); NGA_Put64(bc_tensor_gah,lo,hi,&sbuf[0],&ld); }; block_for(ec, ltensor, copy_to_bc); //caller is responsible for deallocating return bc_tensor; } template<typename TensorType> void from_block_cyclic_tensor(Tensor<TensorType> bc_tensor, Tensor<TensorType> tensor) { EXPECTS(tensor.num_modes() == 2 && bc_tensor.num_modes() == 2); LabeledTensor<TensorType> ltensor = tensor(); ExecutionContext& ec = get_ec(ltensor); int bc_handle = bc_tensor.ga_handle(); // convert a block cyclic tamm tensor to regular 2D tamm tensor auto copy_from_bc = [&](const IndexVector& bid){ const IndexVector blockid = internal::translate_blockid(bid, ltensor); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); int64_t lo[2] = {cd_ncast<size_t>(block_offset[0]), cd_ncast<size_t>(block_offset[1])}; int64_t hi[2] = {cd_ncast<size_t>(block_offset[0] + block_dims[0]-1), cd_ncast<size_t>(block_offset[1] + block_dims[1]-1)}; int64_t ld = cd_ncast<size_t>(block_dims[1]); std::vector<TensorType> sbuf(dsize); NGA_Get64(bc_handle,lo,hi,&sbuf[0],&ld); tensor.put(blockid, sbuf); }; block_for(ec, ltensor, copy_from_bc); } inline TiledIndexLabel compose_lbl(const TiledIndexLabel& lhs, const TiledIndexLabel& rhs) { auto lhs_tis = lhs.tiled_index_space(); auto rhs_tis = rhs.tiled_index_space(); auto res_tis = lhs_tis.compose_tis(rhs_tis); return res_tis.label("all"); } inline TiledIndexSpace compose_tis(const TiledIndexSpace& lhs, const TiledIndexSpace& rhs) { return lhs.compose_tis(rhs); } inline TiledIndexLabel invert_lbl(const TiledIndexLabel& lhs) { auto lhs_tis = lhs.tiled_index_space().invert_tis(); return lhs_tis.label("all"); } inline TiledIndexSpace invert_tis(const TiledIndexSpace& lhs) { return lhs.invert_tis(); } inline TiledIndexLabel intersect_lbl(const TiledIndexLabel& lhs, const TiledIndexLabel& rhs) { auto lhs_tis = lhs.tiled_index_space(); auto rhs_tis = rhs.tiled_index_space(); auto res_tis = lhs_tis.intersect_tis(rhs_tis); return res_tis.label("all"); } inline TiledIndexSpace intersect_tis(const TiledIndexSpace& lhs, const TiledIndexSpace& rhs) { return lhs.intersect_tis(rhs); } inline TiledIndexLabel union_lbl(const TiledIndexLabel& lhs, const TiledIndexLabel& rhs) { auto lhs_tis = lhs.tiled_index_space(); auto rhs_tis = rhs.tiled_index_space(); auto res_tis = lhs_tis.union_tis(rhs_tis); return res_tis.label("all"); } inline TiledIndexSpace union_tis(const TiledIndexSpace& lhs, const TiledIndexSpace& rhs) { return lhs.union_tis(rhs); } inline TiledIndexLabel project_lbl(const TiledIndexLabel& lhs, const TiledIndexLabel& rhs) { auto lhs_tis = lhs.tiled_index_space(); auto rhs_tis = rhs.tiled_index_space(); auto res_tis = lhs_tis.project_tis(rhs_tis); return res_tis.label("all"); } inline TiledIndexSpace project_tis(const TiledIndexSpace& lhs, const TiledIndexSpace& rhs) { return lhs.project_tis(rhs); } /// @todo: Implement template<typename TensorType> inline TensorType invert_tensor(TensorType tens) { TensorType res; return res; } /** * @brief uses a function to fill in elements of a tensor * * @tparam TensorType the type of the elements in the tensor * @param ec Execution context used in the blockfor * @param ltensor tensor to operate on * @param func function to fill in the tensor with */ template<typename TensorType> inline size_t hash_tensor(ExecutionContext* ec, Tensor<TensorType> tensor) { auto ltensor = tensor(); size_t hash = tensor.num_modes(); auto lambda = [&](const IndexVector& bid) { const IndexVector blockid = internal::translate_blockid(bid, ltensor); const tamm::TAMM_SIZE dsize = tensor.block_size(blockid); internal::hash_combine(hash, tensor.block_size(blockid)); std::vector<TensorType> dbuf(dsize); tensor.get(blockid, dbuf); for(auto& val : dbuf) { internal::hash_combine(hash, val); } }; block_for(*ec, ltensor, lambda); return hash; } } // namespace tamm #endif // TAMM_TAMM_UTILS_HPP_
37.793993
144
0.557743
smferdous1
3874c2e7c52b6295ccf37da849b6a82a7c1e2c62
10,702
cpp
C++
common/resource/entity_manager.cpp
Pength-TH/egal-D-engine
f16a8def566f678cb324bd901768d32f4412396f
[ "Apache-2.0" ]
null
null
null
common/resource/entity_manager.cpp
Pength-TH/egal-D-engine
f16a8def566f678cb324bd901768d32f4412396f
[ "Apache-2.0" ]
null
null
null
common/resource/entity_manager.cpp
Pength-TH/egal-D-engine
f16a8def566f678cb324bd901768d32f4412396f
[ "Apache-2.0" ]
null
null
null
#include "common/resource/entity_manager.h" #include "common/egal-d.h" #include "common/resource/resource_manager.h" #include "common/resource/material_manager.h" #include "common/lua/lua_manager.h" namespace egal { e_bool Entity::force_keep_skin = false; Mesh::Mesh ( Material* mat, const bgfx::VertexDecl& vertex_decl, const e_char* name, IAllocator& allocator ) : name(name, allocator) , vertex_decl(vertex_decl) , material(mat) , instance_idx(-1) , indices(allocator) , vertices(allocator) , uvs(allocator) , skin(allocator) { } e_void Mesh::set(const Mesh& rhs) { type = rhs.type; indices = rhs.indices; vertices = rhs.vertices; uvs = rhs.uvs; skin = rhs.skin; flags = rhs.flags; layer_mask = rhs.layer_mask; instance_idx = rhs.instance_idx; indices_count = rhs.indices_count; vertex_decl = rhs.vertex_decl; vertex_buffer_handle = rhs.vertex_buffer_handle; index_buffer_handle = rhs.index_buffer_handle; name = rhs.name; // all except material } e_void Mesh::setMaterial(Material* new_material, Entity& Entity, Renderer& renderer) { if (material) material->getResourceManager().unload(*material); material = new_material; static const e_int32 transparent_layer = renderer.getLayer("transparent"); layer_mask = material->getRenderLayerMask(); if (material->getRenderLayer() == transparent_layer) { type = Mesh::RIGID; } else if (material->getLayersCount() > 0) { if (Entity.getBoneCount() > 0) { type = Mesh::MULTILAYER_SKINNED; } else { type = Mesh::MULTILAYER_RIGID; } } else if (Entity.getBoneCount() > 0) { type = skin.empty() ? Mesh::RIGID_INSTANCED : Mesh::SKINNED; } else type = Mesh::RIGID_INSTANCED; } Pose::Pose(IAllocator& allocator) : allocator(allocator) { positions = nullptr; rotations = nullptr; count = 0; is_absolute = false; } Pose::~Pose() { allocator.deallocate(positions); allocator.deallocate(rotations); } e_void Pose::blend(Pose& rhs, e_float weight) { ASSERT(count == rhs.count); if (weight <= 0.001f) return; weight = Math::clamp(weight, 0.0f, 1.0f); e_float inv = 1.0f - weight; for (e_int32 i = 0, c = count; i < c; ++i) { positions[i] = positions[i] * inv + rhs.positions[i] * weight; nlerp(rotations[i], rhs.rotations[i], &rotations[i], weight); } } e_void Pose::resize(e_int32 count) { is_absolute = false; allocator.deallocate(positions); allocator.deallocate(rotations); this->count = count; if (count) { positions = static_cast<float3*>(allocator.allocate(sizeof(float3) * count)); rotations = static_cast<Quaternion*>(allocator.allocate(sizeof(Quaternion) * count)); } else { positions = nullptr; rotations = nullptr; } } e_void Pose::computeAbsolute(Entity& entity) { //PROFILE_FUNCTION(); if (is_absolute) return; for (e_int32 i = entity.getFirstNonrootBoneIndex(); i < count; ++i) { e_int32 parent = entity.getBone(i).parent_idx; positions[i] = rotations[parent].rotate(positions[i]) + positions[parent]; rotations[i] = rotations[parent] * rotations[i]; } is_absolute = true; } e_void Pose::computeRelative(Entity& entity) { //PROFILE_FUNCTION(); if (!is_absolute) return; for (e_int32 i = count - 1; i >= entity.getFirstNonrootBoneIndex(); --i) { e_int32 parent = entity.getBone(i).parent_idx; positions[i] = -rotations[parent].rotate(positions[i] - positions[parent]); rotations[i] = rotations[i] * -rotations[parent]; } is_absolute = false; } Entity::Entity(const ArchivePath& path, ResourceManagerBase& resource_manager, Renderer& renderer, IAllocator& allocator) : Resource(path, resource_manager, allocator) , m_bounding_radius() , m_allocator(allocator) , m_bone_map(m_allocator) , m_meshes(m_allocator) , m_bones(m_allocator) , m_first_nonroot_bone_index(0) , m_flags(0) , m_loading_flags(0) , m_lod_count(0) , m_renderer(renderer) { if (force_keep_skin) m_loading_flags = (e_uint32)LoadingFlags::KEEP_SKIN; m_lods[0] = { 0, -1, FLT_MAX }; m_lods[1] = { 0, -1, FLT_MAX }; m_lods[2] = { 0, -1, FLT_MAX }; m_lods[3] = { 0, -1, FLT_MAX }; } Entity::~Entity() { ASSERT(isEmpty()); } static float3 evaluateSkin(float3& p, Mesh::Skin s, const float4x4* matrices) { float4x4 m = matrices[s.indices[0]] * s.weights.x + matrices[s.indices[1]] * s.weights.y + matrices[s.indices[2]] * s.weights.z + matrices[s.indices[3]] * s.weights.w; return m.transformPoint(p); } static e_void computeSkinMatrices(const Pose& pose, const Entity& Entity, float4x4* matrices) { for (e_int32 i = 0; i < pose.count; ++i) { auto& bone = Entity.getBone(i); RigidTransform tmp = { pose.positions[i], pose.rotations[i] }; matrices[i] = (tmp * bone.inv_bind_transform).toMatrix(); } } RayCastEntityHit Entity::castRay(const float3& origin, const float3& dir, const Matrix& model_transform, const Pose* pose) { RayCastEntityHit hit; hit.m_is_hit = false; if (!isReady()) return hit; Matrix inv = model_transform; inv.inverse(); float3 local_origin = inv.transformPoint(origin); float3 local_dir = static_cast<float3>(inv * float4(dir.x, dir.y, dir.z, 0)); Matrix matrices[256]; ASSERT(!pose || pose->count <= TlengthOf(matrices)); e_bool is_skinned = false; for (e_int32 mesh_index = m_lods[0].from_mesh; mesh_index <= m_lods[0].to_mesh; ++mesh_index) { Mesh& mesh = m_meshes[mesh_index]; is_skinned = pose && !mesh.skin.empty() && pose->count <= TlengthOf(matrices); } if (is_skinned) { computeSkinMatrices(*pose, *this, matrices); } for (e_int32 mesh_index = m_lods[0].from_mesh; mesh_index <= m_lods[0].to_mesh; ++mesh_index) { Mesh& mesh = m_meshes[mesh_index]; e_bool is_mesh_skinned = !mesh.skin.empty(); e_uint16* indices16 = (e_uint16*)&mesh.indices[0]; e_uint32* indices32 = (e_uint32*)&mesh.indices[0]; e_bool is16 = mesh.flags & (e_uint32)Mesh::Flags::INDICES_16_BIT; e_int32 index_size = is16 ? 2 : 4; for (e_int32 i = 0, c = mesh.indices.size() / index_size; i < c; i += 3) { float3 p0, p1, p2; if (is16) { p0 = mesh.vertices[indices16[i]]; p1 = mesh.vertices[indices16[i + 1]]; p2 = mesh.vertices[indices16[i + 2]]; if (is_mesh_skinned) { p0 = evaluateSkin(p0, mesh.skin[indices16[i]], matrices); p1 = evaluateSkin(p1, mesh.skin[indices16[i + 1]], matrices); p2 = evaluateSkin(p2, mesh.skin[indices16[i + 2]], matrices); } } else { p0 = mesh.vertices[indices32[i]]; p1 = mesh.vertices[indices32[i + 1]]; p2 = mesh.vertices[indices32[i + 2]]; if (is_mesh_skinned) { p0 = evaluateSkin(p0, mesh.skin[indices32[i]], matrices); p1 = evaluateSkin(p1, mesh.skin[indices32[i + 1]], matrices); p2 = evaluateSkin(p2, mesh.skin[indices32[i + 2]], matrices); } } float3 normal = crossProduct(p1 - p0, p2 - p0); e_float q = dotProduct(normal, local_dir); if (q == 0) continue; e_float d = -dotProduct(normal, p0); e_float t = -(dotProduct(normal, local_origin) + d) / q; if (t < 0) continue; float3 hit_point = local_origin + local_dir * t; float3 edge0 = p1 - p0; float3 VP0 = hit_point - p0; if (dotProduct(normal, crossProduct(edge0, VP0)) < 0) continue; float3 edge1 = p2 - p1; float3 VP1 = hit_point - p1; if (dotProduct(normal, crossProduct(edge1, VP1)) < 0) continue; float3 edge2 = p0 - p2; float3 VP2 = hit_point - p2; if (dotProduct(normal, crossProduct(edge2, VP2)) < 0) continue; if (!hit.m_is_hit || hit.m_t > t) { hit.m_is_hit = true; hit.m_t = t; hit.m_mesh = &m_meshes[mesh_index]; } } } hit.m_origin = origin; hit.m_dir = dir; return hit; } e_void Entity::getRelativePose(Pose& pose) { ASSERT(pose.count == getBoneCount()); float3* pos = pose.positions; Quaternion* rot = pose.rotations; for (e_int32 i = 0, c = getBoneCount(); i < c; ++i) { pos[i] = m_bones[i].relative_transform.pos; rot[i] = m_bones[i].relative_transform.rot; } pose.is_absolute = false; } e_void Entity::getPose(Pose& pose) { ASSERT(pose.count == getBoneCount()); float3* pos = pose.positions; Quaternion* rot = pose.rotations; for (e_int32 i = 0, c = getBoneCount(); i < c; ++i) { pos[i] = m_bones[i].transform.pos; rot[i] = m_bones[i].transform.rot; } pose.is_absolute = true; } e_void Entity::onBeforeReady() { static const e_int32 transparent_layer = m_renderer.getLayer("transparent"); for (Mesh& mesh : m_meshes) { mesh.layer_mask = mesh.material->getRenderLayerMask(); if (mesh.material->getRenderLayer() == transparent_layer) { mesh.type = Mesh::RIGID; } else if (mesh.material->getLayersCount() > 0) { if (getBoneCount() > 0) { mesh.type = Mesh::MULTILAYER_SKINNED; } else { mesh.type = Mesh::MULTILAYER_RIGID; } } else if (getBoneCount() > 0) { mesh.type = mesh.skin.empty() ? Mesh::RIGID_INSTANCED : Mesh::SKINNED; } else mesh.type = Mesh::RIGID_INSTANCED; } } e_void Entity::setKeepSkin() { if (m_loading_flags & (e_uint32)LoadingFlags::KEEP_SKIN) return; m_loading_flags = m_loading_flags | (e_uint32)LoadingFlags::KEEP_SKIN; if (isReady()) m_resource_manager.reload(*this); } e_int32 Entity::getBoneIdx(const e_char* name) { for (e_int32 i = 0, c = m_bones.size(); i < c; ++i) { if (m_bones[i].name == name) { return i; } } return -1; } } namespace egal { Resource* EntityManager::createResource(const ArchivePath& path) { return _aligned_new(m_allocator, Entity)(path, *this, m_renderer, m_allocator); } egal::Resource* EntityManager::createResource() { return _aligned_new(m_allocator, Entity)(ArchivePath(""), *this, m_renderer, m_allocator); } e_void EntityManager::destroyResource(Resource& resource) { _delete(m_allocator, static_cast<Entity*>(&resource)); } static float3 getBonePosition(Entity* Entity, e_int32 bone_index) { return Entity->getBone(bone_index).transform.pos; } static e_int32 getBoneParent(Entity* Entity, e_int32 bone_index) { return Entity->getBone(bone_index).parent_idx; } }
26.230392
124
0.635676
Pength-TH
3876a3b72e6d055e3bf97fa59eb87394933a20d9
587
cpp
C++
2threads-2.cpp
CMPT-431-SFU/Cpp11-Demos
56ed14c5eb9e355edf7a387943492f50c3d591ec
[ "MIT" ]
null
null
null
2threads-2.cpp
CMPT-431-SFU/Cpp11-Demos
56ed14c5eb9e355edf7a387943492f50c3d591ec
[ "MIT" ]
null
null
null
2threads-2.cpp
CMPT-431-SFU/Cpp11-Demos
56ed14c5eb9e355edf7a387943492f50c3d591ec
[ "MIT" ]
null
null
null
/* * * Same as 2threads.cpp, but using a single function * with parameters, as opposed to two functions. * Additionally, the thread function sleeps for * a number of milliseconds after printing the * string. * */ #include <thread> #include <iostream> #include <chrono> using namespace std; void print_string(const char *s, int sleepms) { while(1) { cout << s << endl; this_thread::sleep_for(chrono::milliseconds(sleepms)); } } int main(int argc, char* argv[]) { thread t1(print_string, "0", 1); thread t2(print_string, "1", 2); t1.join(); t2.join(); return 0; }
16.771429
56
0.67632
CMPT-431-SFU
3876eb274ff09efbe92e4033a4762be132ae367d
7,014
hpp
C++
include/crypto-exchange-client-core/client.hpp
drozhkov/crypto-exchange-client-core
68ce28bfcc1859b2207cf50ff78ba3300d48d44d
[ "MIT" ]
null
null
null
include/crypto-exchange-client-core/client.hpp
drozhkov/crypto-exchange-client-core
68ce28bfcc1859b2207cf50ff78ba3300d48d44d
[ "MIT" ]
null
null
null
include/crypto-exchange-client-core/client.hpp
drozhkov/crypto-exchange-client-core
68ce28bfcc1859b2207cf50ff78ba3300d48d44d
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2022 Denis Rozhkov <denis@rozhkoff.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /// client.hpp /// /// 0.0 - created (Denis Rozhkov <denis@rozhkoff.com>) /// #ifndef __CRYPTO_EXCHANGE_CLIENT_CORE__CLIENT__H #define __CRYPTO_EXCHANGE_CLIENT_CORE__CLIENT__H #include <functional> #include <vector> #include <memory> #include <unordered_map> #include "core.hpp" #include "wsClient.hpp" #include "httpClient.hpp" namespace as::cryptox { class Client; struct t_price_book_ticker; struct t_order_update; enum class Coin { _undef, A_UNKNOWN, A_ANY, A_ALL, BTC, USDT, ETH, KCS, TRX }; enum class Symbol : size_t { _undef, A_UNKNOWN = 1024, A_ANY, A_ALL }; enum class Direction { _undef, BUY, SELL }; using t_number = as::FixedNumber; using t_order_id = as::t_string; using t_exchangeClientReadyHandler = std::function<void( Client & )>; using t_exchangeClientErrorHandler = std::function<void( Client & )>; using t_priceBookTickerHandler = std::function<void( Client &, t_price_book_ticker & )>; using t_orderUpdateHandler = std::function<void( Client &, t_order_update & )>; struct t_price_book_ticker { Symbol symbol; t_number bidPrice; t_number bidQuantity; t_number askPrice; t_number askQuantity; }; struct t_order { t_order_id id; }; struct t_order_update { t_order_id orderId; }; class Pair { protected: Coin m_base; Coin m_quote; as::t_string m_name; public: Pair() { } Pair( Coin base, Coin quote, const as::t_string & name ) : m_base( base ) , m_quote( quote ) , m_name( name ) { } Coin Base() const { return m_base; } Coin Quote() const { return m_quote; } const as::t_string & Name() const { return m_name; } }; class Client { protected: as::Url m_wsApiUrl; as::Url m_httpApiUrl; HttpsClient m_httpClient; std::unique_ptr<as::WsClient> m_wsClient; t_timespan m_wsTimeoutMs{ 0 }; t_exchangeClientReadyHandler m_clientReadyHandler; t_exchangeClientErrorHandler m_clientErrorHandler; std::unordered_map<Symbol, t_priceBookTickerHandler> m_priceBookTickerHandlerMap; t_orderUpdateHandler m_orderUpdateHandler; std::unordered_map<as::t_stringview, Coin> m_coinMap; std::unordered_map<Coin, as::t_stringview> m_coinReverseMap; std::unordered_map<as::t_stringview, Symbol> m_symbolMap; std::vector<Pair> m_pairList; protected: virtual void wsErrorHandler( as::WsClient &, int, const as::t_string & ) = 0; virtual void wsHandshakeHandler( as::WsClient & ) = 0; virtual bool wsReadHandler( as::WsClient &, const char *, size_t ) = 0; void addSymbolMapEntry( const as::t_stringview & name, as::cryptox::Symbol s ) { m_symbolMap.emplace( name, s ); } void addCoinMapEntry( const as::t_stringview & name, as::cryptox::Coin c ) { m_coinMap.emplace( name, c ); m_coinReverseMap.emplace( c, name ); } virtual void initCoinMap() { addCoinMapEntry( AS_T( "UNKNOWN" ), Coin::A_UNKNOWN ); addCoinMapEntry( AS_T( "BTC" ), Coin::BTC ); addCoinMapEntry( AS_T( "ETH" ), Coin::ETH ); addCoinMapEntry( AS_T( "KCS" ), Coin::KCS ); addCoinMapEntry( AS_T( "TRX" ), Coin::TRX ); addCoinMapEntry( AS_T( "USDT" ), Coin::USDT ); } virtual void initSymbolMap(); virtual void initWsClient(); template <typename TMap, typename TArg> void callSymbolHandler( as::cryptox::Symbol symbol, TMap & map, TArg & arg ) { auto it = map.find( symbol ); if ( map.end() == it ) { it = map.find( Symbol::A_ANY ); } if ( map.end() != it ) { it->second( *this, arg ); } } public: Client( const as::t_string & httpApiUrl, const as::t_string & wsApiUrl ) : m_httpApiUrl( httpApiUrl ) , m_wsApiUrl( wsApiUrl ) { } virtual ~Client() = default; template <typename T> static t_timespan UnixTs() { return std::chrono::duration_cast<T>( std::chrono::system_clock::now().time_since_epoch() ) .count(); } virtual void run( const t_exchangeClientReadyHandler & handler ) { initCoinMap(); initSymbolMap(); m_clientReadyHandler = handler; } virtual void subscribePriceBookTicker( Symbol symbol, const t_priceBookTickerHandler & handler ) { if ( Symbol::A_ALL == symbol ) { symbol = Symbol::A_ANY; } m_priceBookTickerHandlerMap.emplace( symbol, handler ); } virtual void subscribeOrderUpdate( const t_orderUpdateHandler & handler ) { m_orderUpdateHandler = handler; } virtual t_order placeOrder( Direction direction, Symbol symbol, const FixedNumber & price, const FixedNumber & quantity ) = 0; virtual const as::t_char * SymbolName( Symbol symbol ) const { return Pair( symbol ).Name().c_str(); } virtual Symbol Symbol( const as::t_char * symbolName ) const { auto it = m_symbolMap.find( symbolName ); if ( m_symbolMap.end() != it ) { return it->second; } return Symbol::A_UNKNOWN; } virtual const as::t_char * CoinName( Coin coin ) const { auto it = m_coinReverseMap.find( coin ); if ( m_coinReverseMap.end() != it ) { return it->second.data(); } return CoinName( Coin::A_UNKNOWN ); } virtual Coin Coin( const as::t_char * coinName ) const { auto it = m_coinMap.find( coinName ); if ( m_coinMap.end() != it ) { return it->second; } return Coin::A_UNKNOWN; } virtual const Pair & Pair( as::cryptox::Symbol symbol ) const { if ( symbol >= as::cryptox::Symbol::A_UNKNOWN ) { symbol = as::cryptox::Symbol::_undef; } return m_pairList[static_cast<size_t>( symbol )]; } virtual const as::t_char * DirectionName( Direction direction ) const { switch ( direction ) { case Direction::BUY: return AS_T( "buy" ); case Direction::SELL: return AS_T( "sell" ); } return AS_T( "UNKNOWN" ); } Client & ErrorHandler( const t_exchangeClientErrorHandler & handler ) { m_clientErrorHandler = handler; return *this; } }; } #endif
21.987461
78
0.68848
drozhkov
387e63387a754586d8e4088ee528c5839b399415
107
cpp
C++
AllClaimsWidget.cpp
congchenutd/Claims
95062b638f9d103d4579677b6ef6886316171448
[ "MIT" ]
null
null
null
AllClaimsWidget.cpp
congchenutd/Claims
95062b638f9d103d4579677b6ef6886316171448
[ "MIT" ]
null
null
null
AllClaimsWidget.cpp
congchenutd/Claims
95062b638f9d103d4579677b6ef6886316171448
[ "MIT" ]
null
null
null
#include "AllClaimsWidget.h" AllClaimsWidget::AllClaimsWidget(QWidget* parent) : QWidget(parent) { }
13.375
49
0.738318
congchenutd
3883a1ef7e86ef83856e85ae0cf960c5402a9452
450
hxx
C++
dust/utils/VectorUtils.hxx
JeneLitsch/Dust
85e3ef191e58b3438501b52f9d72edd8064e5a27
[ "MIT" ]
null
null
null
dust/utils/VectorUtils.hxx
JeneLitsch/Dust
85e3ef191e58b3438501b52f9d72edd8064e5a27
[ "MIT" ]
null
null
null
dust/utils/VectorUtils.hxx
JeneLitsch/Dust
85e3ef191e58b3438501b52f9d72edd8064e5a27
[ "MIT" ]
null
null
null
#pragma once #include "sfml.hxx" #include <cmath> namespace dust { class VectorUtils { public: static inline sf::Vector2f toVector(float angle) { constexpr const float degToRad = float(M_PI) / 180.f; const float radianAngle = (angle - 90.f) * degToRad; return sf::Vector2f(std::cos(radianAngle), std::sin(radianAngle)); } static inline sf::Vector2f deg90(sf::Vector2f vector) { return sf::Vector2f(vector.y, -vector.x); } }; }
26.470588
69
0.691111
JeneLitsch
3886881963165acb069fa7ca169f175524dbf44b
2,700
cpp
C++
d2dcustomeffects/cpp/computeshader/customcomputeshadermain.cpp
kaid7pro/old-Windows-universal-samples
f97d2b880420fff7bcf7ea0aaf20ee837c002d7d
[ "MIT" ]
6
2015-12-23T22:28:56.000Z
2021-11-06T17:05:51.000Z
d2dcustomeffects/cpp/computeshader/customcomputeshadermain.cpp
y3key/Windows-universal-samples
f97d2b880420fff7bcf7ea0aaf20ee837c002d7d
[ "MIT" ]
null
null
null
d2dcustomeffects/cpp/computeshader/customcomputeshadermain.cpp
y3key/Windows-universal-samples
f97d2b880420fff7bcf7ea0aaf20ee837c002d7d
[ "MIT" ]
8
2015-10-26T01:44:51.000Z
2022-03-12T09:47:56.000Z
#include "pch.h" #include "CustomComputeShaderMain.h" #include "DirectXHelper.h" using namespace CustomComputeShader; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::System::Threading; using namespace Windows::UI::Core; using namespace Concurrency; // Loads and initializes application assets when the application is loaded. CustomComputeShaderMain::CustomComputeShaderMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) : m_deviceResources(deviceResources) { // Register to be notified if the Device is lost or recreated. m_deviceResources->RegisterDeviceNotify(this); m_sceneRenderer = std::unique_ptr<CustomComputeShaderRenderer>(new CustomComputeShaderRenderer(m_deviceResources)); m_sampleOverlay = std::unique_ptr<SampleOverlay>(new SampleOverlay(m_deviceResources, L"Direct2D Custom Compute Shader Effect")); } CustomComputeShaderMain::~CustomComputeShaderMain() { // Deregister device notification. m_deviceResources->RegisterDeviceNotify(nullptr); } // Updates application state when the window size changes (e.g. device orientation change) void CustomComputeShaderMain::CreateWindowSizeDependentResources() { m_sceneRenderer->CreateWindowSizeDependentResources(); m_sampleOverlay->CreateWindowSizeDependentResources(); } void CustomComputeShaderMain::Update() { // Unlike the pixel and vertex shader effects, the compute shader effect does not animate over time. // Therefore, render state is only updated on events such as CreateWindowSizeDependentResources(). } // Renders the current frame according to the current application state. // Returns true if the frame was rendered and is ready to be displayed. bool CustomComputeShaderMain::Render() { m_sceneRenderer->Render(); m_sampleOverlay->Render(); return true; } // Notifies renderers that device resources need to be released. void CustomComputeShaderMain::OnDeviceLost() { m_sceneRenderer->ReleaseDeviceDependentResources(); m_sampleOverlay->ReleaseDeviceDependentResources(); } // Notifies renderers that device resources may now be recreated. void CustomComputeShaderMain::OnDeviceRestored() { m_sceneRenderer->CreateDeviceDependentResources(); m_sampleOverlay->CreateDeviceDependentResources(); CreateWindowSizeDependentResources(); } void CustomComputeShaderMain::SaveInternalState(_In_ IPropertySet ^ state) { m_sceneRenderer->SaveInternalState(state); } void CustomComputeShaderMain::LoadInternalState(_In_ IPropertySet ^ state) { m_sceneRenderer->LoadInternalState(state); }
35.526316
134
0.775926
kaid7pro
388e58af48d64a27ad4f8dfbe352ef77dd0ade37
3,731
cpp
C++
igl/voxel_grid.cpp
aviadtzemah/animation2
9a3f980fbe27672fe71f8f61f73b5713f2af5089
[ "Apache-2.0" ]
2,392
2016-12-17T14:14:12.000Z
2022-03-30T19:40:40.000Z
igl/voxel_grid.cpp
aviadtzemah/animation2
9a3f980fbe27672fe71f8f61f73b5713f2af5089
[ "Apache-2.0" ]
106
2018-04-19T17:47:31.000Z
2022-03-01T19:44:11.000Z
igl/voxel_grid.cpp
aviadtzemah/animation2
9a3f980fbe27672fe71f8f61f73b5713f2af5089
[ "Apache-2.0" ]
184
2017-11-15T09:55:37.000Z
2022-02-21T16:30:46.000Z
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2016 Alec Jacobson <alecjacobson@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "voxel_grid.h" #include "grid.h" template < typename Scalar, typename DerivedGV, typename Derivedside> IGL_INLINE void igl::voxel_grid( const Eigen::AlignedBox<Scalar,3> & box, const int in_s, const int pad_count, Eigen::PlainObjectBase<DerivedGV> & GV, Eigen::PlainObjectBase<Derivedside> & side) { using namespace Eigen; using namespace std; typename DerivedGV::Index si = -1; box.diagonal().maxCoeff(&si); //DerivedGV::Index si = 0; //assert(si>=0); const Scalar s_len = box.diagonal()(si); assert(in_s>(pad_count*2+1) && "s should be > 2*pad_count+1"); const Scalar s = in_s - 2*pad_count; side(si) = s; for(int i = 0;i<3;i++) { if(i!=si) { side(i) = std::ceil(s * (box.max()(i)-box.min()(i))/s_len); } } side.array() += 2*pad_count; grid(side,GV); // A * p/s + B = min // A * (1-p/s) + B = max // B = min - A * p/s // A * (1-p/s) + min - A * p/s = max // A * (1-p/s) - A * p/s = max-min // A * (1-2p/s) = max-min // A = (max-min)/(1-2p/s) const Array<Scalar,3,1> ps= (Scalar)(pad_count)/(side.transpose().template cast<Scalar>().array()-1.); const Array<Scalar,3,1> A = box.diagonal().array()/(1.0-2.*ps); //// This would result in an "anamorphic", but perfectly fit grid: //const Array<Scalar,3,1> B = box.min().array() - A.array()*ps; //GV.array().rowwise() *= A.transpose(); //GV.array().rowwise() += B.transpose(); // Instead scale by largest factor and move to match center typename Array<Scalar,3,1>::Index ai = -1; Scalar a = A.maxCoeff(&ai); const Array<Scalar,1,3> ratio = a*(side.template cast<Scalar>().array()-1.0)/(Scalar)(side(ai)-1.0); GV.array().rowwise() *= ratio; const Eigen::Matrix<Scalar,1,3> offset = (box.center().transpose()-GV.colwise().mean()).eval(); GV.rowwise() += offset; } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation // generated by autoexplicit.sh template void igl::voxel_grid<float, Eigen::Matrix<float, -1, -1, 0, -1, -1>, Eigen::Matrix<int, 1, 3, 1, 1, 3> >(Eigen::AlignedBox<float, 3> const&, int, int, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, 1, 3, 1, 1, 3> >&); template void igl::voxel_grid<float, Eigen::Matrix<float, -1, 3, 0, -1, 3>, Eigen::Matrix<int, 3, 1, 0, 3, 1> >(Eigen::AlignedBox<float, 3> const&, int, int, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, 3, 1, 0, 3, 1> >&); template void igl::voxel_grid<float, Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<int, 3, 1, 0, 3, 1> >(Eigen::AlignedBox<float, 3> const&, int, int, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, 3, 1, 0, 3, 1> >&); template void igl::voxel_grid<double, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, 3, 1, 0, 3, 1> >(Eigen::AlignedBox<double, 3> const&, int, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, 3, 1, 0, 3, 1> >&); template void igl::voxel_grid<double, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, 1, 3, 1, 1, 3> >(Eigen::AlignedBox<double, 3> const&, int, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, 1, 3, 1, 1, 3> >&); #endif
50.418919
292
0.629858
aviadtzemah
38952944364388f20e660e778b35b37f5348a3db
1,851
cpp
C++
src/AutoTests/Tests/CollidingCircularUnits/Systems/TestCircularUnitsSystem.cpp
gameraccoon/HideAndSeek
bc1e9c8dd725968ad4bc204877d8ddca2132ace7
[ "MIT" ]
null
null
null
src/AutoTests/Tests/CollidingCircularUnits/Systems/TestCircularUnitsSystem.cpp
gameraccoon/HideAndSeek
bc1e9c8dd725968ad4bc204877d8ddca2132ace7
[ "MIT" ]
null
null
null
src/AutoTests/Tests/CollidingCircularUnits/Systems/TestCircularUnitsSystem.cpp
gameraccoon/HideAndSeek
bc1e9c8dd725968ad4bc204877d8ddca2132ace7
[ "MIT" ]
null
null
null
#include "Base/precomp.h" #include "AutoTests/Tests/CollidingCircularUnits/Systems/TestCircularUnitsSystem.h" #include "GameData/Components/AiControllerComponent.generated.h" #include "GameData/Components/CollisionComponent.generated.h" #include "GameData/Components/MovementComponent.generated.h" #include "GameData/Components/NavMeshComponent.generated.h" #include "GameData/Components/TimeComponent.generated.h" #include "GameData/Components/TransformComponent.generated.h" #include "GameData/World.h" #include "GameLogic/SharedManagers/WorldHolder.h" TestCircularUnitsSystem::TestCircularUnitsSystem(WorldHolder& worldHolder) noexcept : mWorldHolder(worldHolder) { } void TestCircularUnitsSystem::update() { World& world = mWorldHolder.getWorld(); const auto [time] = world.getWorldComponents().getComponents<TimeComponent>(); const float dt = time->getValue().lastFixedUpdateDt; std::optional<std::pair<EntityView, CellPos>> playerEntity = world.getTrackedSpatialEntity(STR_TO_ID("ControlledEntity")); if (!playerEntity.has_value()) { return; } const auto [playerTransform] = playerEntity->first.getComponents<const TransformComponent>(); if (playerTransform == nullptr) { return; } Vector2D targetLocation = playerTransform->getLocation(); SpatialEntityManager spatialManager = world.getSpatialData().getAllCellManagers(); spatialManager.forEachComponentSet<const AiControllerComponent, const TransformComponent, MovementComponent>( [targetLocation, dt](const AiControllerComponent* /*aiController*/, const TransformComponent* transform, MovementComponent* movement) { Vector2D nextStep = targetLocation - transform->getLocation(); movement->setMoveDirection(nextStep); movement->setNextStep(nextStep * movement->getOriginalSpeed() * dt); movement->setSpeed(movement->getOriginalSpeed()); } ); }
34.924528
135
0.796326
gameraccoon
3897a28381761090b8382cb9686ee7adad0380d9
1,336
cpp
C++
Rozwiazania-zadan/10_Seria-X/points.cpp
bzglinicki/Programowanie-metody-numeryczne
3b22a5b6da24699b989b85b757f5e66f8fafd537
[ "MIT" ]
null
null
null
Rozwiazania-zadan/10_Seria-X/points.cpp
bzglinicki/Programowanie-metody-numeryczne
3b22a5b6da24699b989b85b757f5e66f8fafd537
[ "MIT" ]
null
null
null
Rozwiazania-zadan/10_Seria-X/points.cpp
bzglinicki/Programowanie-metody-numeryczne
3b22a5b6da24699b989b85b757f5e66f8fafd537
[ "MIT" ]
null
null
null
#include <algorithm> #include <chrono> #include <iostream> #include <numeric> #include <random> #include <vector> struct Point { double x; double y; double z; int id; }; template <class Rng> Point pointFactory(Rng &rng, int id) { std::uniform_real_distribution<> up(0, 2 * M_PI); std::uniform_real_distribution<> ut(-1, 1); double phi = up(rng); double theta = acos(ut(rng)); double x = sin(theta) * cos(phi); double y = sin(theta) * sin(phi); double z = cos(theta); return Point{x, y, z, id}; } Point meanPoint(std::vector<Point> &v) { Point p{0, 0, 0, 0}; auto p2 = std::accumulate(v.begin(), v.end(), p, [](Point x, Point i) { x.x += i.x; x.y += i.y; x.z += i.z; x.id += i.id; return x; }); p2.x /= v.size(); p2.y /= v.size(); p2.z /= v.size(); return p2; } int main() { auto seed = std::chrono ::steady_clock ::now().time_since_epoch().count(); std::default_random_engine rng(seed); // przykladowe inicjalizacje struktury Point p{0.1, 0.2, 0.3, 1}; Point p2 = {0.5, 0.6, 0.7, 2}; Point p3; // dostep do pol p3.x = 0.9; p3.y = 1; p3.z = 1.1; p3.id = 3; std::vector<Point> v(1000); for (int i = 0; i < v.size(); ++i) { v.at(i) = pointFactory(rng, i); } auto m = meanPoint(v); std::cout << m.x << " " << m.y << " " << m.z << std::endl; }
22.644068
76
0.56512
bzglinicki
3897fa81a217c1a8520b1aebbdef095e86966cbe
6,581
cpp
C++
bfvmm/tests/debug/serial/test_serial_ns16550a.cpp
chp-io/hypervisor
7c1dce35e9e54601de1c4655565fde803ab446f0
[ "MIT" ]
5
2020-03-28T18:31:24.000Z
2022-03-16T07:51:29.000Z
bfvmm/tests/debug/serial/test_serial_ns16550a.cpp
chp-io/hypervisor
7c1dce35e9e54601de1c4655565fde803ab446f0
[ "MIT" ]
7
2017-11-07T00:25:25.000Z
2018-02-14T18:37:18.000Z
bfvmm/tests/debug/serial/test_serial_ns16550a.cpp
chp-io/hypervisor
7c1dce35e9e54601de1c4655565fde803ab446f0
[ "MIT" ]
2
2020-05-21T22:57:04.000Z
2020-06-17T15:04:38.000Z
// // Copyright (C) 2019 Assured Information Security, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <catch/catch.hpp> #include <map> #include <bfgsl.h> #include <debug/serial/serial_ns16550a.h> using namespace bfvmm; static std::map<uint16_t, uint8_t> g_ports; extern "C" uint8_t _inb(uint16_t port) noexcept { return gsl::narrow_cast<uint8_t>(g_ports[port]); } extern "C" void _outb(uint16_t port, uint8_t val) noexcept { g_ports[port] = val; } extern "C" uint32_t _ind(uint16_t port) noexcept { return g_ports[port]; } extern "C" void _outd(uint16_t port, uint32_t val) noexcept { g_ports[port] = gsl::narrow_cast<uint8_t>(val); } TEST_CASE("serial: support") { CHECK_NOTHROW(_inb(0)); CHECK_NOTHROW(_outb(0, 0)); CHECK_NOTHROW(_ind(0)); CHECK_NOTHROW(_outd(0, 0)); } TEST_CASE("serial: constructor_null_intrinsics") { CHECK_NOTHROW(std::make_unique<serial_ns16550a>()); } TEST_CASE("serial: success") { CHECK(serial_ns16550a::instance()->baud_rate() == serial_ns16550a::DEFAULT_BAUD_RATE); CHECK(serial_ns16550a::instance()->data_bits() == serial_ns16550a::DEFAULT_DATA_BITS); CHECK(serial_ns16550a::instance()->stop_bits() == serial_ns16550a::DEFAULT_STOP_BITS); CHECK(serial_ns16550a::instance()->parity_bits() == serial_ns16550a::DEFAULT_PARITY_BITS); } TEST_CASE("serial: set_baud_rate_success") { auto serial = std::make_unique<serial_ns16550a>(); serial->set_baud_rate(serial_ns16550a::baud_rate_50); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_50); serial->set_baud_rate(serial_ns16550a::baud_rate_75); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_75); serial->set_baud_rate(serial_ns16550a::baud_rate_110); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_110); serial->set_baud_rate(serial_ns16550a::baud_rate_150); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_150); serial->set_baud_rate(serial_ns16550a::baud_rate_300); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_300); serial->set_baud_rate(serial_ns16550a::baud_rate_600); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_600); serial->set_baud_rate(serial_ns16550a::baud_rate_1200); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_1200); serial->set_baud_rate(serial_ns16550a::baud_rate_1800); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_1800); serial->set_baud_rate(serial_ns16550a::baud_rate_2000); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_2000); serial->set_baud_rate(serial_ns16550a::baud_rate_2400); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_2400); serial->set_baud_rate(serial_ns16550a::baud_rate_3600); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_3600); serial->set_baud_rate(serial_ns16550a::baud_rate_4800); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_4800); serial->set_baud_rate(serial_ns16550a::baud_rate_7200); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_7200); serial->set_baud_rate(serial_ns16550a::baud_rate_9600); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_9600); serial->set_baud_rate(serial_ns16550a::baud_rate_19200); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_19200); serial->set_baud_rate(serial_ns16550a::baud_rate_38400); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_38400); serial->set_baud_rate(serial_ns16550a::baud_rate_57600); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_57600); serial->set_baud_rate(serial_ns16550a::baud_rate_115200); CHECK(serial->baud_rate() == serial_ns16550a::baud_rate_115200); } TEST_CASE("serial: set_data_bits_success") { auto serial = std::make_unique<serial_ns16550a>(); serial->set_data_bits(serial_ns16550a::char_length_5); CHECK(serial->data_bits() == serial_ns16550a::char_length_5); serial->set_data_bits(serial_ns16550a::char_length_6); CHECK(serial->data_bits() == serial_ns16550a::char_length_6); serial->set_data_bits(serial_ns16550a::char_length_7); CHECK(serial->data_bits() == serial_ns16550a::char_length_7); serial->set_data_bits(serial_ns16550a::char_length_8); CHECK(serial->data_bits() == serial_ns16550a::char_length_8); } TEST_CASE("serial: set_stop_bits_success") { auto serial = std::make_unique<serial_ns16550a>(); serial->set_stop_bits(serial_ns16550a::stop_bits_1); CHECK(serial->stop_bits() == serial_ns16550a::stop_bits_1); serial->set_stop_bits(serial_ns16550a::stop_bits_2); CHECK(serial->stop_bits() == serial_ns16550a::stop_bits_2); } TEST_CASE("serial: set_parity_bits_success") { auto serial = std::make_unique<serial_ns16550a>(); serial->set_parity_bits(serial_ns16550a::parity_none); CHECK(serial->parity_bits() == serial_ns16550a::parity_none); serial->set_parity_bits(serial_ns16550a::parity_odd); CHECK(serial->parity_bits() == serial_ns16550a::parity_odd); serial->set_parity_bits(serial_ns16550a::parity_even); CHECK(serial->parity_bits() == serial_ns16550a::parity_even); serial->set_parity_bits(serial_ns16550a::parity_mark); CHECK(serial->parity_bits() == serial_ns16550a::parity_mark); serial->set_parity_bits(serial_ns16550a::parity_space); CHECK(serial->parity_bits() == serial_ns16550a::parity_space); } TEST_CASE("serial: write character") { g_ports[DEFAULT_COM_PORT + 5] = 0xFF; auto serial = std::make_unique<serial_ns16550a>(); serial->write('c'); }
41.389937
94
0.751254
chp-io
389cfe5d9eee79551c1a92e3dee40be7e534451c
3,834
hpp
C++
include/Client.hpp
nachooya/mdnscpp
168d20a73c363545fd59a95611d85a05d6f99d67
[ "MIT" ]
null
null
null
include/Client.hpp
nachooya/mdnscpp
168d20a73c363545fd59a95611d85a05d6f99d67
[ "MIT" ]
null
null
null
include/Client.hpp
nachooya/mdnscpp
168d20a73c363545fd59a95611d85a05d6f99d67
[ "MIT" ]
null
null
null
#ifndef __MDNS_CLIENT_HPP__ #define __MDNS_CLIENT_HPP__ #include <functional> #include <list> #include <map> #include <utility> #include <time.h> #include <uv.h> #include "Logger.hpp" #include "DnsPacket.hpp" namespace MDns { class Client: public std::enable_shared_from_this<Client> { public: typedef enum { NET_IFACES_LOOPBACK = 0x01, // 0000 0001 NET_IFACES_POINTOPOINT = 0x02, // 0000 0010 NET_IFACES_DEFAULT = 0x04, // 0000 0100 NET_IFACES_ALL = 0x07, // 0000 0111 } NetworkInterfaceFilter; typedef std::function<void( bool error, const std::string& name, const std::string& ipAddress )> CallbackA; static std::shared_ptr<Client> New ( uv_loop_t* loop, NetworkInterfaceFilter filter = NET_IFACES_DEFAULT); ~Client (); std::string getLocalDomain(); void announceA ( uint32_t ttl = DEFAULT_TTL); void announceAAAA ( uint32_t ttl = DEFAULT_TTL); void queryA ( const std::string& name, std::shared_ptr<CallbackA> callback, uint32_t timeoutMsecs); private: friend class NhLookup; typedef struct { std::string name; uint32_t sa_family; std::string ipAddress; } networkInterface_t; typedef struct { Client* mdns; std::weak_ptr<CallbackA> callbackWeak; std::unique_ptr<uv_timer_t> uvTimerHandler = std::make_unique<uv_timer_t>(); std::string name; uint32_t timeoutMsecs; } queryHandler_t; static const int32_t DEFAULT_TTL = 120; static std::shared_ptr<Logger> LOG; //NOTE: recordName -> list of query Handlers typedef std::map< std::string, std::list<std::shared_ptr<queryHandler_t>> > recordCallbacks_t; uv_loop_t* _loop = nullptr; std::string _uuid; std::map<uv_udp_t*, networkInterface_t> _udpHandleToInterface; std::map<std::string, uv_udp_t*> _ifaceToUdpHandleIpv4; std::map<std::string, uv_udp_t*> _ifaceToUdpHandleIpv6; //NOTE: value is <expiration(ttl), IPv4> std::map<std::string, std::pair<time_t, std::string>> _recordsA; recordCallbacks_t _recordsACallbacks; //NOTE: value is <expiration(ttl), IPv6> std::map<std::string, std::pair<time_t, std::string>> _recordsAAAA; recordCallbacks_t _recordsAAAACallbacks; Client ( uv_loop_t* loop, NetworkInterfaceFilter filter); static void libuvAllocCallback ( uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf); static void libuvHandleUdpDatagram ( uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned flags); static void libuvTimeoutHandlerForQueries ( uv_timer_t* handle); std::shared_ptr<std::list<networkInterface_t>> getNetworkInterfaces ( NetworkInterfaceFilter filter); void handleUdpDatagram ( uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned flags); uv_udp_t* socketOpenIpv4 ( const std::string& ifname); uv_udp_t* socketOpenIpv6 ( const std::string& ifname); void notify ( DnsPacket::record_type_t type, const std::string& name, const std::string& ipv4); int sendPacket ( uv_udp_t* uv_udp, std::shared_ptr<std::vector<uint8_t>> packet); void sendResponseA ( uv_udp_t* handleFrom, uint32_t ttl); void sendResponseAAAA ( uv_udp_t* handleFrom, uint32_t ttl); void printCache (); }; } #endif
25.390728
84
0.617632
nachooya
38a2930dafb309d27511800b51d63ad1913e88a7
949
hpp
C++
include/argot/gen/not.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
49
2018-05-09T23:17:45.000Z
2021-07-21T10:05:19.000Z
include/argot/gen/not.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
null
null
null
include/argot/gen/not.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
2
2019-08-04T03:51:36.000Z
2020-12-28T06:53:29.000Z
/*============================================================================== Copyright (c) 2017, 2018 Matt Calabrese Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef ARGOT_GEN_NOT_HPP_ #define ARGOT_GEN_NOT_HPP_ #include <argot/gen/explicit_concept.hpp> #include <argot/gen/is_modeled.hpp> #include <argot/gen/make_concept_map.hpp> #ifndef ARGOT_GENERATE_PREPROCESSED_CONCEPTS #include <argot/detail/detection.hpp> #endif // ARGOT_GENERATE_PREPROCESSED_CONCEPTS namespace argot { template< class ConceptSpec > ARGOT_EXPLICIT_CONCEPT( Not ) ( ); template< class ConceptSpec > struct make_concept_map < Not< ConceptSpec > , call_detail::fast_enable_if_t< !is_modeled_v< ConceptSpec > > >{}; } // namespace argot #endif // ARGOT_GEN_NOT_HPP_
25.648649
80
0.649104
mattcalabrese
38a3118051f978dbce5cc9a61f04ac62b99c33b2
635
cpp
C++
UUT/Core/Math/Random.cpp
kolyden/uut-engine
aa8e5a42c350aceecee668941e06ac626aac6c52
[ "MIT" ]
null
null
null
UUT/Core/Math/Random.cpp
kolyden/uut-engine
aa8e5a42c350aceecee668941e06ac626aac6c52
[ "MIT" ]
null
null
null
UUT/Core/Math/Random.cpp
kolyden/uut-engine
aa8e5a42c350aceecee668941e06ac626aac6c52
[ "MIT" ]
null
null
null
#include "Random.h" #include <random> #include <chrono> namespace uut { static unsigned g_seed = (unsigned)std::chrono::system_clock::now().time_since_epoch().count(); static std::mt19937 g_generator(g_seed); void Random::SetSeed(unsigned seed) { g_seed = seed; g_generator.seed(g_seed); } unsigned Random::GetSeed() { return g_seed; } float Random::Value() { return float(g_generator()) / g_generator.max(); } float Random::Range(float min, float max) { return Value() * (max - min) + min; } int Random::Range(int min, int max) { return g_generator() % (max - min + 1) + min - g_generator.min(); } }
18.142857
96
0.664567
kolyden
38a492409232f15bd0d0a360ad8dca92241a0691
151
cpp
C++
lib/objgfx/vWidget.cpp
cwolsen7905/UbixOS
2f6063103347a8e8c369aacdd1399911bb4a4776
[ "BSD-3-Clause" ]
null
null
null
lib/objgfx/vWidget.cpp
cwolsen7905/UbixOS
2f6063103347a8e8c369aacdd1399911bb4a4776
[ "BSD-3-Clause" ]
null
null
null
lib/objgfx/vWidget.cpp
cwolsen7905/UbixOS
2f6063103347a8e8c369aacdd1399911bb4a4776
[ "BSD-3-Clause" ]
null
null
null
#include "vWidget.h" bool vWidget::vSetActive(bool _active) { bool result = active; active = _active; return result; } // vWidget::vSetActive
15.1
35
0.695364
cwolsen7905
38a86b3c56ac5198c31708c40cfea807a6d9e7f4
10,483
cpp
C++
src/algebra/MatrixOperator.cpp
btbujiangjun/abcdl
cea8568517894d153ee3647eec899b93f34877b4
[ "Apache-2.0" ]
2
2017-09-19T08:26:48.000Z
2018-11-16T12:49:53.000Z
src/algebra/MatrixOperator.cpp
btbujiangjun/abcdl
cea8568517894d153ee3647eec899b93f34877b4
[ "Apache-2.0" ]
null
null
null
src/algebra/MatrixOperator.cpp
btbujiangjun/abcdl
cea8568517894d153ee3647eec899b93f34877b4
[ "Apache-2.0" ]
null
null
null
/*********************************************** * Author: Jun Jiang - jiangjun4@sina.com * Create: 2017-07-26 13:27 * Last modified : 2017-07-26 13:27 * Filename : MatrixOperator.cpp * Description : **********************************************/ #include <string.h> #include "algebra/Matrix.h" namespace abcdl{ namespace algebra{ template<class T> T& Matrix<T>::operator [] (const size_t idx) const{ CHECK(idx < get_size()); return _data[idx]; } template<class T> bool Matrix<T>::operator == (const Matrix<T>& mat) const{ if(this == &mat){ return true; } size_t size = mat.get_size(); if(get_size() != size){ return false; } bool result_value = true; auto lambda = [](bool* a, const T& b, const T& c){*a = (b == c);}; _po.parallel_reduce_boolean(&result_value, _data, get_size(), mat.data(), size, lambda); return result_value; } template<class T> Matrix<T>& Matrix<T>::operator = (const T& value){ reset(value); return *this; } template<class T> Matrix<T>& Matrix<T>::operator = (const Matrix<T>& mat){ if(this != &mat){ size_t size = mat.get_size(); if(get_size() != size){ if(_data != nullptr){ delete[] _data; } _data = new T[size]; } _rows = mat.rows(); _cols = mat.cols(); memcpy(_data, mat.data(), sizeof(T) * size); } return *this; } template<class T> Matrix<T> Matrix<T>::operator + (const T& value) const{ auto new_mat = clone(); if (value != 0){ auto lambda = [](T* a, const T& b){*a += b;}; _po.parallel_mul2one(new_mat.data(), new_mat.get_size(), value, lambda); } return new_mat; } template<class T> Matrix<T> Matrix<T>::operator + (const Matrix<T>& mat) const{ if(get_size() == 0){ return mat.clone(); } CHECK(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1) || (_rows == mat.rows() && mat.cols() == 1)); Matrix<T> new_mat = clone(); if(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1)){ auto lambda = [](T* a, const T& b){*a += b;}; _po.parallel_mul2mul_repeat(new_mat.data(), new_mat.get_size(), mat.data(), mat.get_size(), lambda); }else{ for(size_t i = 0; i < _rows; i++){ T value = mat.get_data(i, 0); for(size_t j = 0; j < _cols; j++){ new_mat.set_data(get_data(i, j) + value, i, j); } } } return new_mat; } template<class T> Matrix<T>& Matrix<T>::operator += (const T& value){ auto lambda = [](T* a, const T& b){*a += b;}; _po.parallel_mul2one(_data, get_size(), value, lambda); return *this; } template<class T> Matrix<T>& Matrix<T>::operator += (const Matrix<T>& mat){ if(get_size() == 0){ set_data(mat); return *this; } CHECK(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1) || (_rows == mat.rows() && mat.cols() == 1)); if(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1)){ auto lambda = [](T* a, const T& b){*a += b;}; _po.parallel_mul2mul_repeat(_data, get_size(), mat.data(), mat.get_size(), lambda); }else{ for(size_t i = 0; i < _rows; i++){ T value = mat.get_data(i, 0); for(size_t j = 0; j < _cols; j++){ set_data(get_data(i, j) + value, i, j); } } } return *this; } template<class T> Matrix<T> Matrix<T>::operator - (const T& value) const{ auto lambda = [](T* a, const T& b){*a -= b;}; auto new_mat = clone(); _po.parallel_mul2one(new_mat.data(), new_mat.get_size(), value, lambda); return new_mat; } template<class T> Matrix<T> Matrix<T>::operator - (const Matrix<T>& mat) const{ CHECK(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1) || (_rows == mat.rows() && mat.cols() == 1)); auto new_mat = clone(); if(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1)){ auto lambda = [](T* a, const T& b){*a -= b;}; _po.parallel_mul2mul_repeat(new_mat.data(), new_mat.get_size(), mat.data(), mat.get_size(), lambda); }else{ for(size_t i = 0; i < _rows; i++){ T value = mat.get_data(i, 0); for(size_t j = 0; j < _cols; j++){ new_mat.set_data(get_data(i, j) - value, i, j); } } } return new_mat; } template<class T> Matrix<T>& Matrix<T>::operator -= (const T& value){ auto lambda = [](T* a, const T& b){*a -= b;}; _po.parallel_mul2one(_data, get_size(), value, lambda); return *this; } template<class T> Matrix<T>& Matrix<T>::operator -= (const Matrix<T>& mat){ CHECK(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1) || (_rows == mat.rows() && mat.cols() == 1)); if(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1)){ auto lambda = [](T* a, const T& b){*a -= b;}; _po.parallel_mul2mul_repeat(_data, get_size(), mat.data(), mat.get_size(), lambda); }else{ for(size_t i = 0; i < _rows; i++){ T value = mat.get_data(i, 0); for(size_t j = 0; j < _cols; j++){ set_data(get_data(i, j) - value, i, j); } } } return *this; } template<class T> Matrix<T> Matrix<T>::operator * (const T& value) const{ auto lambda = [](T* a, const T& b){*a *= b;}; auto new_mat = clone(); _po.parallel_mul2one(new_mat.data(), new_mat.get_size(), value, lambda); return new_mat; } template<class T> Matrix<T> Matrix<T>::operator * (const Matrix<T>& mat) const{ CHECK(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1) || (_rows == mat.rows() && mat.cols() == 1)); auto new_mat = clone(); if(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1)){ auto lambda = [](T* a, const T& b){*a *= b;}; _po.parallel_mul2mul_repeat(new_mat.data(), new_mat.get_size(), mat.data(), mat.get_size(), lambda); }else{ for(size_t i = 0; i < _rows; i++){ T value = mat.get_data(i, 0); for(size_t j = 0; j < _cols; j++){ new_mat.set_data(get_data(i, j) * value, i, j); } } } return new_mat; } template<class T> Matrix<T>& Matrix<T>::operator *= (const T& value){ auto lambda = [](T* a, const T& b){*a *= b;}; _po.parallel_mul2one(_data, get_size(), value, lambda); return *this; } template<class T> Matrix<T>& Matrix<T>::operator *= (const Matrix<T>& mat){ CHECK(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1) || (_rows == mat.rows() && mat.cols() == 1)); if(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1)){ auto lambda = [](T* a, const T& b){*a *= b;}; _po.parallel_mul2mul_repeat(_data, get_size(), mat.data(), mat.get_size(), lambda); }else{ for(size_t i = 0; i < _rows; i++){ T value = mat.get_data(i, 0); for(size_t j = 0; j < _cols; j++){ set_data(get_data(i, j) * value, i, j); } } } return *this; } template<class T> Matrix<T> Matrix<T>::operator / (const T& value) const{ CHECK(value != 0); auto lambda = [](T* a, const T& b){*a /= b;}; auto new_mat = clone(); _po.parallel_mul2one(new_mat.data(), new_mat.get_size(), value, lambda); return new_mat; } template<class T> Matrix<T> Matrix<T>::operator / (const Matrix<T>& mat) const{ CHECK(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1) || (_rows == mat.rows() && mat.cols() == 1)); auto new_mat = clone(); if(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1)){ auto lambda = [](T* a, const T& b){ CHECK(b != 0); *a /= b;}; _po.parallel_mul2mul_repeat(new_mat.data(), new_mat.get_size(), mat.data(), mat.get_size(), lambda); }else{ for(size_t i = 0; i < _rows; i++){ T value = mat.get_data(i, 0); CHECK(value != 0); for(size_t j = 0; j < _cols; j++){ new_mat.set_data(get_data(i, j) / value, i, j); } } } return new_mat; } template<class T> Matrix<T>& Matrix<T>::operator /= (const T& value){ CHECK(value != 0); auto lambda = [](T* a, const T& b){*a /= b;}; _po.parallel_mul2one(_data, get_size(), value, lambda); return *this; } template<class T> Matrix<T>& Matrix<T>::operator /= (const Matrix<T>& mat){ CHECK(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1) || (_rows == mat.rows() && mat.cols() == 1)); if(equal_shape(mat) || (_cols == mat.cols() && mat.rows() == 1)){ auto lambda = [](T* a, const T& b){ CHECK(b != 0); *a /= b;}; _po.parallel_mul2mul_repeat(_data, get_size(), mat.data(), mat.get_size(), lambda); }else{ for(size_t i = 0; i < _rows; i++){ T value = mat.get_data(i, 0); CHECK(value != 0); for(size_t j = 0; j < _cols; j++){ set_data(get_data(i, j) / value, i, j); } } } return *this; } template<class T> Matrix<T>::operator Matrix<int>() const{ Matrix<int> mat(_rows, _cols); size_t size = get_size(); for(size_t i = 0; i < size; i++){ mat.set_data(i, static_cast<int>(get_data(i))); } return mat; } template<class T> Matrix<T>::operator Matrix<float>() const{ Matrix<float> mat(_rows, _cols); size_t size = get_size(); for(size_t i = 0; i < size; i++){ mat.set_data(i, static_cast<float>(get_data(i))); } return mat; } template<class T> Matrix<T>::operator Matrix<double>() const{ Matrix<double> mat(_rows, _cols); size_t size = get_size(); for(size_t i = 0; i < size; i++){ mat.set_data(i, static_cast<double>(get_data(i))); } return mat; } template<class T> Matrix<T>::operator Matrix<size_t>() const{ Matrix<size_t> mat(_rows, _cols); size_t size = get_size(); for(size_t i = 0; i < size; i++){ mat.set_data(i, static_cast<size_t>(get_data(i))); } return mat; } template class Matrix<int>; template class Matrix<float>; template class Matrix<double>; template class Matrix<size_t>; template class RandomMatrix<float>; template class RandomMatrix<double>; template class EyeMatrix<float>; template class EyeMatrix<double>; }//namespace algebra }//namespace abcdl
29.529577
108
0.536392
btbujiangjun
38a8b37112ca6dd5987c9119b8e44f60fff27235
7,944
cpp
C++
aws-cpp-sdk-ec2/source/model/AnalysisRouteTableRoute.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-ec2/source/model/AnalysisRouteTableRoute.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-ec2/source/model/AnalysisRouteTableRoute.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ec2/model/AnalysisRouteTableRoute.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace EC2 { namespace Model { AnalysisRouteTableRoute::AnalysisRouteTableRoute() : m_destinationCidrHasBeenSet(false), m_destinationPrefixListIdHasBeenSet(false), m_egressOnlyInternetGatewayIdHasBeenSet(false), m_gatewayIdHasBeenSet(false), m_instanceIdHasBeenSet(false), m_natGatewayIdHasBeenSet(false), m_networkInterfaceIdHasBeenSet(false), m_originHasBeenSet(false), m_transitGatewayIdHasBeenSet(false), m_vpcPeeringConnectionIdHasBeenSet(false) { } AnalysisRouteTableRoute::AnalysisRouteTableRoute(const XmlNode& xmlNode) : m_destinationCidrHasBeenSet(false), m_destinationPrefixListIdHasBeenSet(false), m_egressOnlyInternetGatewayIdHasBeenSet(false), m_gatewayIdHasBeenSet(false), m_instanceIdHasBeenSet(false), m_natGatewayIdHasBeenSet(false), m_networkInterfaceIdHasBeenSet(false), m_originHasBeenSet(false), m_transitGatewayIdHasBeenSet(false), m_vpcPeeringConnectionIdHasBeenSet(false) { *this = xmlNode; } AnalysisRouteTableRoute& AnalysisRouteTableRoute::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode destinationCidrNode = resultNode.FirstChild("destinationCidr"); if(!destinationCidrNode.IsNull()) { m_destinationCidr = Aws::Utils::Xml::DecodeEscapedXmlText(destinationCidrNode.GetText()); m_destinationCidrHasBeenSet = true; } XmlNode destinationPrefixListIdNode = resultNode.FirstChild("destinationPrefixListId"); if(!destinationPrefixListIdNode.IsNull()) { m_destinationPrefixListId = Aws::Utils::Xml::DecodeEscapedXmlText(destinationPrefixListIdNode.GetText()); m_destinationPrefixListIdHasBeenSet = true; } XmlNode egressOnlyInternetGatewayIdNode = resultNode.FirstChild("egressOnlyInternetGatewayId"); if(!egressOnlyInternetGatewayIdNode.IsNull()) { m_egressOnlyInternetGatewayId = Aws::Utils::Xml::DecodeEscapedXmlText(egressOnlyInternetGatewayIdNode.GetText()); m_egressOnlyInternetGatewayIdHasBeenSet = true; } XmlNode gatewayIdNode = resultNode.FirstChild("gatewayId"); if(!gatewayIdNode.IsNull()) { m_gatewayId = Aws::Utils::Xml::DecodeEscapedXmlText(gatewayIdNode.GetText()); m_gatewayIdHasBeenSet = true; } XmlNode instanceIdNode = resultNode.FirstChild("instanceId"); if(!instanceIdNode.IsNull()) { m_instanceId = Aws::Utils::Xml::DecodeEscapedXmlText(instanceIdNode.GetText()); m_instanceIdHasBeenSet = true; } XmlNode natGatewayIdNode = resultNode.FirstChild("natGatewayId"); if(!natGatewayIdNode.IsNull()) { m_natGatewayId = Aws::Utils::Xml::DecodeEscapedXmlText(natGatewayIdNode.GetText()); m_natGatewayIdHasBeenSet = true; } XmlNode networkInterfaceIdNode = resultNode.FirstChild("networkInterfaceId"); if(!networkInterfaceIdNode.IsNull()) { m_networkInterfaceId = Aws::Utils::Xml::DecodeEscapedXmlText(networkInterfaceIdNode.GetText()); m_networkInterfaceIdHasBeenSet = true; } XmlNode originNode = resultNode.FirstChild("origin"); if(!originNode.IsNull()) { m_origin = Aws::Utils::Xml::DecodeEscapedXmlText(originNode.GetText()); m_originHasBeenSet = true; } XmlNode transitGatewayIdNode = resultNode.FirstChild("transitGatewayId"); if(!transitGatewayIdNode.IsNull()) { m_transitGatewayId = Aws::Utils::Xml::DecodeEscapedXmlText(transitGatewayIdNode.GetText()); m_transitGatewayIdHasBeenSet = true; } XmlNode vpcPeeringConnectionIdNode = resultNode.FirstChild("vpcPeeringConnectionId"); if(!vpcPeeringConnectionIdNode.IsNull()) { m_vpcPeeringConnectionId = Aws::Utils::Xml::DecodeEscapedXmlText(vpcPeeringConnectionIdNode.GetText()); m_vpcPeeringConnectionIdHasBeenSet = true; } } return *this; } void AnalysisRouteTableRoute::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_destinationCidrHasBeenSet) { oStream << location << index << locationValue << ".DestinationCidr=" << StringUtils::URLEncode(m_destinationCidr.c_str()) << "&"; } if(m_destinationPrefixListIdHasBeenSet) { oStream << location << index << locationValue << ".DestinationPrefixListId=" << StringUtils::URLEncode(m_destinationPrefixListId.c_str()) << "&"; } if(m_egressOnlyInternetGatewayIdHasBeenSet) { oStream << location << index << locationValue << ".EgressOnlyInternetGatewayId=" << StringUtils::URLEncode(m_egressOnlyInternetGatewayId.c_str()) << "&"; } if(m_gatewayIdHasBeenSet) { oStream << location << index << locationValue << ".GatewayId=" << StringUtils::URLEncode(m_gatewayId.c_str()) << "&"; } if(m_instanceIdHasBeenSet) { oStream << location << index << locationValue << ".InstanceId=" << StringUtils::URLEncode(m_instanceId.c_str()) << "&"; } if(m_natGatewayIdHasBeenSet) { oStream << location << index << locationValue << ".NatGatewayId=" << StringUtils::URLEncode(m_natGatewayId.c_str()) << "&"; } if(m_networkInterfaceIdHasBeenSet) { oStream << location << index << locationValue << ".NetworkInterfaceId=" << StringUtils::URLEncode(m_networkInterfaceId.c_str()) << "&"; } if(m_originHasBeenSet) { oStream << location << index << locationValue << ".Origin=" << StringUtils::URLEncode(m_origin.c_str()) << "&"; } if(m_transitGatewayIdHasBeenSet) { oStream << location << index << locationValue << ".TransitGatewayId=" << StringUtils::URLEncode(m_transitGatewayId.c_str()) << "&"; } if(m_vpcPeeringConnectionIdHasBeenSet) { oStream << location << index << locationValue << ".VpcPeeringConnectionId=" << StringUtils::URLEncode(m_vpcPeeringConnectionId.c_str()) << "&"; } } void AnalysisRouteTableRoute::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_destinationCidrHasBeenSet) { oStream << location << ".DestinationCidr=" << StringUtils::URLEncode(m_destinationCidr.c_str()) << "&"; } if(m_destinationPrefixListIdHasBeenSet) { oStream << location << ".DestinationPrefixListId=" << StringUtils::URLEncode(m_destinationPrefixListId.c_str()) << "&"; } if(m_egressOnlyInternetGatewayIdHasBeenSet) { oStream << location << ".EgressOnlyInternetGatewayId=" << StringUtils::URLEncode(m_egressOnlyInternetGatewayId.c_str()) << "&"; } if(m_gatewayIdHasBeenSet) { oStream << location << ".GatewayId=" << StringUtils::URLEncode(m_gatewayId.c_str()) << "&"; } if(m_instanceIdHasBeenSet) { oStream << location << ".InstanceId=" << StringUtils::URLEncode(m_instanceId.c_str()) << "&"; } if(m_natGatewayIdHasBeenSet) { oStream << location << ".NatGatewayId=" << StringUtils::URLEncode(m_natGatewayId.c_str()) << "&"; } if(m_networkInterfaceIdHasBeenSet) { oStream << location << ".NetworkInterfaceId=" << StringUtils::URLEncode(m_networkInterfaceId.c_str()) << "&"; } if(m_originHasBeenSet) { oStream << location << ".Origin=" << StringUtils::URLEncode(m_origin.c_str()) << "&"; } if(m_transitGatewayIdHasBeenSet) { oStream << location << ".TransitGatewayId=" << StringUtils::URLEncode(m_transitGatewayId.c_str()) << "&"; } if(m_vpcPeeringConnectionIdHasBeenSet) { oStream << location << ".VpcPeeringConnectionId=" << StringUtils::URLEncode(m_vpcPeeringConnectionId.c_str()) << "&"; } } } // namespace Model } // namespace EC2 } // namespace Aws
35.464286
159
0.717019
perfectrecall
38ab36142614144900493ea0c845c969173c6035
3,467
cxx
C++
GPU/GPUTracking/TPCClusterFinder/ClusterAccumulator.cxx
preghenella/AliRoot
7a1a71f12a47e78e5082253e7a8edf08cd8afff6
[ "BSD-3-Clause" ]
null
null
null
GPU/GPUTracking/TPCClusterFinder/ClusterAccumulator.cxx
preghenella/AliRoot
7a1a71f12a47e78e5082253e7a8edf08cd8afff6
[ "BSD-3-Clause" ]
null
null
null
GPU/GPUTracking/TPCClusterFinder/ClusterAccumulator.cxx
preghenella/AliRoot
7a1a71f12a47e78e5082253e7a8edf08cd8afff6
[ "BSD-3-Clause" ]
null
null
null
//**************************************************************************\ //* This file is property of and copyright by the ALICE Project *\ //* ALICE Experiment at CERN, All rights reserved. *\ //* *\ //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *\ //* for The ALICE HLT Project. *\ //* *\ //* Permission to use, copy, modify and distribute this software and its *\ //* documentation strictly for non-commercial purposes is hereby granted *\ //* without fee, provided that the above copyright notice appears in all *\ //* copies and that both the copyright notice and this permission notice *\ //* appear in the supporting documentation. The authors make no claims *\ //* about the suitability of this software for any purpose. It is *\ //* provided "as is" without express or implied warranty. *\ //************************************************************************** /// \file ClusterAccumulator.cxx /// \author Felix Weiglhofer #include "ClusterAccumulator.h" #include "CfUtils.h" using namespace GPUCA_NAMESPACE::gpu; GPUd() void ClusterAccumulator::toNative(const deprecated::Digit& d, tpc::ClusterNative& cn) const { bool isEdgeCluster = CfUtils::isAtEdge(&d); bool wasSplitInTime = mSplitInTime >= MIN_SPLIT_NUM; bool wasSplitInPad = mSplitInPad >= MIN_SPLIT_NUM; uchar flags = 0; flags |= (isEdgeCluster) ? tpc::ClusterNative::flagEdge : 0; flags |= (wasSplitInTime) ? tpc::ClusterNative::flagSplitTime : 0; flags |= (wasSplitInPad) ? tpc::ClusterNative::flagSplitPad : 0; cn.qMax = d.charge; cn.qTot = mQtot; cn.setTimeFlags(mTimeMean, flags); cn.setPad(mPadMean); cn.setSigmaTime(mTimeSigma); cn.setSigmaPad(mPadSigma); } GPUd() void ClusterAccumulator::update(Charge splitCharge, Delta2 d) { mQtot += splitCharge; mPadMean += splitCharge * d.x; mTimeMean += splitCharge * d.y; mPadSigma += splitCharge * d.x * d.x; mTimeSigma += splitCharge * d.y * d.y; } GPUd() Charge ClusterAccumulator::updateInner(PackedCharge charge, Delta2 d) { Charge q = charge.unpack(); update(q, d); bool split = charge.isSplit(); mSplitInTime += (d.y != 0 && split); mSplitInPad += (d.x != 0 && split); return q; } GPUd() Charge ClusterAccumulator::updateOuter(PackedCharge charge, Delta2 d) { Charge q = charge.unpack(); bool split = charge.isSplit(); bool has3x3 = charge.has3x3Peak(); update((has3x3) ? 0.f : q, d); mSplitInTime += (d.y != 0 && split && !has3x3); mSplitInPad += (d.x != 0 && split && !has3x3); return q; } GPUd() void ClusterAccumulator::finalize(const deprecated::Digit& myDigit) { mQtot += myDigit.charge; if (mQtot == 0) { return; // TODO: Why does this happen? } mPadMean /= mQtot; mTimeMean /= mQtot; mPadSigma /= mQtot; mTimeSigma /= mQtot; mPadSigma = CAMath::Sqrt(mPadSigma - mPadMean * mPadMean); mTimeSigma = CAMath::Sqrt(mTimeSigma - mTimeMean * mTimeMean); mPadMean += myDigit.pad; mTimeMean += myDigit.time; #if defined(CORRECT_EDGE_CLUSTERS) if (CfUtils::isAtEdge(myDigit)) { float s = (myDigit->pad < 2) ? 1.f : -1.f; bool c = s * (mPadMean - myDigit->pad) > 0.f; mPadMean = (c) ? myDigit->pad : mPadMean; } #endif }
32.101852
98
0.599654
preghenella
38ab95d3605a66ed5d24b200eeea33273ea0d6b9
724
cpp
C++
src/Stages/TileMaker.cpp
lucashflores/jogo-tecprog
21b114f21b933247a321e17905338a4f51620d2a
[ "MIT" ]
null
null
null
src/Stages/TileMaker.cpp
lucashflores/jogo-tecprog
21b114f21b933247a321e17905338a4f51620d2a
[ "MIT" ]
null
null
null
src/Stages/TileMaker.cpp
lucashflores/jogo-tecprog
21b114f21b933247a321e17905338a4f51620d2a
[ "MIT" ]
null
null
null
#include "Stages/TileMaker.h" using namespace Stages; TileMaker::TileMaker(int stg, EntityList* pEL): stage(stg) { if (pEL) pEntityList = pEL; } TileMaker::~TileMaker() { pEntityList = NULL; } void TileMaker::makePlatform(Coordinates::Vector<float> initialPos, unsigned int size) { Id::ids tileId = stage == 1? Id::tile1 : Id::tile2; Platform* platform = NULL; platform = new Platform(tileId, initialPos, size, pEntityList); platform = NULL; } void TileMaker::makeWall(Coordinates::Vector<float> initialPos, unsigned int size) { Id::ids tileId = stage == 1? Id::tile1 : Id::tile2; Wall* wall = NULL; wall = new Wall(tileId, initialPos, size, pEntityList); wall = NULL; }
26.814815
88
0.671271
lucashflores
38ac1b6f64851128a96383af27e1cf6130e3e6fd
896
cc
C++
cpp/leetcode/1035.uncrossed-lines.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
3
2021-03-03T13:18:23.000Z
2022-02-09T07:49:24.000Z
cpp/leetcode/1035.uncrossed-lines.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
null
null
null
cpp/leetcode/1035.uncrossed-lines.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
1
2021-03-29T15:21:42.000Z
2021-03-29T15:21:42.000Z
#include <gtest/gtest.h> #include <vector> namespace { class Solution { public: int maxUncrossedLines(const std::vector<int>& nums1, const std::vector<int>& nums2) { int len1 = nums1.size(), len2 = nums2.size(); std::vector<std::vector<int>> dp(len1 + 1, std::vector<int>(len2 + 1)); for (int i = 1; i <= len1; ++i) { for (int j = 1; j <= len2; ++j) { if (nums1[i - 1] == nums2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[len1][len2]; } }; } // namespace TEST(Leetcode, uncrossed_lines) { Solution s; EXPECT_EQ(2, s.maxUncrossedLines({1, 4, 2}, {1, 2, 4})); EXPECT_EQ(3, s.maxUncrossedLines({2, 5, 1, 2, 5}, {10, 5, 2, 1, 5, 2})); EXPECT_EQ(2, s.maxUncrossedLines({1, 3, 7, 1, 7, 5}, {1, 9, 2, 5, 1})); }
27.151515
75
0.502232
liubang
38ad213c84ab4193ab4d62bbafee306f350230d5
1,986
hpp
C++
agent/config.hpp
markovchainz/cppagent
97314ec43786a90697ca7fda15db13f2973aee3e
[ "Apache-2.0" ]
null
null
null
agent/config.hpp
markovchainz/cppagent
97314ec43786a90697ca7fda15db13f2973aee3e
[ "Apache-2.0" ]
null
null
null
agent/config.hpp
markovchainz/cppagent
97314ec43786a90697ca7fda15db13f2973aee3e
[ "Apache-2.0" ]
null
null
null
#ifndef CONFIG_HPP #define CONFIG_HPP #include "service.hpp" #include <string> class Agent; class Device; class log_level; class RollingFileLogger; typedef void (NamespaceFunction)(const std::string &aUrn, const std::string &aLocation, const std::string &aPrefix); typedef void (StyleFunction)(const std::string &aLocation); class AgentConfiguration : public MTConnectService { public: AgentConfiguration(); virtual ~AgentConfiguration(); // For MTConnectService virtual void stop(); virtual void start() ; virtual void initialize(int aArgc, const char *aArgv[]); void configureLogger(dlib::config_reader::kernel_1a &aReader); void loadConfig(std::istream &aFile); void setAgent(Agent *aAgent) { mAgent = aAgent; } Agent *getAgent() { return mAgent; } RollingFileLogger *getLogger() { return mLoggerFile; } protected: Device *defaultDevice(); void loadAdapters(dlib::config_reader::kernel_1a &aReader, bool aDefaultPreserve, int aLegacyTimeout, int aReconnectInterval, bool aIgnoreTimestamps, bool aConversionRequired, bool aUpcaseValue); void loadAllowPut(dlib::config_reader::kernel_1a &aReader); void loadNamespace(dlib::config_reader::kernel_1a &aReader, const char *aNamespaceType, NamespaceFunction *aCallback); void loadFiles(dlib::config_reader::kernel_1a &aReader); void loadStyle(dlib::config_reader::kernel_1a &aReader, const char *aDoc, StyleFunction *aFunction); void loadTypes(dlib::config_reader::kernel_1a &aReader); void LoggerHook(const std::string& aLoggerName, const dlib::log_level& l, const dlib::uint64 aThreadId, const char* aMessage); void monitorThread(); protected: Agent *mAgent; RollingFileLogger *mLoggerFile; bool mMonitorFiles; int mMinimumConfigReloadAge; std::string mDevicesFile; bool mRestart; }; #endif
31.03125
102
0.698892
markovchainz
38b35326baacef053863eb2e67ea332261250704
1,169
cpp
C++
src/state/levelUp.cpp
nick-valentine/roguelike
51c3a3a182d18e555d4f1744ed3e1a95f3aa1a83
[ "MIT" ]
null
null
null
src/state/levelUp.cpp
nick-valentine/roguelike
51c3a3a182d18e555d4f1744ed3e1a95f3aa1a83
[ "MIT" ]
null
null
null
src/state/levelUp.cpp
nick-valentine/roguelike
51c3a3a182d18e555d4f1744ed3e1a95f3aa1a83
[ "MIT" ]
null
null
null
#include "levelUp.h" namespace state { LevelUp::LevelUp(objects::EntityAttribute *playerStats) : Abstract(), mPlayerStats(playerStats) { std::vector<std::string> options; options.push_back("health"); options.push_back("strength"); options.push_back("constitution"); options.push_back("dexterity"); options.push_back("agility"); options.push_back("magicka"); mMenu = component::Menu("You leveled up! What would you like to improve?", options, iPoint(1, 1), iPoint(20, 20)); } void LevelUp::update(Context *ctx) { int result = mMenu.update(ctx); switch (result) { case -1: return; case -2: mLog->info("you really should improve something"); return; case 0: mPlayerStats->health+=5; mPlayerStats->maxHealth+=5; break; case 1: mPlayerStats->strength++; break; case 2: mPlayerStats->constitution++; break; case 3: mPlayerStats->dexterity++; break; case 4: mPlayerStats->agility++; break; case 5: mPlayerStats->magicka++; default: break; } mShouldClose = true; } void LevelUp::render(window::ptr &win) { mMenu.setDims(iPoint(1, 1), win->size()); mMenu.render(win); } }
20.875
116
0.664671
nick-valentine
38b61429e809d4788aeb34a881461b3289cff217
1,871
cc
C++
tests/testStringRef.cc
magestik/gf
60d9bbe084828fff88f1a511bd1191c774ccef4a
[ "Zlib" ]
null
null
null
tests/testStringRef.cc
magestik/gf
60d9bbe084828fff88f1a511bd1191c774ccef4a
[ "Zlib" ]
null
null
null
tests/testStringRef.cc
magestik/gf
60d9bbe084828fff88f1a511bd1191c774ccef4a
[ "Zlib" ]
null
null
null
/* * Gamedev Framework (gf) * Copyright (C) 2016-2018 Julien Bernard * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <gf/StringRef.h> #include "gtest/gtest.h" TEST(StringRefTest, DefaultCtor) { gf::StringRef ref; EXPECT_EQ(0u, ref.getSize()); EXPECT_EQ(nullptr, ref.getData()); } TEST(StringRefTest, PointerCtor) { const char *str = "a string"; gf::StringRef ref(str); EXPECT_EQ(8u, ref.getSize()); EXPECT_EQ(str, ref.getData()); } TEST(StringRefTest, PointerSizeCtor) { const char *str = "a string"; gf::StringRef ref(str, 8); EXPECT_EQ(8u, ref.getSize()); EXPECT_EQ(str, ref.getData()); } TEST(StringRefTest, StringCtor) { std::string str("a string"); gf::StringRef ref(str); EXPECT_EQ(8u, ref.getSize()); EXPECT_EQ(&str[0], ref.getData()); } TEST(StringRefTest, IsEmpty) { std::string str1; gf::StringRef ref1(str1); EXPECT_TRUE(ref1.isEmpty()); const char *str2 = ""; gf::StringRef ref2(str2); EXPECT_TRUE(ref2.isEmpty()); gf::StringRef ref3; EXPECT_TRUE(ref3.isEmpty()); }
26.352113
77
0.706574
magestik
38b6195bf3eb833350e9e86c7617ad0678daae02
608
cpp
C++
src/backends/windows/window/get_long_ptr.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
src/backends/windows/window/get_long_ptr.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
src/backends/windows/window/get_long_ptr.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
#include <awl/exception.hpp> #include <awl/backends/windows/clear_last_error.hpp> #include <awl/backends/windows/has_last_error.hpp> #include <awl/backends/windows/windows.hpp> #include <awl/backends/windows/window/get_long_ptr.hpp> #include <fcppt/text.hpp> LONG_PTR awl::backends::windows::window::get_long_ptr(HWND const _hwnd, int const _index) { awl::backends::windows::clear_last_error(); LONG_PTR const result{::GetWindowLongPtr(_hwnd, _index)}; if (result == 0 && awl::backends::windows::has_last_error()) throw awl::exception{FCPPT_TEXT("GetWindowLongPtr failed")}; return result; }
30.4
80
0.759868
freundlich
38bcdde813e0c908d57e77a5cba83638a307f026
628
cpp
C++
LeetCode/Medium/Longest Common Subsequence/Solution_1.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
8
2021-02-14T13:13:27.000Z
2022-01-08T23:58:32.000Z
LeetCode/Medium/Longest Common Subsequence/Solution_1.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
17
2021-02-28T17:03:50.000Z
2021-10-19T13:02:03.000Z
LeetCode/Medium/Longest Common Subsequence/Solution_1.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
15
2021-03-01T03:54:29.000Z
2021-10-19T18:29:00.000Z
class Solution { public: int longestCommonSubsequence(string text1, string text2){ int n1 = text1.length(); int n2 = text2.length(); vector<vector<int>>dp(n1+1,vector<int>(n2+1,0)); for(int i =1;i<=n1;i++){ for(int j = 1; j<=n2; j++){ if(text1[i-1] == text2[j-1]){ dp[i][j] = 1+ dp[i-1][j-1]; } else{ int op1 = dp[i-1][j]; int op2 = dp[i][j-1]; dp[i][j] = max(op1,op2); } } } return dp[n1][n2]; } };
28.545455
61
0.374204
shouryagupta21
38c10017df290898d00dbb9d08f71bb51fee0049
2,418
cpp
C++
test/linux_unit_tests/TemplateProcessorTest.cpp
PlutoLimited/Smooth
76251a4e69ea085718fe3f42ea8a24f496139111
[ "Apache-2.0" ]
283
2017-07-18T15:31:42.000Z
2022-03-30T12:05:03.000Z
test/linux_unit_tests/TemplateProcessorTest.cpp
PlutoLimited/Smooth
76251a4e69ea085718fe3f42ea8a24f496139111
[ "Apache-2.0" ]
131
2017-08-23T18:49:03.000Z
2021-11-29T08:03:21.000Z
test/linux_unit_tests/TemplateProcessorTest.cpp
PlutoLimited/Smooth
76251a4e69ea085718fe3f42ea8a24f496139111
[ "Apache-2.0" ]
53
2017-12-31T13:34:21.000Z
2022-02-04T11:26:49.000Z
/* Smooth - A C++ framework for embedded programming on top of Espressif's ESP-IDF Copyright 2019 Per Malmberg (https://gitbub.com/PerMalmberg) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <catch2/catch.hpp> #include <unordered_map> #define EXPOSE_PRIVATE_PARTS_FOR_TEST #include "smooth/application/network/http/regular/TemplateProcessor.h" #include "smooth/application/network/http/regular/ITemplateDataRetriever.h" using namespace smooth::application::network::http::regular; class DataRetriever : public ITemplateDataRetriever { public: DataRetriever() { data.emplace("{{name}}", "Bob"); data.emplace("{{food}}", "an ice cream"); } std::string get(const std::string& key) const override { std::string res{}; try { res = data.at(key); } catch (...) { } return res; } private: std::unordered_map<std::string, std::string> data{}; }; SCENARIO("Parsing a text") { GIVEN("A text") { std::string text{ "Hello {{name}}, want {{food}}?" }; THEN("Correctly replaces tokens") { auto dr = std::make_shared<DataRetriever>(); std::set<std::string> ss{ "html" }; TemplateProcessor tp(std::move(ss), dr); tp.process_template(text); REQUIRE(text == "Hello Bob, want an ice cream?"); } } } SCENARIO("Parsing a text with unknown tokens") { GIVEN("A text") { std::string text{ "---{{abc}}---" }; THEN("Replaces with empty string") { auto dr = std::make_shared<DataRetriever>(); std::set<std::string> ss{ "html" }; TemplateProcessor tp(std::move(ss), dr); tp.process_template(text); REQUIRE(text == "------"); } } }
26.571429
79
0.598015
PlutoLimited
38c1f26b09330b9e67e7e1b6155d380b9c692ea1
3,209
cpp
C++
src/bench/ccoins_caching.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
13
2019-01-23T04:36:05.000Z
2022-02-21T11:20:25.000Z
src/bench/ccoins_caching.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
null
null
null
src/bench/ccoins_caching.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
3
2019-01-24T07:48:15.000Z
2021-06-11T13:34:44.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //版权所有(c)2016-2018比特币核心开发者 //根据MIT软件许可证分发,请参见随附的 //文件复制或http://www.opensource.org/licenses/mit-license.php。 #include <bench/bench.h> #include <coins.h> #include <policy/policy.h> #include <wallet/crypter.h> #include <vector> //Fixme:在test/transaction_tests.cpp中使用setupdummyinputs进行重复数据消除。 // //帮助程序:创建两个虚拟事务,每个事务使用 //两个输出。第一个有11个和50个硬币输出 //支付给Tx Pubkey,第二个21和22个硬币输出 //支付给一个tx-pubkeyhash。 // static std::vector<CMutableTransaction> SetupDummyInputs(CBasicKeyStore& keystoreRet, CCoinsViewCache& coinsRet) { std::vector<CMutableTransaction> dummyTransactions; dummyTransactions.resize(2); //向密钥库添加一些密钥: CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(i % 2); keystoreRet.AddKey(key[i]); } //创建一些虚拟输入事务 dummyTransactions[0].vout.resize(2); dummyTransactions[0].vout[0].nValue = 11 * COIN; dummyTransactions[0].vout[0].scriptPubKey << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG; dummyTransactions[0].vout[1].nValue = 50 * COIN; dummyTransactions[0].vout[1].scriptPubKey << ToByteVector(key[1].GetPubKey()) << OP_CHECKSIG; AddCoins(coinsRet, CTransaction(dummyTransactions[0]), 0); dummyTransactions[1].vout.resize(2); dummyTransactions[1].vout[0].nValue = 21 * COIN; dummyTransactions[1].vout[0].scriptPubKey = GetScriptForDestination(key[2].GetPubKey().GetID()); dummyTransactions[1].vout[1].nValue = 22 * COIN; dummyTransactions[1].vout[1].scriptPubKey = GetScriptForDestination(key[3].GetPubKey().GetID()); AddCoins(coinsRet, CTransaction(dummyTransactions[1]), 0); return dummyTransactions; } //用于简单访问ccoinsviewcache数据库的微基准。注自 //Laanwj,“但是,复制客户机的实际使用模式很困难, //很多时候,数据库的微观基准显示完全不同 //特征,例如重新索引计时。但这不是 //每一个基准。” //(https://github.com/bitcoin/bitcoin/issues/7883_issuecomment-224807484) static void CCoinsCaching(benchmark::State& state) { CBasicKeyStore keystore; CCoinsView coinsDummy; CCoinsViewCache coins(&coinsDummy); std::vector<CMutableTransaction> dummyTransactions = SetupDummyInputs(keystore, coins); CMutableTransaction t1; t1.vin.resize(3); t1.vin[0].prevout.hash = dummyTransactions[0].GetHash(); t1.vin[0].prevout.n = 1; t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0); t1.vin[1].prevout.hash = dummyTransactions[1].GetHash(); t1.vin[1].prevout.n = 0; t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); t1.vin[2].prevout.hash = dummyTransactions[1].GetHash(); t1.vin[2].prevout.n = 1; t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); t1.vout.resize(2); t1.vout[0].nValue = 90 * COIN; t1.vout[0].scriptPubKey << OP_1; //基准。 const CTransaction tx_1(t1); while (state.KeepRunning()) { bool success = AreInputsStandard(tx_1, coins); assert(success); CAmount value = coins.GetValueIn(tx_1); assert(value == (50 + 21 + 22) * COIN); } } BENCHMARK(CCoinsCaching, 170 * 1000);
33.082474
100
0.703334
yinchengtsinghua
38c35ab65ac6d34784842a53cc14f8d02aaa3805
4,525
cpp
C++
src/complexMoveHeuristic.cpp
robhor/tcbvrp
86cd6c1ec5a1152ff2ddb154183b005f6f7751ed
[ "MIT" ]
null
null
null
src/complexMoveHeuristic.cpp
robhor/tcbvrp
86cd6c1ec5a1152ff2ddb154183b005f6f7751ed
[ "MIT" ]
null
null
null
src/complexMoveHeuristic.cpp
robhor/tcbvrp
86cd6c1ec5a1152ff2ddb154183b005f6f7751ed
[ "MIT" ]
null
null
null
// Copyright 2014 Robert Horvath, Johannes Vogel #include "./complexMoveHeuristic.h" #include "./nodeSwapper.h" #include "./edgeMover.h" #include "./supplySwapper.h" bool complexMove(Solution* solution, time_t stop_time, int moves, int current_length); bool complexMove_nodeSwap(Solution* solution, time_t stop_time, bool best_improvement, int moves, int current_length); bool complexMove_edgeMove(Solution* solution, time_t stop_time, bool best_improvement, int moves, int current_length); bool complexMove_supplySwap(Solution* solution, time_t stop_time, bool best_improvement, int moves, int current_length); bool time_up(time_t stop_time) { time_t current_time = time(nullptr); if (current_time > stop_time) return true; return false; } bool complexMove(Solution* solution, time_t stop_time, bool best_improvement, int moves, int current_length) { if (time_up(stop_time)) return false; return complexMove_nodeSwap(solution, stop_time, best_improvement, moves, current_length) || complexMove_edgeMove(solution, stop_time, best_improvement, moves, current_length) || complexMove_supplySwap(solution, stop_time, best_improvement, moves, current_length); } bool complexMove_nodeSwap(Solution* solution, time_t stop_time, bool best_improvement, int moves, int current_length) { NodeSwapper ns(solution); if (best_improvement && moves == 1) { Solution *best_solution = solution->clone(); while (ns.next()) { if (solution->length < best_solution->length) { delete best_solution; best_solution = solution->clone(); } } if (best_solution->length < current_length) { solution->set(best_solution); return true; } else { return false; } } while (ns.next()) { if (solution->length < current_length) { return true; } else if (moves > 1) { if (complexMove(solution, stop_time, best_improvement, moves-1, current_length)) { return true; } } } return false; } bool complexMove_edgeMove(Solution* solution, time_t stop_time, bool best_improvement, int moves, int current_length) { EdgeMover em(solution); if (best_improvement && moves == 1) { Solution *best_solution = solution->clone(); while (em.next()) { if (solution->length < best_solution->length) { delete best_solution; best_solution = solution->clone(); } } if (best_solution->length < current_length) { solution->set(best_solution); return true; } else { return false; } } while (em.next()) { if (solution->length < current_length) { return true; } else if (moves > 1) { if (complexMove(solution, stop_time, best_improvement, moves-1, current_length)) { return true; } } } return false; } bool complexMove_supplySwap(Solution* solution, time_t stop_time, bool best_improvement, int moves, int current_length) { SupplySwapper ss(solution); if (best_improvement && moves == 1) { Solution *best_solution = solution->clone(); while (ss.next()) { if (solution->length < best_solution->length) { delete best_solution; best_solution = solution->clone(); } } if (best_solution->length < current_length) { solution->set(best_solution); return true; } else { return false; } } while (ss.next()) { if (solution->length < current_length) { return true; } else if (moves > 1) { if (complexMove(solution, stop_time, best_improvement, moves-1, current_length)) { return true; } } } return false; } bool complexMove(Solution* solution, time_t stop_time, bool best_improvement) { int moves = 1; while (!time_up(stop_time)) { if (complexMove(solution, stop_time, best_improvement, moves, solution->length)) { return true; } else { moves++; } } return false; }
31.423611
96
0.58453
robhor
38c8dc4a0bc061b7a33f7db26384bcc9b4606326
414
cpp
C++
src/autowiring/dispatch_aborted_exception.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
src/autowiring/dispatch_aborted_exception.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
src/autowiring/dispatch_aborted_exception.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
// Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "dispatch_aborted_exception.h" dispatch_aborted_exception::dispatch_aborted_exception(void) : autowiring_error("Dispatch queue aborted") {} dispatch_aborted_exception::dispatch_aborted_exception(const std::string& what) : autowiring_error(what) {} dispatch_aborted_exception::~dispatch_aborted_exception(void){}
29.571429
81
0.806763
CaseyCarter