blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
cf1fe3499d46a2f832c7574452f3f6c2b0abda7c
04913c00867c4ee73032f6cb04bb98300faeff6b
/src/include/pmdOptions.hpp
e55300b03aa892e80625e828924f041ddb7fde34
[]
no_license
Apulus/GHDB
a51c971f0f4e592c27502d385e3f58ab88219bbb
51775c8828903fc4c5d3232ebdb18cc51c8c4845
refs/heads/master
2021-05-02T11:04:03.832842
2017-03-22T08:10:49
2017-03-22T08:10:49
53,928,024
1
1
null
2016-03-15T09:35:12
2016-03-15T08:39:06
null
UTF-8
C++
false
false
2,802
hpp
/************************************************** Copyright (C) 2016 CHEN Gonghao. chengonghao@yeah.net **************************************************/ #ifndef PMDOPTIONS_HPP__ #define PMDOPTIONS_HPP__ #include "core.hpp" #include <boost/program_options.hpp> #include <boost/program_options/parsers.hpp> using namespace std ; namespace po = boost::program_options ; #define PMD_OPTION_HELP "help" #define PMD_OPTION_DBPATH "dbpath" #define PMD_OPTION_SVCNAME "svcname" #define PMD_OPTION_MAXPOOL "maxpool" #define PMD_OPTION_LOGPATH "logpath" #define PMD_OPTION_CONFPATH "confpath" #define PMD_ADD_PARAM_OPTIONS_BEGIN( desc )\ desc.add_options() #define PMD_ADD_PARAM_OPTIONS_END ; #define PMD_COMMANDS_STRING(a,b) (string(a) + string(b)).c_str() #define PMD_COMMANDS_OPTIONS \ ( PMD_COMMANDS_STRING ( PMD_OPTION_HELP, ",h"), "help" ) \ ( PMD_COMMANDS_STRING ( PMD_OPTION_DBPATH, ",d"), boost::program_options::value<string>(), "database file full path" ) \ ( PMD_COMMANDS_STRING ( PMD_OPTION_SVCNAME, ",s"), boost::program_options::value<string>(), "local service name" ) \ ( PMD_COMMANDS_STRING ( PMD_OPTION_MAXPOOL, ",m"), boost::program_options::value<string>(), "max pooled agent" ) \ ( PMD_COMMANDS_STRING ( PMD_OPTION_LOGPATH, ",l"), boost::program_options::value<string>(), "diagnostic log file full path" ) \ ( PMD_COMMANDS_STRING ( PMD_OPTION_CONFPATH, ",c"), boost::program_options::value<string>(), "configuration file full path" ) \ #define CONFFILENAME "ghdb.conf" #define LOGFILENAME "diag.log" #define DBFILENAME "ghdb.data" #define SVCNAME "48127" #define NUMPOOL 20 class pmdOptions { public : pmdOptions () ; ~pmdOptions () ; public : int readCmd ( int argc, char **argv, po::options_description &desc, po::variables_map &vm ) ; int importVM ( const po::variables_map &vm, bool isDefault = true ) ; int readConfigureFile ( const char *path, po::options_description &desc, po::variables_map &vm ) ; int init ( int argc, char **argv ) ; public : inline char *getDBPath () { return _dbPath ; } inline char *getLogPath () { return _logPath ; } inline char *getConfPath () { return _confPath ; } inline char *getServiceName() { return _svcName ; } inline int getMaxPool () { return _maxPool ; } private : char _dbPath [ OSS_MAX_PATHSIZE+1 ] ; char _logPath [ OSS_MAX_PATHSIZE+1 ] ; char _confPath [ OSS_MAX_PATHSIZE+1 ] ; char _svcName [ NI_MAXSERV+1 ] ; int _maxPool ; } ; #endif
[ "chengonghao@yeah.net" ]
chengonghao@yeah.net
3c27974ed981aae87b9c0a97e54fbeb0ed13878f
95d149260a735a4b2173a40bb6dc14cd7e2d4cc2
/src/load_service.cc
6010167a111f19d0946190e000bdb69204acdaca
[ "Apache-2.0" ]
permissive
dmreiland/dinit
4886368aff0eef557f9a4b32a01b664ad0c1bff5
faa441bfc33fa8ae99eb6e4229276385fbfc5828
refs/heads/master
2020-07-23T20:28:10.592956
2017-06-13T00:01:28
2017-06-13T00:01:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,915
cc
#include <algorithm> #include <string> #include <fstream> #include <locale> #include <iostream> #include <limits> #include <sys/stat.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include "service.h" typedef std::string string; typedef std::string::iterator string_iterator; // Utility function to skip white space. Returns an iterator at the // first non-white-space position (or at end). static string_iterator skipws(string_iterator i, string_iterator end) { using std::locale; using std::isspace; while (i != end) { if (! isspace(*i, locale::classic())) { break; } ++i; } return i; } // Read a setting name. static string read_setting_name(string_iterator & i, string_iterator end) { using std::locale; using std::ctype; using std::use_facet; const ctype<char> & facet = use_facet<ctype<char> >(locale::classic()); string rval; // Allow alphabetical characters, and dash (-) in setting name while (i != end && (*i == '-' || facet.is(ctype<char>::alpha, *i))) { rval += *i; ++i; } return rval; } namespace { class SettingException { std::string info; public: SettingException(const std::string &&exc_info) : info(std::move(exc_info)) { } std::string &getInfo() { return info; } }; } // Read a setting value // // In general a setting value is a single-line string. It may contain multiple parts // separated by white space (which is normally collapsed). A hash mark - # - denotes // the end of the value and the beginning of a comment (it should be preceded by // whitespace). // // Part of a value may be quoted using double quote marks, which prevents collapse // of whitespace and interpretation of most special characters (the quote marks will // not be considered part of the value). A backslash can precede a character (such // as '#' or '"' or another backslash) to remove its special meaning. Newline // characters are not allowed in values and cannot be quoted. // // This function expects the string to be in an ASCII-compatible, single byte // encoding (the "classic" locale). // // Params: // service_name - the name of the service to which the setting applies // i - reference to string iterator through the line // end - iterator at end of line // part_positions - list of <int,int> to which the position of each setting value // part will be added as [start,end). May be null. static string read_setting_value(string_iterator & i, string_iterator end, std::list<std::pair<unsigned,unsigned>> * part_positions = nullptr) { using std::locale; using std::isspace; i = skipws(i, end); string rval; bool new_part = true; int part_start; while (i != end) { char c = *i; if (c == '\"') { if (new_part) { part_start = rval.length(); new_part = false; } // quoted string ++i; while (i != end) { c = *i; if (c == '\"') break; if (c == '\n') { throw SettingException("Line end inside quoted string"); } else if (c == '\\') { // A backslash escapes the following character. ++i; if (i != end) { c = *i; if (c == '\n') { throw SettingException("Line end follows backslash escape character (`\\')"); } rval += c; } } else { rval += c; } ++i; } if (i == end) { // String wasn't terminated throw SettingException("Unterminated quoted string"); } } else if (c == '\\') { if (new_part) { part_start = rval.length(); new_part = false; } // A backslash escapes the next character ++i; if (i != end) { rval += *i; } else { throw SettingException("Backslash escape (`\\') not followed by character"); } } else if (isspace(c, locale::classic())) { if (! new_part && part_positions != nullptr) { part_positions->emplace_back(part_start, rval.length()); new_part = true; } i = skipws(i, end); if (i == end) break; if (*i == '#') break; // comment rval += ' '; // collapse ws to a single space continue; } else if (c == '#') { // Possibly intended a comment; we require leading whitespace to reduce occurrence of accidental // comments in setting values. throw SettingException("hashmark (`#') comment must be separated from setting value by whitespace"); } else { if (new_part) { part_start = rval.length(); new_part = false; } rval += c; } ++i; } // Got to end: if (part_positions != nullptr) { part_positions->emplace_back(part_start, rval.length()); } return rval; } static int signalNameToNumber(std::string &signame) { if (signame == "HUP") return SIGHUP; if (signame == "INT") return SIGINT; if (signame == "QUIT") return SIGQUIT; if (signame == "USR1") return SIGUSR1; if (signame == "USR2") return SIGUSR2; return -1; } static const char * uid_err_msg = "Specified user id contains invalid numeric characters or is outside allowed range."; // Parse a userid parameter which may be a numeric user ID or a username. If a name, the // userid is looked up via the system user database (getpwnam() function). In this case, // the associated group is stored in the location specified by the group_p parameter iff // it is not null and iff it contains the value -1. static uid_t parse_uid_param(const std::string &param, const std::string &service_name, gid_t *group_p) { // Could be a name or a numeric id. But we should assume numeric first, just in case // a user manages to give themselves a username that parses as a number. std::size_t ind = 0; try { // POSIX does not specify whether uid_t is an signed or unsigned, but regardless // is is probably safe to assume that valid values are positive. We'll also assert // that the value range fits within "unsigned long long" since it seems unlikely // that would ever not be the case. static_assert((uintmax_t)std::numeric_limits<uid_t>::max() <= (uintmax_t)std::numeric_limits<unsigned long long>::max(), "uid_t is too large"); unsigned long long v = std::stoull(param, &ind, 0); if (v > static_cast<unsigned long long>(std::numeric_limits<uid_t>::max()) || ind != param.length()) { throw ServiceDescriptionExc(service_name, uid_err_msg); } return v; } catch (std::out_of_range &exc) { throw ServiceDescriptionExc(service_name, uid_err_msg); } catch (std::invalid_argument &exc) { // Ok, so it doesn't look like a number: proceed... } errno = 0; struct passwd * pwent = getpwnam(param.c_str()); if (pwent == nullptr) { // Maybe an error, maybe just no entry. if (errno == 0) { throw ServiceDescriptionExc(service_name, "Specified user \"" + param + "\" does not exist in system database."); } else { throw ServiceDescriptionExc(service_name, std::string("Error accessing user database: ") + strerror(errno)); } } if (group_p && *group_p != (gid_t)-1) { *group_p = pwent->pw_gid; } return pwent->pw_uid; } static const char * num_err_msg = "Specified value contains invalid numeric characters or is outside allowed range."; // Parse an unsigned numeric parameter value static unsigned long long parse_unum_param(const std::string &param, const std::string &service_name, unsigned long long max = std::numeric_limits<unsigned long long>::max()) { std::size_t ind = 0; try { unsigned long long v = std::stoull(param, &ind, 0); if (v > max || ind != param.length()) { throw ServiceDescriptionExc(service_name, num_err_msg); } return v; } catch (std::out_of_range &exc) { throw ServiceDescriptionExc(service_name, num_err_msg); } catch (std::invalid_argument &exc) { throw ServiceDescriptionExc(service_name, num_err_msg); } } static const char * gid_err_msg = "Specified group id contains invalid numeric characters or is outside allowed range."; static gid_t parse_gid_param(const std::string &param, const std::string &service_name) { // Could be a name or a numeric id. But we should assume numeric first, just in case // a user manages to give themselves a username that parses as a number. std::size_t ind = 0; try { // POSIX does not specify whether uid_t is an signed or unsigned, but regardless // is is probably safe to assume that valid values are positive. We'll also assume // that the value range fits with "unsigned long long" since it seems unlikely // that would ever not be the case. // // TODO perhaps write a number parser, since even the unsigned variants of the C/C++ // functions accept a leading minus sign... unsigned long long v = std::stoull(param, &ind, 0); if (v > static_cast<unsigned long long>(std::numeric_limits<gid_t>::max()) || ind != param.length()) { throw ServiceDescriptionExc(service_name, gid_err_msg); } return v; } catch (std::out_of_range &exc) { throw ServiceDescriptionExc(service_name, gid_err_msg); } catch (std::invalid_argument &exc) { // Ok, so it doesn't look like a number: proceed... } errno = 0; struct group * grent = getgrnam(param.c_str()); if (grent == nullptr) { // Maybe an error, maybe just no entry. if (errno == 0) { throw ServiceDescriptionExc(service_name, "Specified group \"" + param + "\" does not exist in system database."); } else { throw ServiceDescriptionExc(service_name, std::string("Error accessing group database: ") + strerror(errno)); } } return grent->gr_gid; } static void parse_timespec(const std::string &paramval, const std::string &servicename, const char * paramname, timespec &ts) { decltype(ts.tv_sec) isec = 0; decltype(ts.tv_nsec) insec = 0; auto max_secs = std::numeric_limits<decltype(isec)>::max() / 10; auto len = paramval.length(); decltype(len) i; for (i = 0; i < len; i++) { char ch = paramval[i]; if (ch == '.') { i++; break; } if (ch < '0' || ch > '9') { throw ServiceDescriptionExc(servicename, std::string("Bad value for ") + paramname); } // check for overflow if (isec >= max_secs) { throw ServiceDescriptionExc(servicename, std::string("Too-large value for ") + paramname); } isec *= 10; isec += ch - '0'; } decltype(insec) insec_m = 100000000; // 10^8 for ( ; i < len; i++) { char ch = paramval[i]; if (ch < '0' || ch > '9') { throw ServiceDescriptionExc(servicename, std::string("Bad value for ") + paramname); } insec += (ch - '0') * insec_m; insec_m /= 10; } ts.tv_sec = isec; ts.tv_nsec = insec; } // Find a service record, or load it from file. If the service has // dependencies, load those also. // // Might throw a ServiceLoadExc exception if a dependency cycle is found or if another // problem occurs (I/O error, service description not found etc). Throws std::bad_alloc // if a memory allocation failure occurs. ServiceRecord * ServiceSet::loadServiceRecord(const char * name) { using std::string; using std::ifstream; using std::ios; using std::ios_base; using std::locale; using std::isspace; using std::list; using std::pair; // First try and find an existing record... ServiceRecord * rval = find_service(string(name)); if (rval != 0) { if (rval->isDummy()) { throw ServiceCyclicDependency(name); } return rval; } // Couldn't find one. Have to load it. string service_filename = service_dir; if (*(service_filename.rbegin()) != '/') { service_filename += '/'; } service_filename += name; string command; list<pair<unsigned,unsigned>> command_offsets; string stop_command; list<pair<unsigned,unsigned>> stop_command_offsets; string pid_file; ServiceType service_type = ServiceType::PROCESS; std::list<ServiceRecord *> depends_on; std::list<ServiceRecord *> depends_soft; string logfile; OnstartFlags onstart_flags; int term_signal = -1; // additional termination signal bool auto_restart = false; bool smooth_recovery = false; string socket_path; int socket_perms = 0666; // Note: Posix allows that uid_t and gid_t may be unsigned types, but eg chown uses -1 as an // invalid value, so it's safe to assume that we can do the same: uid_t socket_uid = -1; gid_t socket_gid = -1; // Restart limit interval / count; default is 10 seconds, 3 restarts: timespec restart_interval = { .tv_sec = 10, .tv_nsec = 0 }; int max_restarts = 3; timespec restart_delay = { .tv_sec = 0, .tv_nsec = 200000000 }; string line; ifstream service_file; service_file.exceptions(ios::badbit | ios::failbit); try { service_file.open(service_filename.c_str(), ios::in); } catch (std::ios_base::failure &exc) { throw ServiceNotFound(name); } // Add a dummy service record now to prevent infinite recursion in case of cyclic dependency rval = new ServiceRecord(this, string(name)); records.push_back(rval); try { // getline can set failbit if it reaches end-of-file, we don't want an exception in that case: service_file.exceptions(ios::badbit); while (! (service_file.rdstate() & ios::eofbit)) { getline(service_file, line); string::iterator i = line.begin(); string::iterator end = line.end(); i = skipws(i, end); if (i != end) { if (*i == '#') { continue; // comment line } string setting = read_setting_name(i, end); i = skipws(i, end); if (i == end || (*i != '=' && *i != ':')) { throw ServiceDescriptionExc(name, "Badly formed line."); } i = skipws(++i, end); if (setting == "command") { command = read_setting_value(i, end, &command_offsets); } else if (setting == "socket-listen") { socket_path = read_setting_value(i, end, nullptr); } else if (setting == "socket-permissions") { string sock_perm_str = read_setting_value(i, end, nullptr); std::size_t ind = 0; try { socket_perms = std::stoi(sock_perm_str, &ind, 8); if (ind != sock_perm_str.length()) { throw std::logic_error(""); } } catch (std::logic_error &exc) { throw ServiceDescriptionExc(name, "socket-permissions: Badly-formed or out-of-range numeric value"); } } else if (setting == "socket-uid") { string sock_uid_s = read_setting_value(i, end, nullptr); socket_uid = parse_uid_param(sock_uid_s, name, &socket_gid); } else if (setting == "socket-gid") { string sock_gid_s = read_setting_value(i, end, nullptr); socket_gid = parse_gid_param(sock_gid_s, name); } else if (setting == "stop-command") { stop_command = read_setting_value(i, end, &stop_command_offsets); } else if (setting == "pid-file") { pid_file = read_setting_value(i, end); } else if (setting == "depends-on") { string dependency_name = read_setting_value(i, end); depends_on.push_back(loadServiceRecord(dependency_name.c_str())); } else if (setting == "waits-for") { string dependency_name = read_setting_value(i, end); depends_soft.push_back(loadServiceRecord(dependency_name.c_str())); } else if (setting == "logfile") { logfile = read_setting_value(i, end); } else if (setting == "restart") { string restart = read_setting_value(i, end); auto_restart = (restart == "yes" || restart == "true"); } else if (setting == "smooth-recovery") { string recovery = read_setting_value(i, end); smooth_recovery = (recovery == "yes" || recovery == "true"); } else if (setting == "type") { string type_str = read_setting_value(i, end); if (type_str == "scripted") { service_type = ServiceType::SCRIPTED; } else if (type_str == "process") { service_type = ServiceType::PROCESS; } else if (type_str == "bgprocess") { service_type = ServiceType::BGPROCESS; } else if (type_str == "internal") { service_type = ServiceType::INTERNAL; } else { throw ServiceDescriptionExc(name, "Service type must be one of: \"scripted\"," " \"process\", \"bgprocess\" or \"internal\""); } } else if (setting == "options") { std::list<std::pair<unsigned,unsigned>> indices; string onstart_cmds = read_setting_value(i, end, &indices); for (auto indexpair : indices) { string option_txt = onstart_cmds.substr(indexpair.first, indexpair.second - indexpair.first); if (option_txt == "starts-rwfs") { onstart_flags.rw_ready = true; } else if (option_txt == "starts-log") { onstart_flags.log_ready = true; } else if (option_txt == "no-sigterm") { onstart_flags.no_sigterm = true; } else if (option_txt == "runs-on-console") { onstart_flags.runs_on_console = true; // A service that runs on the console necessarily starts on console: onstart_flags.starts_on_console = true; } else if (option_txt == "starts-on-console") { onstart_flags.starts_on_console = true; } else if (option_txt == "pass-cs-fd") { onstart_flags.pass_cs_fd = true; } else { throw ServiceDescriptionExc(name, "Unknown option: " + option_txt); } } } else if (setting == "termsignal") { string signame = read_setting_value(i, end, nullptr); int signo = signalNameToNumber(signame); if (signo == -1) { throw ServiceDescriptionExc(name, "Unknown/unsupported termination signal: " + signame); } else { term_signal = signo; } } else if (setting == "restart-limit-interval") { string interval_str = read_setting_value(i, end, nullptr); parse_timespec(interval_str, name, "restart-limit-interval", restart_interval); } else if (setting == "restart-delay") { string rsdelay_str = read_setting_value(i, end, nullptr); parse_timespec(rsdelay_str, name, "restart-delay", restart_delay); } else if (setting == "restart-limit-count") { string limit_str = read_setting_value(i, end, nullptr); max_restarts = parse_unum_param(limit_str, name, std::numeric_limits<int>::max()); } else { throw ServiceDescriptionExc(name, "Unknown setting: " + setting); } } } service_file.close(); if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS || service_type == ServiceType::SCRIPTED) { if (command.length() == 0) { throw ServiceDescriptionExc(name, "Service command not specified"); } } // Now replace the dummy service record with a real record: for (auto iter = records.begin(); iter != records.end(); iter++) { if (*iter == rval) { // We've found the dummy record delete rval; if (service_type == ServiceType::PROCESS) { auto rvalps = new process_service(this, string(name), std::move(command), command_offsets, &depends_on, &depends_soft); rvalps->set_restart_interval(restart_interval, max_restarts); rvalps->set_restart_delay(restart_delay); rval = rvalps; } else if (service_type == ServiceType::BGPROCESS) { auto rvalps = new bgproc_service(this, string(name), std::move(command), command_offsets, &depends_on, &depends_soft); rvalps->set_pid_file(std::move(pid_file)); rvalps->set_restart_interval(restart_interval, max_restarts); rvalps->set_restart_delay(restart_delay); rval = rvalps; } else if (service_type == ServiceType::SCRIPTED) { rval = new scripted_service(this, string(name), std::move(command), command_offsets, &depends_on, &depends_soft); rval->setStopCommand(stop_command, stop_command_offsets); } else { rval = new ServiceRecord(this, string(name), service_type, std::move(command), command_offsets, &depends_on, &depends_soft); } rval->setLogfile(logfile); rval->setAutoRestart(auto_restart); rval->setSmoothRecovery(smooth_recovery); rval->setOnstartFlags(onstart_flags); rval->setExtraTerminationSignal(term_signal); rval->set_socket_details(std::move(socket_path), socket_perms, socket_uid, socket_gid); *iter = rval; break; } } return rval; } catch (SettingException &setting_exc) { // Must remove the dummy service record. std::remove(records.begin(), records.end(), rval); delete rval; throw ServiceDescriptionExc(name, std::move(setting_exc.getInfo())); } catch (...) { // Must remove the dummy service record. std::remove(records.begin(), records.end(), rval); delete rval; throw; } }
[ "davmac@davmac.org" ]
davmac@davmac.org
1829aeed104e6a7bc43bcce3ea5d1151835c54b4
a9aca5fbf458c2799022fad925aaf5066fcad19e
/sources/model/Section.cpp
96da7ae2d04712564bd28580e84f843d81d8d96a
[ "MIT" ]
permissive
btolfa/aspose-words-cloud-cpp
ce68bce98392220038b3878eb6a1b3cf67a22b11
570980f5d1b02725ed792277a1c9923c50f8f8ff
refs/heads/master
2020-04-07T16:19:28.054962
2018-11-21T09:21:54
2018-11-21T09:21:54
158,524,516
0
0
null
2018-11-21T09:37:52
2018-11-21T09:37:51
null
UTF-8
C++
false
false
11,621
cpp
/** -------------------------------------------------------------------------------------------------------------------- * <copyright company="Aspose" file="Section.cpp"> * Copyright (c) 2018 Aspose.Words for Cloud * </copyright> * <summary> * 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. * </summary> -------------------------------------------------------------------------------------------------------------------- **/ #include "Section.h" namespace io { namespace swagger { namespace client { namespace model { Section::Section() { m_ChildNodesIsSet = false; m_HeaderFootersIsSet = false; m_PageSetupIsSet = false; m_ParagraphsIsSet = false; m_TablesIsSet = false; } Section::~Section() { } void Section::validate() { // TODO: implement validation } web::json::value Section::toJson() const { web::json::value val = this->LinkElement::toJson(); { std::vector<web::json::value> jsonArray; for( auto& item : m_ChildNodes ) { jsonArray.push_back(ModelBase::toJson(item)); } if(jsonArray.size() > 0) { val[utility::conversions::to_string_t("ChildNodes")] = web::json::value::array(jsonArray); } } if(m_HeaderFootersIsSet) { val[utility::conversions::to_string_t("HeaderFooters")] = ModelBase::toJson(m_HeaderFooters); } if(m_PageSetupIsSet) { val[utility::conversions::to_string_t("PageSetup")] = ModelBase::toJson(m_PageSetup); } if(m_ParagraphsIsSet) { val[utility::conversions::to_string_t("Paragraphs")] = ModelBase::toJson(m_Paragraphs); } if(m_TablesIsSet) { val[utility::conversions::to_string_t("Tables")] = ModelBase::toJson(m_Tables); } return val; } void Section::fromJson(web::json::value& val) { this->LinkElement::fromJson(val); { m_ChildNodes.clear(); std::vector<web::json::value> jsonArray; if(val.has_field(utility::conversions::to_string_t("ChildNodes"))) { for( auto& item : val[utility::conversions::to_string_t("ChildNodes")].as_array() ) { if(item.is_null()) { m_ChildNodes.push_back( std::shared_ptr<NodeLink>(nullptr) ); } else { std::shared_ptr<NodeLink> newItem(new NodeLink()); newItem->fromJson(item); m_ChildNodes.push_back( newItem ); } } } } if(val.has_field(utility::conversions::to_string_t("HeaderFooters"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("HeaderFooters")]; if(!fieldValue.is_null()) { std::shared_ptr<LinkElement> newItem(new LinkElement()); newItem->fromJson(fieldValue); setHeaderFooters( newItem ); } } if(val.has_field(utility::conversions::to_string_t("PageSetup"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("PageSetup")]; if(!fieldValue.is_null()) { std::shared_ptr<LinkElement> newItem(new LinkElement()); newItem->fromJson(fieldValue); setPageSetup( newItem ); } } if(val.has_field(utility::conversions::to_string_t("Paragraphs"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("Paragraphs")]; if(!fieldValue.is_null()) { std::shared_ptr<LinkElement> newItem(new LinkElement()); newItem->fromJson(fieldValue); setParagraphs( newItem ); } } if(val.has_field(utility::conversions::to_string_t("Tables"))) { web::json::value& fieldValue = val[utility::conversions::to_string_t("Tables")]; if(!fieldValue.is_null()) { std::shared_ptr<LinkElement> newItem(new LinkElement()); newItem->fromJson(fieldValue); setTables( newItem ); } } } void Section::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } if(m_LinkIsSet) { if (m_Link.get()) { m_Link->toMultipart(multipart, utility::conversions::to_string_t("link.")); } } { std::vector<web::json::value> jsonArray; for( auto& item : m_ChildNodes ) { jsonArray.push_back(ModelBase::toJson(item)); } if(jsonArray.size() > 0) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("ChildNodes"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); } } if(m_HeaderFootersIsSet) { if (m_HeaderFooters.get()) { m_HeaderFooters->toMultipart(multipart, utility::conversions::to_string_t("HeaderFooters.")); } } if(m_PageSetupIsSet) { if (m_PageSetup.get()) { m_PageSetup->toMultipart(multipart, utility::conversions::to_string_t("PageSetup.")); } } if(m_ParagraphsIsSet) { if (m_Paragraphs.get()) { m_Paragraphs->toMultipart(multipart, utility::conversions::to_string_t("Paragraphs.")); } } if(m_TablesIsSet) { if (m_Tables.get()) { m_Tables->toMultipart(multipart, utility::conversions::to_string_t("Tables.")); } } } void Section::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } if(multipart->hasContent(utility::conversions::to_string_t("link"))) { if(multipart->hasContent(utility::conversions::to_string_t("link"))) { std::shared_ptr<WordsApiLink> newItem(new WordsApiLink()); newItem->fromMultiPart(multipart, utility::conversions::to_string_t("link.")); setLink( newItem ); } } { m_ChildNodes.clear(); if(multipart->hasContent(utility::conversions::to_string_t("ChildNodes"))) { web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("ChildNodes")))); for( auto& item : jsonArray.as_array() ) { if(item.is_null()) { m_ChildNodes.push_back( std::shared_ptr<NodeLink>(nullptr) ); } else { std::shared_ptr<NodeLink> newItem(new NodeLink()); newItem->fromJson(item); m_ChildNodes.push_back( newItem ); } } } } if(multipart->hasContent(utility::conversions::to_string_t("HeaderFooters"))) { if(multipart->hasContent(utility::conversions::to_string_t("HeaderFooters"))) { std::shared_ptr<LinkElement> newItem(new LinkElement()); newItem->fromMultiPart(multipart, utility::conversions::to_string_t("HeaderFooters.")); setHeaderFooters( newItem ); } } if(multipart->hasContent(utility::conversions::to_string_t("PageSetup"))) { if(multipart->hasContent(utility::conversions::to_string_t("PageSetup"))) { std::shared_ptr<LinkElement> newItem(new LinkElement()); newItem->fromMultiPart(multipart, utility::conversions::to_string_t("PageSetup.")); setPageSetup( newItem ); } } if(multipart->hasContent(utility::conversions::to_string_t("Paragraphs"))) { if(multipart->hasContent(utility::conversions::to_string_t("Paragraphs"))) { std::shared_ptr<LinkElement> newItem(new LinkElement()); newItem->fromMultiPart(multipart, utility::conversions::to_string_t("Paragraphs.")); setParagraphs( newItem ); } } if(multipart->hasContent(utility::conversions::to_string_t("Tables"))) { if(multipart->hasContent(utility::conversions::to_string_t("Tables"))) { std::shared_ptr<LinkElement> newItem(new LinkElement()); newItem->fromMultiPart(multipart, utility::conversions::to_string_t("Tables.")); setTables( newItem ); } } } std::vector<std::shared_ptr<NodeLink>>& Section::getChildNodes() { return m_ChildNodes; } void Section::setChildNodes(std::vector<std::shared_ptr<NodeLink>> value) { m_ChildNodes = value; m_ChildNodesIsSet = true; } bool Section::childNodesIsSet() const { return m_ChildNodesIsSet; } void Section::unsetChildNodes() { m_ChildNodesIsSet = false; } std::shared_ptr<LinkElement> Section::getHeaderFooters() const { return m_HeaderFooters; } void Section::setHeaderFooters(std::shared_ptr<LinkElement> value) { m_HeaderFooters = value; m_HeaderFootersIsSet = true; } bool Section::headerFootersIsSet() const { return m_HeaderFootersIsSet; } void Section::unsetHeaderFooters() { m_HeaderFootersIsSet = false; } std::shared_ptr<LinkElement> Section::getPageSetup() const { return m_PageSetup; } void Section::setPageSetup(std::shared_ptr<LinkElement> value) { m_PageSetup = value; m_PageSetupIsSet = true; } bool Section::pageSetupIsSet() const { return m_PageSetupIsSet; } void Section::unsetPageSetup() { m_PageSetupIsSet = false; } std::shared_ptr<LinkElement> Section::getParagraphs() const { return m_Paragraphs; } void Section::setParagraphs(std::shared_ptr<LinkElement> value) { m_Paragraphs = value; m_ParagraphsIsSet = true; } bool Section::paragraphsIsSet() const { return m_ParagraphsIsSet; } void Section::unsetParagraphs() { m_ParagraphsIsSet = false; } std::shared_ptr<LinkElement> Section::getTables() const { return m_Tables; } void Section::setTables(std::shared_ptr<LinkElement> value) { m_Tables = value; m_TablesIsSet = true; } bool Section::tablesIsSet() const { return m_TablesIsSet; } void Section::unsetTables() { m_TablesIsSet = false; } } } } }
[ "evgeny.kuleshov@aspose.com" ]
evgeny.kuleshov@aspose.com
ccaef2ea8c7e0b6d097c73efbf99e257bffea052
e43ddf8aa1e5541205ace207bf13cb1d87cb2704
/ObLvliDlg.h
ea424981d3429eb1a647b4e4b71869f3b1a41b13
[ "MIT" ]
permissive
clayne/obranditem
5dbdf817cee53882020179d71de3f53ed6fe611e
4869f96bb9eda7b3a2369815c5f225050d28c445
refs/heads/master
2023-03-16T05:51:36.236547
2020-04-02T18:19:39
2020-04-02T18:19:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,497
h
/*=========================================================================== * * File: Oblvlidlg.H * Author: Dave Humphrey (uesp@sympatico.ca) * Created On: May 7, 2006 * * Description * *=========================================================================*/ #ifndef __OBLVLIDLG_H #define __OBLVLIDLG_H /*=========================================================================== * * Begin Required Includes * *=========================================================================*/ #include "modfile/records/oblvlirecord.h" #include "windows/obrecordlistctrl.h" /*=========================================================================== * End of Required Includes *=========================================================================*/ /*=========================================================================== * * Begin Class CobLvliDlg Definition * *=========================================================================*/ class CObLvliDlg : public CDialog { protected: CObLvliRecord* m_pRecord; public: /* Construction */ CObLvliDlg(CWnd* pParent = NULL); /* Set and get control data */ void ClearControlData (void); void SetControlData (void); void SetTitle (const SSCHAR* pEditorID); /* Set class members */ void SetRecord (CObRecord* pRecord) { m_pRecord = ObCastClass(CObLvliRecord, pRecord); } /* Dialog Data */ //{{AFX_DATA(CObLvliDlg) enum { IDD = IDD_LVLI_DLG }; CEdit m_UserData; CObRecordListCtrl m_ItemList; CButton m_CalculateEach; CButton m_CalculateAll; CEdit m_ChanceNone; CEdit m_EditorID; CEdit m_FormID; //}}AFX_DATA /* ClassWizard generated virtual function overrides */ //{{AFX_VIRTUAL(CObLvliDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL protected: /* Generated message map functions */ //{{AFX_MSG(CObLvliDlg) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; /*=========================================================================== * End of Class CobLvliDlg Definition *=========================================================================*/ //{{AFX_INSERT_LOCATION}} //}}AFX_INSERT_LOCATION #endif /*=========================================================================== * End of File Oblvlidlg.H *=========================================================================*/
[ "dave@uesp.net" ]
dave@uesp.net
46ed82eb32a5735e3cab37a63a1ef15a1af8bb75
e391808c077683c42f09278a9a98d005de3b561f
/Animation/sitem.cpp
78a8b0cdfee30e1698546369c85c90f654c3c0b2
[]
no_license
ShiFengZeng/Qt
feaa7c78d95e98b9e2ee458091e547f3a0cedf65
ddd6c268203af03f2abd845e6d73c98b638fb065
refs/heads/master
2020-03-21T01:54:16.467867
2018-06-20T02:17:50
2018-06-20T02:17:50
137,968,663
0
0
null
null
null
null
UTF-8
C++
false
false
1,769
cpp
#include "SItem.h" SItem::SItem() { //random start rotation angle = (qrand() % 60); setRotation(angle); //set the speed speed = 6; //random start position int StartX = 0; int StartY = 0; if((qrand() % 1)) { StartX = (qrand() % 200); StartY = (qrand() % 200); } else { StartX = (qrand() % -100); StartY = (qrand() % -100); } setPos(mapToParent(StartX,StartY)); } QRectF SItem::boundingRect() const { return QRect(0,0,50,50); } void SItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { QRectF rec = boundingRect(); //basic Collision detection if(scene()->collidingItems(this).isEmpty()) { //no collision } else { //collision!!!! //Set the position DoCollision(); } QImage image("C:\\Users\\A53\\Documents\\Qt\\Animation\\bee-cartoon.png"); painter->drawImage(rec,image); } void SItem::advance(int phase) { if(!phase) return; QPointF location = this->pos(); setPos(mapToParent(0,-(speed))); } void SItem::DoCollision() { //Get a new position //Change the angle with a little randomness if(((qrand() %1))) { setRotation(rotation() + (180 + (qrand() % 10))); } else { setRotation(rotation() + (180 + (qrand() % -10))); } //see if the new position is in bounds QPointF newpoint = mapToParent(-(boundingRect().width()), -(boundingRect().width() + 2)); if(!scene()->sceneRect().contains((newpoint))) { //move it back in bounds newpoint = mapToParent(0,0); } else { //set the new position setPos(newpoint); } }
[ "90011551a90011551@yahoo.com.tw" ]
90011551a90011551@yahoo.com.tw
bad14fa302fe5b7b6f0b86cb2b2a4e2ae8d418fd
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_DinoCharacterStatusComponent_BP_Kaprosuchus_parameters.hpp
2a0d0860e01e12c9832cf29c05d4be6c51befb3b
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
860
hpp
#pragma once // ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DinoCharacterStatusComponent_BP_Kaprosuchus_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function DinoCharacterStatusComponent_BP_Kaprosuchus.DinoCharacterStatusComponent_BP_Kaprosuchus_C.ExecuteUbergraph_DinoCharacterStatusComponent_BP_Kaprosuchus struct UDinoCharacterStatusComponent_BP_Kaprosuchus_C_ExecuteUbergraph_DinoCharacterStatusComponent_BP_Kaprosuchus_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
1c78d469e932bb7afa7a2c5e8ceb9a38524b706e
d839703d3e2f6947cd8c4314d01de2a70ffff1dc
/Union_Find/QuickUnion/QuickUnionUF.h
0b13882f3a2fe7b216884c97ee7fbbf38f6b3ba4
[]
no_license
sbonab/Algorithms
cea61b3e6af351fd0e4099eeecf1fc9c86155b6f
7bd4678beda4b4d67be660743fa77c448e91555a
refs/heads/master
2023-08-25T22:01:41.973974
2021-11-04T00:00:44
2021-11-04T00:00:44
367,378,175
0
0
null
null
null
null
UTF-8
C++
false
false
1,300
h
#ifndef QUICK_UNION_UF_H_ #define QUICK_UNION_UF_H_ #include <iostream> #include <vector> using std::vector; /** * Implementation of the weighted quick-union with path compression, WQUPC */ class QuickUnionUF { public: /** * Constructor * @param N Number of the nodes */ QuickUnionUF(int N); /** * Destructor */ virtual ~QuickUnionUF(); /** * [] Returns the id of the parent of the node * @param i Index of the node */ int& operator [](int i); /** * Finds whether or not given indices are connected * @param i Index of the first node * @param j Index of the second node */ bool Connected(int i, int j); /** * Changes the root of node i to root of node j * @param i Index of the first node * @param j Index of the second node */ void Union(int i, int j); /** * Find the root of the node with the passed index * @param i Index of the node */ int Root(int i); /** * Returns the number of the nodes */ int size(); /** * Prints the id of the parents */ void print() const; private: // id vector vector<int> id; // represents the depth of the tree that the node is part of vector<int> sz; }; #endif
[ "sbonab7@gmail.com" ]
sbonab7@gmail.com
d8a3965e47d45a87970713c2f1b663ec9d0107fd
a56252fda5c9e42eff04792c6e16e413ad51ba1a
/resources/home/dnanexus/root/include/TGLStopwatch.h
41d72b1843e56e9be21980d1fa906863f650bc6b
[ "LGPL-2.1-or-later", "LGPL-2.1-only", "Apache-2.0" ]
permissive
edawson/parliament2
4231e692565dbecf99d09148e75c00750e6797c4
2632aa3484ef64c9539c4885026b705b737f6d1e
refs/heads/master
2021-06-21T23:13:29.482239
2020-12-07T21:10:08
2020-12-07T21:10:08
150,246,745
0
0
Apache-2.0
2019-09-11T03:22:55
2018-09-25T10:21:03
Python
UTF-8
C++
false
false
2,085
h
// @(#)root/gl:$Id$ // Author: Richard Maunder 25/05/2005 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TGLStopwatch #define ROOT_TGLStopwatch #include "Rtypes.h" ////////////////////////////////////////////////////////////////////////// // // // TGLStopwatch // // // // Stopwatch object for timing GL work. We do not use the TStopwatch as // // we need to perform GL flushing to get accurate times + we record // // timing overheads here. // // // MT: Bypassed all of the overhead stuff. It does not seem reasonable // anyway. Besides it was being initialized outside of a valid GL // context and coused random crashes (especially on 64-bit machines with // nvidia cards). // ////////////////////////////////////////////////////////////////////////// class TGLStopwatch { private: // Fields Double_t fStart; //! start time (millisec) Double_t fEnd; //! end time (millisec) Double_t fLastRun; //! time of last run (milisec) // Methods Double_t GetClock(void) const; public: TGLStopwatch(); virtual ~TGLStopwatch(); // ClassDef introduces virtual fns void Start(); Double_t Lap() const; Double_t End(); Double_t LastRun() const { return fLastRun; } ClassDef(TGLStopwatch,0) // a GL stopwatch utility class }; #endif // ROOT_TGLStopwatch
[ "slzarate96@gmail.com" ]
slzarate96@gmail.com
abc7bdb75fe0c9ce9b7a9eea26898bfc67ba045d
28ff4c159715eb022dfb11ddcc9fcea4b751f43c
/syncdata/SDK/在售2次开发包201507/二次开发(基于底层协议)/02短报文协议DEMO/VC/WGController32_VC/ace/Intrusive_Auto_Ptr.inl
7aac01aa4e450823fe3c765e00a6cadcf4b2c625
[]
no_license
PravinShahi0007/kqmj
e0ddd74b1510a8f2576d459c3608f128c0c98c5a
c99c022ddd7cb2353a8ac2337602650634bfe49f
refs/heads/master
2023-03-17T15:29:29.442521
2019-02-19T07:52:41
2019-02-19T07:52:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,758
inl
// -*- C++ -*- // // $Id: Intrusive_Auto_Ptr.inl 96985 2013-04-11 15:50:32Z huangh $ #include "ace/Guard_T.h" #include "ace/Log_Category.h" ACE_BEGIN_VERSIONED_NAMESPACE_DECL template <class X> ACE_INLINE ACE_Intrusive_Auto_Ptr<X>::ACE_Intrusive_Auto_Ptr (X *p, bool addref) : rep_ (p) { if (rep_ != 0 && addref) X::intrusive_add_ref (rep_); } template <class X> ACE_INLINE ACE_Intrusive_Auto_Ptr<X>::ACE_Intrusive_Auto_Ptr (const ACE_Intrusive_Auto_Ptr<X> &r) : rep_ (r.rep_) { if (rep_ != 0) X::intrusive_add_ref (rep_); } template <class X> ACE_INLINE X * ACE_Intrusive_Auto_Ptr<X>::operator-> (void) const { return this->rep_; } template<class X> ACE_INLINE X & ACE_Intrusive_Auto_Ptr<X>::operator *() const { return *this->rep_; } template <class X> ACE_INLINE X* ACE_Intrusive_Auto_Ptr<X>::get (void) const { // We return the ACE_Future_rep. return this->rep_; } template<class X> ACE_INLINE X * ACE_Intrusive_Auto_Ptr<X>::release (void) { X *p = this->rep_; if (this->rep_ != 0) X::intrusive_remove_ref (this->rep_); this->rep_ = 0; return p; } template<class X> ACE_INLINE void ACE_Intrusive_Auto_Ptr<X>::reset (X *p) { // Avoid deleting the underlying auto_ptr if assigning the same actual // pointer value. if (this->rep_ == p) return; X *old_rep = this->rep_; this->rep_ = p; if (this->rep_ != 0) X::intrusive_add_ref (this->rep_); if (old_rep != 0) X::intrusive_remove_ref (old_rep); return; } template <class X> ACE_INLINE void ACE_Intrusive_Auto_Ptr<X>::operator = (const ACE_Intrusive_Auto_Ptr<X> &rhs) { // do nothing when aliasing if (this->rep_ == rhs.rep_) return; // assign a zero if (rhs.rep_ == 0) { X::intrusive_remove_ref (rhs.rep_); this->rep_ = 0; return; } // bind <this> to the same <ACE_Intrusive_Auto_Ptr_Rep> as <rhs>. X *old_rep = this->rep_; this->rep_ = rhs.rep_; X::intrusive_add_ref (this->rep_); X::intrusive_remove_ref (old_rep); } // Copy derived class constructor template<class X> template <class U> ACE_INLINE ACE_Intrusive_Auto_Ptr<X>::ACE_Intrusive_Auto_Ptr (const ACE_Intrusive_Auto_Ptr<U> & rhs) { // note implicit cast from U* to T* so illegal copy will generate a // compiler warning here this->rep_ = rhs.operator-> (); X::intrusive_add_ref(this->rep_); } /// Equality operator that returns @c true if both /// ACE_Intrusive_Auto_Ptr objects point to the same underlying /// representation. It does not compare the actual pointers. /** * @note It also returns @c true if both objects have just been * instantiated and not used yet. */ template<class T, class U> ACE_INLINE bool operator==(ACE_Intrusive_Auto_Ptr<T> const & a, ACE_Intrusive_Auto_Ptr<U> const & b) { return a.get() == b.get(); } /// Inequality operator, which is the opposite of equality. template<class T, class U> ACE_INLINE bool operator!=(ACE_Intrusive_Auto_Ptr<T> const & a, ACE_Intrusive_Auto_Ptr<U> const & b) { return a.get() != b.get(); } template<class T, class U> ACE_INLINE bool operator==(ACE_Intrusive_Auto_Ptr<T> const & a, U * b) { return a.get() == b; } template<class T, class U> ACE_INLINE bool operator!=(ACE_Intrusive_Auto_Ptr<T> & a, U * b) { return a.get() != b; } template<class T, class U> ACE_INLINE bool operator==(T * a, ACE_Intrusive_Auto_Ptr<U> const & b) { return a == b.get(); } template<class T, class U> ACE_INLINE bool operator!=(T * a, ACE_Intrusive_Auto_Ptr<U> const & b) { return a != b.get(); } ACE_END_VERSIONED_NAMESPACE_DECL
[ "zj@fccs.com" ]
zj@fccs.com
0252a98e5430566fec3b97644f937df3f171df21
5b641d7b69ba0d43bd224d19831ab67a5b101582
/bin/xsandbox/graphics.cpp
36a22576808e99c1adce493a81ecb9273fdbc2d5
[]
no_license
jpivarski-talks/1999-2006_gradschool-2
9d7a4e91bbde6dc7f472ea21253b32a0eca104e4
ca889b4d09814a226513e39625ae2f140c97b5d5
refs/heads/master
2022-11-19T11:37:55.623868
2020-07-25T01:19:32
2020-07-25T01:19:32
282,235,528
0
0
null
null
null
null
UTF-8
C++
false
false
8,778
cpp
#include "graphics.h" #include "sand_water.h" int width = 400; int height = 300; float light_angle = 150. * 3.14 / 180.; float lightx = cos( light_angle ); float lighty = sin( light_angle ); const float lightz = 5.; bool contours = true; unsigned char* buffer = NULL; float* sand_speckle = NULL; //// graphics_init() //////////////////////////////////////////////////// void graphics_init( GlobalParams par ) { width = par.window_width; height = par.window_height; buffer = (unsigned char*) malloc( 3 * sizeof( unsigned char ) * width * height ); sand_speckle = (float*) malloc( sizeof( float ) * width * height ); ASSERT( buffer ); ASSERT( sand_speckle ); for ( int y = 0; y < height; y++ ) for( int x = 0; x < width; x++ ) { // red, green and blue buffer[ BUFINDEX( x, y ) + 0 ] = 0; buffer[ BUFINDEX( x, y ) + 1 ] = 0; buffer[ BUFINDEX( x, y ) + 2 ] = 0; sand_speckle[ SPECKINDEX( x, y ) ] = generate_sand_speckle(); } } //// graphics_resize() ////////////////////////////////////////////////// void graphics_resize( int new_width, int new_height ) { unsigned char* new_buffer = (unsigned char*) malloc( 3 * sizeof( unsigned char ) * new_width * new_height ); float* new_sand_speckle = (float*) malloc( sizeof( float ) * new_width * new_height ); ASSERT( new_buffer ); ASSERT( new_sand_speckle ); // Looks crappy. :( // // for ( int y = 0; y < new_height; y++ ) // for( int x = 0; x < new_width; x++ ) // if ( x < width && y < height ) // { // // red, green and blue // new_buffer[ NEWINDEX( x, y ) + 0 ] = buffer[ BUFINDEX( x, y ) + 0 ]; // new_buffer[ NEWINDEX( x, y ) + 1 ] = buffer[ BUFINDEX( x, y ) + 1 ]; // new_buffer[ NEWINDEX( x, y ) + 2 ] = buffer[ BUFINDEX( x, y ) + 2 ]; // new_sand_speckle[ NEWSPECKINDEX( x, y ) ] = // sand_speckle[ SPECKINDEX( x, y ) ]; // } // else // { // // red, green and blue // new_buffer[ NEWINDEX( x, y ) + 0 ] = 0; // new_buffer[ NEWINDEX( x, y ) + 1 ] = 0; // new_buffer[ NEWINDEX( x, y ) + 2 ] = 0; // new_sand_speckle[ NEWSPECKINDEX( x, y ) ] = generate_sand_speckle(); // } for ( int y = 0; y < new_height; y++ ) for( int x = 0; x < new_width; x++ ) { // red, green and blue new_buffer[ NEWINDEX( x, y ) + 0 ] = 0; new_buffer[ NEWINDEX( x, y ) + 1 ] = 0; new_buffer[ NEWINDEX( x, y ) + 2 ] = 0; new_sand_speckle[ NEWSPECKINDEX( x, y ) ] = generate_sand_speckle(); } free( buffer ); free( sand_speckle ); buffer = new_buffer; sand_speckle = new_sand_speckle; width = new_width; height = new_height; } //// graphics_cleanup() ///////////////////////////////////////////////// void graphics_cleanup() { free( buffer ); } //// change_light_angle() /////////////////////////////////////////////// void change_light_angle( float delta ) { light_angle += delta; lightx = cos( light_angle ); lighty = sin( light_angle ); } //// toggle_contours() ////////////////////////////////////////////////// void toggle_contours() { contours = ( ! contours ); } //// generate_sand_speckle() //////////////////////////////////////////// float generate_sand_speckle() { // Get gaussian deviates by the elimination method float rx, ry; do { rx = ( float( rand() ) / float( RAND_MAX ) ) * 6. - 3.; ry = ( float( rand() ) / float( RAND_MAX ) ); } while( ry > exp( -( rx * rx / 2. ) ) ); return 1. + rx / 10.; } //// graphics_draw() //////////////////////////////////////////////////// void graphics_draw( int x, int y, int box_width, int box_height ) { int xbegin = ( x < 0 ? 0 : x ); int ybegin = ( y < 0 ? 0 : y ); int xend = x + box_width; int yend = y + box_height; if ( xend >= width ) xend = width; if ( yend >= height ) yend = height; for( int y_ = y; y_ < yend; y_++ ) for( int x_ = x; x_ < xend; x_++ ) pixel_draw( x_, y_ ); } //// pixel_draw() /////////////////////////////////////////////////////// // This is where a lot of time is spent. It is awkward because I am // trying to optimize it... void pixel_draw( int x, int y ) { unsigned char red, green, blue; // calculate shading from angle of illumination // (3-D mesh is made from triangles of sand pixels) float here = sand_pixel( x, y ); float right = sand_pixel( x + 1, y ); float down = sand_pixel( x, y + 1 ); const float min_reflection = -20.; const float max_reflection = 20.; // This is the dot product of the normal to the surface with the // vector { lightx, lighty, lightz } (the normal to the surface is // taken to have unit z-projection (maybe this would be better if // normalized... but it looks all right!) float reflection = ( ( ( lighty * ( right - here ) + lightx * ( down - here ) + lightz ) - min_reflection ) / ( max_reflection - min_reflection ) ); if ( reflection > 1. ) reflection = 1.; else if ( reflection < 0. ) reflection = 0.; float water_depth = water_pixel( x, y ); // this involves a little calculation const float max_sand_depth = 200.; const float min_sand_depth = -200.; float norm_sand = 0.; // only defined for water_depth < level_one if ( water_depth < level_one ) { norm_sand = ( here - min_sand_depth ) / ( max_sand_depth - min_sand_depth ); if ( norm_sand > 1. ) norm_sand = 1.; if ( norm_sand < 0. ) norm_sand = 0.; } // Four levels of water depth: if ( water_depth < level_zero ) { sand_color( norm_sand, reflection, sand_speckle[ SPECKINDEX( x, y ) ], &red, &green, &blue ); } else if ( water_depth < level_one ) { sand_color( norm_sand, reflection, sand_speckle[ SPECKINDEX( x, y ) ], &red, &green, &blue ); // first level is foam--- you can see the sand underneath but it // is whitened (50% translucent) // if ( water_depth + blocksand_pixel( x, y ) > sand_pixel( x, y ) ) // { red = (unsigned char)( ceil( ( 1. * red + 0xFF ) / 2. ) ); green = (unsigned char)( ceil( ( 1. * green + 0xFF ) / 2. ) ); blue = (unsigned char)( ceil( ( 1. * blue + 0xFF ) / 2. ) ); // } } else if ( water_depth < level_two ) { // see note about brightness in the "else" part. This one is // that, averaged with white (like the foam above) float brightness = 133.1 + 95.428 * sqrt( reflection ); red = green = 0; blue = (unsigned char)( ceil( brightness )); } else { // I used to calculate the sand first and get the water // brightness from the sand--- but that would be nominally the // following: float brightness = 11.23 + 190.86 * sqrt( reflection ); red = green = 0; blue = (unsigned char)( ceil( brightness )); } // since both contours and water shading are multiplicative // effects, it doesn't matter if there's water or sand here if ( contours ) { // this contortion of code may make things faster without contour lines if ( water_depth >= level_one ) { norm_sand = ( here - min_sand_depth ) / ( max_sand_depth - min_sand_depth ); if ( norm_sand > 1. ) norm_sand = 1.; if ( norm_sand < 0. ) norm_sand = 0.; } // the choices of 100 and 10 for modularization define contour // widths and spacings if ( int( floor( norm_sand * 100 ) ) % 10 == 5 ) { const float contour_dimming = 0.75; red = (unsigned char)( ceil( red * contour_dimming ) ); green = (unsigned char)( ceil( green * contour_dimming ) ); blue = (unsigned char)( ceil( blue * contour_dimming ) ); } } // now we have to actually draw it into the buffer!!! buffer[ BUFINDEX( x, y ) + 0 ] = red; buffer[ BUFINDEX( x, y ) + 1 ] = green; buffer[ BUFINDEX( x, y ) + 2 ] = blue; } //// sand_color() /////////////////////////////////////////////////////// // sand color basically follows a brightness line on a nice sandy hue // there's a little variation in color with height and speckling in green void sand_color( float sand_depth, float reflection, float sand_speck, unsigned char* red, unsigned char* green, unsigned char* blue ) { // physically, the intensity should be the square of the // wavefunction (but the square root looks better!) *red = (unsigned char)( ceil( sqrt( reflection ) * 0xF0 + 0x0F ) ); // putting all the speckle in the green channel is convenient and // looks pretty nice float tmp = ceil( float( *red ) * ( 167 * sand_speck + 22 * sand_depth ) / 216 ); if ( tmp > 0xFF ) tmp = float( 0xFF ); *green = (unsigned char)( tmp ); *blue = (unsigned char)( ceil( float( *red ) * ( 80 * sand_depth + 51 ) / 216 ) ); }
[ "jpivarski@gmail.com" ]
jpivarski@gmail.com
cf694838118b486f6f9719d71629f09b0a793b33
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium/crypto/encryptor_nss.cc
aaa66268341623e15c87ff7e9d63e1ebe4c0e7df
[ "MIT", "BSD-3-Clause" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
3,677
cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "crypto/encryptor.h" #include <cryptohi.h> #include <vector> #include "base/logging.h" #include "crypto/nss_util.h" #include "crypto/symmetric_key.h" namespace crypto { Encryptor::Encryptor() : key_(NULL), mode_(CBC) { EnsureNSSInit(); } Encryptor::~Encryptor() { } bool Encryptor::Init(SymmetricKey* key, Mode mode, const std::string& iv) { DCHECK(key); DCHECK_EQ(CBC, mode); key_ = key; mode_ = mode; if (iv.size() != AES_BLOCK_SIZE) return false; slot_.reset(PK11_GetBestSlot(CKM_AES_CBC_PAD, NULL)); if (!slot_.get()) return false; SECItem iv_item; iv_item.type = siBuffer; iv_item.data = reinterpret_cast<unsigned char*>( const_cast<char *>(iv.data())); iv_item.len = iv.size(); param_.reset(PK11_ParamFromIV(CKM_AES_CBC_PAD, &iv_item)); if (!param_.get()) return false; return true; } bool Encryptor::Encrypt(const std::string& plaintext, std::string* ciphertext) { ScopedPK11Context context(PK11_CreateContextBySymKey(CKM_AES_CBC_PAD, CKA_ENCRYPT, key_->key(), param_.get())); if (!context.get()) return false; size_t ciphertext_len = plaintext.size() + AES_BLOCK_SIZE; std::vector<unsigned char> buffer(ciphertext_len); int op_len; SECStatus rv = PK11_CipherOp(context.get(), &buffer[0], &op_len, ciphertext_len, reinterpret_cast<unsigned char*>( const_cast<char*>(plaintext.data())), plaintext.size()); if (SECSuccess != rv) return false; unsigned int digest_len; rv = PK11_DigestFinal(context.get(), &buffer[op_len], &digest_len, ciphertext_len - op_len); if (SECSuccess != rv) return false; ciphertext->assign(reinterpret_cast<char *>(&buffer[0]), op_len + digest_len); return true; } bool Encryptor::Decrypt(const std::string& ciphertext, std::string* plaintext) { if (ciphertext.empty()) return false; ScopedPK11Context context(PK11_CreateContextBySymKey(CKM_AES_CBC_PAD, CKA_DECRYPT, key_->key(), param_.get())); if (!context.get()) return false; size_t plaintext_len = ciphertext.size(); std::vector<unsigned char> buffer(plaintext_len); int op_len; SECStatus rv = PK11_CipherOp(context.get(), &buffer[0], &op_len, plaintext_len, reinterpret_cast<unsigned char*>( const_cast<char*>(ciphertext.data())), ciphertext.size()); if (SECSuccess != rv) return false; unsigned int digest_len; rv = PK11_DigestFinal(context.get(), &buffer[op_len], &digest_len, plaintext_len - op_len); if (SECSuccess != rv) return false; plaintext->assign(reinterpret_cast<char *>(&buffer[0]), op_len + digest_len); return true; } } // namespace crypto
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
9b1aeff02e773d43f7489e989665db33d66f732b
664e84659fbbbe4f97c1740b28a4ddda8ea2b624
/include/gsound/math/SIMDRay3D.h
45098b0cb719fe1867f902feb64d4d4e01f9387b
[]
no_license
SoundSight/SoundSight
baeaa0dd26d454eeb859efe1b6091cc0b61761fa
0dd3a1c5a8824173de0174133d56279c8497457f
refs/heads/master
2021-01-01T05:14:53.424886
2016-05-27T05:12:34
2016-05-27T05:12:34
59,781,138
2
0
null
null
null
null
UTF-8
C++
false
false
6,454
h
/* * Project: GSound * * File: gsound/math/SIMDRay3D.h * * Version: 1.0.0 * * Contents: gsound::math::SIMDRay3D class declaration * * License: * * Copyright (C) 2010-12 Carl Schissler, University of North Carolina at Chapel Hill. * All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for educational, research, and non-profit purposes, without * fee, and without a written agreement is hereby granted, provided that the * above copyright notice, this paragraph, and the following four paragraphs * appear in all copies. * * Permission to incorporate this software into commercial products may be * obtained by contacting the University of North Carolina at Chapel Hill. * * This software program and documentation are copyrighted by Carl Schissler and * the University of North Carolina at Chapel Hill. The software program and * documentation are supplied "as is", without any accompanying services from * the University of North Carolina at Chapel Hill or the authors. The University * of North Carolina at Chapel Hill and the authors do not warrant that the * operation of the program will be uninterrupted or error-free. The end-user * understands that the program was developed for research purposes and is advised * not to rely exclusively on the program for any reason. * * IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR ITS * EMPLOYEES OR THE AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, * SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE * UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE AUTHORS HAVE BEEN ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY * DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY * STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND * THE AUTHORS HAVE NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, * ENHANCEMENTS, OR MODIFICATIONS. * * * Contact Information: * * Please send all bug reports and other contact to: * Carl Schissler * carl.schissler@gmail.com * * Updates and downloads are available at the main GSound web page: * http://gamma.cs.unc.edu/GSOUND/ * */ #ifndef INCLUDE_GSOUND_SIMD_RAY_3D_H #define INCLUDE_GSOUND_SIMD_RAY_3D_H #include "GSoundMathConfig.h" #include "Ray3D.h" #include "SIMDVector3D.h" //########################################################################################## //*************************** Start GSound Math Namespace ******************************** GSOUND_MATH_NAMESPACE_START //****************************************************************************************** //########################################################################################## //******************************************************************************** //******************************************************************************** //******************************************************************************** /// A template prototype declaration for the SIMDRay3D class. /** * This class is used to store and operate on a set of N 3D rays * in a SIMD fashion. The rays are stored in a structure-of-arrays format * that accelerates SIMD operations. Each ray is specified by an origin * point and a direction vector. */ template < typename T, Size dimension > class SIMDRay3D; //******************************************************************************** //******************************************************************************** //******************************************************************************** /// A specialization for the SIMDRay3D class that has a SIMD width of 4. /** * This class is used to store and operate on a set of 4 3D rays * in a SIMD fashion. The rays are stored in a structure-of-arrays format * that accelerates SIMD operations. Each ray is specified by an origin * point and a direction vector. */ template < typename T > class GSOUND_ALIGN(16) SIMDRay3D<T,4> { public: //******************************************************************************** //******************************************************************************** //******************************************************************************** //****** Constructors /// Create a SIMD ray with N copies of the specified ray for a SIMD width of N. GSOUND_FORCE_INLINE SIMDRay3D( const Ray3D<T>& ray ) : origin( ray.origin ), direction( ray.direction ) { } /// Create a SIMD ray with the 4 rays it contains equal to the specified rays. GSOUND_FORCE_INLINE SIMDRay3D( const Ray3D<T>& ray1, const Ray3D<T>& ray2, const Ray3D<T>& ray3, const Ray3D<T>& ray4 ) : origin( ray1.origin, ray2.origin, ray3.origin, ray4.origin ), direction( ray1.direction, ray2.direction, ray3.direction, ray4.direction ) { } //******************************************************************************** //******************************************************************************** //******************************************************************************** //****** Public Data Members /// A SIMD 3D vector indicating the origin of the ray(s). SIMDVector3D<T,4> origin; /// A SIMD 3D vector indicating the direction of the ray(s). SIMDVector3D<T,4> direction; }; //########################################################################################## //*************************** End GSound Math Namespace ********************************** GSOUND_MATH_NAMESPACE_END //****************************************************************************************** //########################################################################################## #endif // INCLUDE_GSOUND_SIMD_RAY_3D_H
[ "hkjeldsen@gmail.com" ]
hkjeldsen@gmail.com
d9fac9a95529b2f1cfc8df3d9ca5afdad23476e1
f3c9530b94b0c8829454b7ff5699a978ab04393d
/jnetpcap/builds/jnetpcap-2.0/trunk-2.0.b0001-1/src/c/packet_protocol.cpp
e0d939e98802805e30a7a4c1870be27504c9dd2b
[]
no_license
hongpingwei/jnetpcap-code
70083699858b720ebec4f1e373f4683d6bd86b9a
f271c3e3e004c7e7d7d808aa8adc25bbfe15bd2c
refs/heads/master
2021-01-11T19:57:10.823207
2015-03-19T14:33:54
2015-03-19T14:33:54
79,429,395
0
0
null
null
null
null
UTF-8
C++
false
false
39,497
cpp
/*************************************************************************** * Copyright (C) 2007, Sly Technologies, Inc * * Distributed under the Lesser GNU Public License (LGPL) * * * This file contains functions for dissecting and scanning packets. * First it defines some global tables that are used to initialize * packet_scanner. Second, two types of functions are defined in this file, * where the first scan_* is used as a scanner (wireshark term dissector), * and the second as validator of the header in validate_* function. * * The scanner function is a void function which returns its findings * by modifying the scan_t structure passed to it. The most critical * parameter being scan.length which holds the length of the header. * * The validator function is completely passive and does not modify scan_t * structure passed to it. The return value determines if validation * succeeded or failed. The validator function (validate_*) returns either * the numerical header ID of the header its validating if its a valid * header, or the constant INVALID. A table lookup is provided using 2 * functions validate and validate_next. The validate function assumes the * header is at the current offset, while validate_next validates the * header at offset + length + gap (gap is another property that determines * the number of bytes between the header and its payload, a padding of * sorts.) The result from validate_next can be directly assigned to * scan.next_id is typically how this function was designed to work. * The INVALID constant is mapped to PAYLOAD_ID constant which is a valid * catch-all header when validation failes. * * Validator function (validate_*) is also used as a heuristic determinant * for the next possible header. The main scanner loop, using * native_heuristics table (defined in this file), maintains a list of * validate functions as a heuristic check if port/type number lookup for * next header in packet fails. * * Note the function signature differences between a scan_* and validate_* * functions: * typedef void (*native_protocol_func_t)(scan_t *scan); * typedef int (*native_validate_func_t)(scan_t *scan); * * Lastly the file contains a init_native_protocols function which is * called only once during initialization phase. This is where all the * defined scan_* and validate_* functions are referenced for storage in * the lookup tables. Also a numerical ID to text lookup table is uset up * so that numerical header IDs can be mapped to text. This table is only * used for debug purposes, but none the less it is an important table * and any new protocol added must be defined in it. * ***************************************************************************/ /* * Utility file that provides various conversion methods for chaging objects * back and forth between C and Java JNI. */ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <ctype.h> #include <pcap.h> #include <jni.h> #ifndef WIN32 #include <errno.h> #include <string.h> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> #include <unistd.h> #endif /*WIN32*/ #include "packet_jscanner.h" #include "packet_protocol.h" #include "jnetpcap_utils.h" #include "nio_jmemory.h" #include "nio_jbuffer.h" #include "org_jnetpcap_protocol_JProtocol.h" #include "export.h" #include "util_debug.h" /* * Array of function pointers. These functions perform a per protocol scan * and return the next header. They also return the length of the header. * * New protocols are added in the init_native_protocol() in this file. */ native_protocol_func_t native_protocols [MAX_ID_COUNT]; native_validate_func_t native_heuristics [MAX_ID_COUNT][MAX_ID_COUNT]; native_validate_func_t validate_table [MAX_ID_COUNT]; native_debug_func_t native_debug [MAX_ID_COUNT]; native_dissect_func_t subheader_dissectors [MAX_ID_COUNT]; native_dissect_func_t field_dissectors [MAX_ID_COUNT]; const char *native_protocol_names[MAX_ID_COUNT]; #define ENTER(id, msg) #define EXIT() #define TRACE(frmt...) #define CALL(name) /* * Catch all */ void scan_not_implemented_yet(scan_t *scan) { sprintf(str_buf, "scanner (native or java) for protocol %s(%d) undefined", id2str(scan->id), scan->id); throwException(scan->env, ILLEGAL_STATE_EXCEPTION, str_buf); } /* * Scan SLL (Linux Cooked Capture) header */ void scan_sll(scan_t *scan) { ENTER(SLL_ID, "scan_sll"); register sll_t *sll = (sll_t *)(scan->buf + scan->offset); scan->length = SLL_LEN; if (is_accessible(scan, 9) == FALSE) { return; } switch(BIG_ENDIAN16(sll->sll_protocol)) { case 0x800: scan->next_id = validate_next(IP4_ID, scan); EXIT(); return; } // printf("scan_sll() next_id=%d\n", scan->next_id); // fflush(stdout); } extern void debug_rtp(rtp_t *rtp); /** * validate_rtp validates values for RTP header at current scan.offset. * * DO NOT CHANGE any scan properties. This is a completely passive method, only * the return value determines if validation passed or not. Return either * constant INVALID or header ID constant. */ int validate_rtp(scan_t *scan) { ENTER(RTP_ID, "validate_rtp"); register rtp_t *rtp = (rtp_t *)(scan->buf + scan->offset); if (rtp->rtp_ver != 2 || rtp->rtp_cc > 15 || rtp->rtp_type > 25 || rtp->rtp_seq == 0 || rtp->rtp_ts == 0 || rtp->rtp_ssrc == 0 ) { TRACE("INVALID header flad"); CALL(debug_rtp(rtp)); EXIT(); return INVALID; } uint32_t *c = (uint32_t *)(rtp + 1); for (int i = 0; i < rtp->rtp_cc; i ++) { TRACE("CSRC[%d]=0x%x", i, BIG_ENDIAN32(c[i])); if (BIG_ENDIAN32(c[i]) == 0) { TRACE("INVALID CSRC entry is 0"); EXIT(); return INVALID; } /* * Check for any duplicates CSRC ids within the table. Normally there * can't be any duplicates. */ for (int j = i + 1; j < rtp->rtp_cc; j ++) { if (BIG_ENDIAN32(c[i]) == BIG_ENDIAN32(c[j])) { TRACE("INVALID duplicates CSRC entries"); EXIT(); return INVALID; } } } if (rtp->rtp_ext) { rtpx_t * rtpx = (rtpx_t *)( scan->buf + scan->offset + RTP_LENGTH + (rtp->rtp_cc * 4)); register int xlen = BIG_ENDIAN16(rtpx->rtpx_len) * 4; if ((!SCAN_IS_FRAGMENT(scan) && (scan->offset + xlen > scan->wire_len)) || (xlen > 1500) ) { TRACE("INVALID rtpx_len > %d bytes (wire_len) in extension header", scan->wire_len); EXIT(); return INVALID; } } TRACE("OK"); EXIT(); CALL(debug_rtp(rtp)); return RTP_ID; } void debug_rtp(rtp_t *rtp) { ENTER(RTP_ID, "debug_rtp"); TRACE("struct rtp_t::" "ver=%d pad=%d ext=%d cc=%d marker=%d type=%d seq=%d ts=%d", (int) rtp->rtp_ver, (int) rtp->rtp_pad, (int) rtp->rtp_ext, (int) rtp->rtp_cc, (int) rtp->rtp_marker, (int) rtp->rtp_type, (int) BIG_ENDIAN16(rtp->rtp_seq), (int) BIG_ENDIAN32(rtp->rtp_ts) ); if (rtp->rtp_cc) { int *csrc = (int *) (rtp + 1); for (int i = 0; i < rtp->rtp_cc; i ++) { TRACE("uin32[]::" "CSRC[%d] = 0x%x", i, BIG_ENDIAN32(csrc[i])); } } if (rtp->rtp_ext) { rtpx_t *rtpx = (rtpx_t *) ((char *)(rtp + 1) + (rtp->rtp_cc * 4)); // At the end of main RTP header TRACE("struct rtpx_t::" "profile=0x%x len=%d", BIG_ENDIAN16(rtpx->rtpx_profile), BIG_ENDIAN16(rtpx->rtpx_len)); } EXIT(); } /* * Scan Session Data Protocol header */ void scan_rtp(scan_t *scan) { register rtp_t *rtp = (rtp_t *)(scan->buf + scan->offset); ACCESS(0); scan->length += RTP_LENGTH + rtp->rtp_cc * 4; /* * Check for extension. We don't care here what it is, just want to add up * all the lengths */ ACCESS(scan->length + 4); if (rtp->rtp_ext) { rtpx_t * rtpx = (rtpx_t *)(scan->buf + scan->offset + scan->length); scan->length += (BIG_ENDIAN16(rtpx->rtpx_len) * 4) + RTPX_LENGTH; } /* If RTP payload is padded, the last byte contains number of pad bytes * used. */ if (rtp->rtp_pad) { ACCESS(scan->wire_len -1); scan->hdr_postfix = scan->buf[scan->wire_len -1]; } /************************* switch (rtp->type)) { case 0: // PCMU 8K case 1: // 1016 8K case 2: // G721 8K case 3: // GSM 8K case 4: // G723 8K case 5: // DVI4 8K case 6: // DVI4 16K case 7: // LPC 8K case 8: // PCMA 8K case 9: // G722 8K case 10: // L16 44K 2CH case 11: // l16 44K 1CH case 12: // QCELP 8K case 13: // CN 8K case 14: // MPA 90K case 15: // G728 8K case 16: // DVI4 11K case 17: // DVI4 22K case 18: // G729 8K case 25: // CellB 90K case 26: // JPEG 90K case 28: // NV 90K case 31: // H261 90K case 32: // MPV 90K case 33: // MP2T 90K case 34: // H263 90K } ****************/ } /* * Scan Session Data Protocol header */ void scan_sdp(scan_t *scan) { register char *sdp = (char *)(scan->buf + scan->offset); scan->length = scan->buf_len - scan->offset; } /* * Scan Session Initiation Protocol header */ void scan_sip(scan_t *scan) { register char *sip = (char *)(scan->buf + scan->offset); packet_state_t *packet = scan->packet; /* * To calculate length we need to take it from ip header - tcp header */ char *buf = scan->buf; header_t tcph = packet->pkt_headers[packet->pkt_header_count -1]; register int size = tcph.hdr_payload; scan->length = size; #ifdef DEBUG char b[32]; b[0] = '\0'; b[31] = '\0'; strncpy(b, sip, (size <= 31)? size : 31); if (size < 10) printf("scan_sip(): #%d INVALID size=%d sip=%s\n", (int) scan->packet->pkt_frame_num, size, b); #endif char * content_type = NULL; /* * We could use strstr(), but for efficiency and since we need to lookup * multiple sub-strings in the text header, we use our own loop. */ for (int i = 0; i < size; i ++){ if ((sip[i] == 'c' || sip[i] == 'C') && strncmp(&sip[i], "Content-Type:", 13)) { content_type = &sip[i + 13]; } if (sip[i] == '\r' && sip[i + 1] == '\n' && sip[i + 2] == '\r' && sip[i + 3] == '\n') { scan->length = i + 4; break; } } if (content_type == NULL) { scan->next_id = PAYLOAD_ID; return; } char *end = &sip[scan->length - 15]; /* Skip whitespace and prevent runaway search */ while (isspace(*content_type) && (content_type < end)) { content_type ++; } if (strncmp(content_type, "application/sdp", 15)) { scan->next_id = validate_next(SDP_ID, scan); return; } return; } /** * validate_sip validates values for SIP header at current scan.offset. * * DO NOT CHANGE any scan properties. This is a completely passive method, only * the return value determines if validation passed or not. Return either * constant INVALID or header ID constant. */ int validate_sip(scan_t *scan) { char *sip = (char *)(scan->buf + scan->offset); packet_state_t *packet = scan->packet; /* * To calculate length we need to take it from ip header - tcp header */ char *buf = scan->buf; header_t tcph = packet->pkt_headers[packet->pkt_header_count -1]; int size = tcph.hdr_payload; /* First sanity check if we have printable chars */ if (size < 5 || (isprint(sip[0]) && isprint(sip[1]) && isprint(sip[2])) == FALSE) { #ifdef DEBUG char b[32]; b[0] = '\0'; b[31] = '\0'; strncpy(b, sip, (size <= 31)? size : 31); printf("validate_sip(): UNMATCHED size=%d sip=%s\n", size, b); #endif return INVALID; } if ( /* SIP Response */ strncmp(sip, "SIP", 3) == 0 || /* SIP Requests */ strncmp(sip, "REGISTER", 8) == 0 || strncmp(sip, "INVITE", 6) == 0 || strncmp(sip, "ACK", 3) == 0 || strncmp(sip, "CANCEL", 6) == 0 || strncmp(sip, "BYE", 3) == 0 || strncmp(sip, "OPTIONS", 7) == 0 ) { #ifndef DEBUG char b[32]; b[0] = '\0'; b[31] = '\0'; strncpy(b, sip, (size <= 31)? size : 31); if (size < 10) printf("validate_sip(): #%d INVALID size=%d sip=%s\n", (int) scan->packet->pkt_frame_num, size, b); #endif return SIP_ID; } return INVALID; } /* * Scan Hyper Text Markup Language header */ void scan_html(scan_t *scan) { scan->length = scan->buf_len - scan->offset; } /* * Scan Hyper Text Transmission Protocol header */ void scan_http(scan_t *scan) { register char *http = (char *)(scan->buf + scan->offset); packet_state_t *packet = scan->packet; /* * To calculate length we need to take it from ip header - tcp header */ char *buf = scan->buf; header_t tcph = packet->pkt_headers[packet->pkt_header_count -1]; register int size = tcph.hdr_payload; scan->length = size; #ifdef DEBUG char b[32]; b[0] = '\0'; b[31] = '\0'; strncpy(b, http, (size <= 31)? size : 31); if (size < 10) printf("scan_http(): #%d INVALID size=%d http=%s\n", (int) scan->packet->pkt_frame_num, size, b); #endif for (int i = 0; i < size; i ++){ if (http[i] == '\r' && http[i + 1] == '\n' && http[i + 2] == '\r' && http[i + 3] == '\n') { scan->length = i + 4; break; } } return; } /** * Validate HTTP header values at current scan.offset. * * DO NOT CHANGE any scan properties. This is a completely passive method, only * the return value determines if validation passed or not. Return either * constant INVALID or header ID constant. */ int validate_http(scan_t *scan) { char *http = (char *)(scan->buf + scan->offset); packet_state_t *packet = scan->packet; /* * To calculate length we need to take it from ip header - tcp header */ char *buf = scan->buf; header_t tcph = packet->pkt_headers[packet->pkt_header_count -1]; int size = tcph.hdr_payload; /* First sanity check if we have printable chars */ if (size < 5 || (isprint(http[0]) && isprint(http[1]) && isprint(http[2])) == FALSE) { #ifdef DEBUG char b[32]; b[0] = '\0'; b[31] = '\0'; strncpy(b, http, (size <= 31)? size : 31); printf("scan_http(): UNMATCHED size=%d http=%s\n", size, b); #endif return INVALID; } if ( /* HTTP Response */ strncmp(http, "HTTP", 4) == 0 || /* HTTP Requests */ strncmp(http, "GET", 3) == 0 || strncmp(http, "OPTIONS", 7) == 0 || strncmp(http, "HEAD", 4) == 0 || strncmp(http, "POST", 4) == 0 || strncmp(http, "PUT", 3) == 0 || strncmp(http, "DELETE", 6) == 0 || strncmp(http, "TRACE", 5) == 0 || strncmp(http, "CONNECT", 7 == 0) ) { #ifndef DEBUG char b[32]; b[0] = '\0'; b[31] = '\0'; strncpy(b, http, (size <= 31)? size : 31); if (size < 10) printf("scan_http(): #%d INVALID size=%d http=%s\n", (int) scan->packet->pkt_frame_num, size, b); #endif return HTTP_ID; } return INVALID; } /* * Scan Internet Control Message Protocol header */ void scan_icmp(scan_t *scan) { icmp_t *icmp = (icmp_t *)(scan->buf + scan->offset); switch (icmp->type) { case 3: // UNREACHABLE case 12: // PARAM PROBLEM scan->length = sizeof(icmp_t) + 4; scan->next_id = validate_next(IP4_ID, scan); scan->flags |= HEADER_FLAG_IGNORE_BOUNDS; // Needed for encapsulated Ip4 break; case 0: // Echo Reply case 8: // Echo Request case 4: case 5: case 11: case 13: case 14: case 15: case 16: default: // scan->length = scan->buf_len - scan->offset; scan->length = 8; break; } } /* * Scan Point to Point protocol */ void scan_ppp(scan_t *scan) { ppp_t *ppp = (ppp_t *)(scan->buf + scan->offset); scan->length = sizeof(ppp_t); switch (BIG_ENDIAN16(ppp->protocol)) { case 0x0021: scan->next_id = validate_next(IP4_ID, scan); break; case 0x0057: scan->next_id = validate_next(IP6_ID, scan); break; } } /* * Scan Layer 2 Tunneling Protocol header */ void scan_l2tp(scan_t *scan) { l2tp_t *l2tp = (l2tp_t *)(scan->buf + scan->offset); scan->length = 6; if (l2tp->l == 1) { scan->length += 2; } if (l2tp->s == 1) { scan->length += 4; } if (l2tp->o == 1) { scan->length += 4; } #ifdef DEBUG printf("scan() lL2TP_ID: b[0]=%d t=%d\n", (int)*(scan->buf + scan->offset), l2tp->t); fflush(stdout); #endif if (l2tp->t == 0) { scan->next_id = validate_next(PPP_ID, scan); } } /* * Scan IEEE 802.1q VLAN tagging header */ void scan_vlan(scan_t *scan) { vlan_t *vlan = (vlan_t *)(scan->buf + scan->offset); scan->length = sizeof(vlan_t); scan->next_id = validate_next(lookup_ethertype(vlan->type), scan); if (scan->next_id == PAYLOAD_ID) { scan->next_id = validate_next(IEEE_802DOT2_ID, scan); } } /* * Scan IEEE 802.2 or LLC2 header */ void scan_llc(scan_t *scan) { llc_t *llc = (llc_t *) (scan->buf + scan->offset); if (llc->control & 0x3 == 0x3) { scan->length = 3; } else { scan->length = 4; } switch (llc->dsap) { case 0xaa: scan->next_id = validate_next(IEEE_SNAP_ID, scan); break; } } /* * Scan IEEE SNAP header */ void scan_snap(scan_t *scan) { snap_t *snap = (snap_t *) (scan->buf + scan->offset); char *b = (char *) snap; scan->length = 5; /* * Set the flow key pair for SNAP. * First, we check if SNAP has already been set by looking in the * flow_key_t and checking if SNAP has previously been processed */ if ((scan->packet->pkt_flow_key.header_map & (1L << IEEE_SNAP_ID)) == 0) { scan->packet->pkt_flow_key.header_map |= (1L << IEEE_SNAP_ID); /* * Ip4 always takes up pair[1] * pair[1] is next protocol in on both sides of the pair */ scan->packet->pkt_flow_key.pair_count = 2; scan->packet->pkt_flow_key.forward_pair[1][0] = BIG_ENDIAN16(snap->pid); scan->packet->pkt_flow_key.forward_pair[1][1] = BIG_ENDIAN16(snap->pid); scan->packet->pkt_flow_key.id[1] = IEEE_SNAP_ID; } switch (BIG_ENDIAN32(snap->oui)) { case 0x0000f8: // OUI_CISCO_90 case 0: scan->next_id = validate_next(lookup_ethertype(*(uint16_t *)(b + 3)), scan); break; } } /* * Scan TCP header */ void scan_tcp(scan_t *scan) { tcp_t *tcp = (tcp_t *) (scan->buf + scan->offset); scan->length = tcp->doff * 4; /* * Set the flow key pair for Tcp. * First, we check if Tcp has already been set by looking in the * flow_key_t and checking if Tcp has previously been processed */ if ((scan->packet->pkt_flow_key.header_map & (1L << TCP_ID)) == 0) { scan->packet->pkt_flow_key.header_map |= (1L << TCP_ID); /* * Tcp takes up one pair * pair[0] is tcp source and destination ports */ int count = scan->packet->pkt_flow_key.pair_count++; scan->packet->pkt_flow_key.forward_pair[count][0] = BIG_ENDIAN16(tcp->sport); scan->packet->pkt_flow_key.forward_pair[count][1] = BIG_ENDIAN16(tcp->dport); scan->packet->pkt_flow_key.id[count] = TCP_ID; scan->packet->pkt_flow_key.flags |= FLOW_KEY_FLAG_REVERSABLE_PAIRS; #ifdef DEBUG printf("scan_tcp(): count=%d map=0x%lx\n", scan->packet->pkt_flow_key.pair_count, scan->packet->pkt_flow_key.header_map ); fflush(stdout); #endif } switch (BIG_ENDIAN16(tcp->dport)) { case 80: case 8080: case 8081: scan->next_id = validate_next(HTTP_ID, scan); return; case 5060: scan->next_id = validate_next(SIP_ID, scan); return; } switch (BIG_ENDIAN16(tcp->sport)) { case 80: case 8080: case 8081: scan->next_id = validate_next(HTTP_ID, scan); return; case 5060: scan->next_id = validate_next(SIP_ID, scan); return; } } void debug_udp(udp_t *udp) { debug_enter("debug_udp"); debug_trace("struct udp_t", "sport=%d dport=%d len=%d crc=0x%x", (int) BIG_ENDIAN16(udp->sport), (int) BIG_ENDIAN16(udp->dport), (int) BIG_ENDIAN16(udp->length), (int) BIG_ENDIAN16(udp->checksum) ); debug_exit("debug_udp"); } /* * Scan UDP header */ void scan_udp(scan_t *scan) { udp_t *udp = (udp_t *) (scan->buf + scan->offset); scan->length = sizeof(udp_t); /* * Set the flow key pair for Udp. * First, we check if Udp has already been set by looking in the * flow_key_t and checking if Udp has previously been processed */ if ((scan->packet->pkt_flow_key.header_map & (1L << UDP_ID)) == 0) { scan->packet->pkt_flow_key.header_map |= (1L << UDP_ID); /* * Tcp takes up one pair * pair[0] is tcp source and destination ports */ int count = scan->packet->pkt_flow_key.pair_count++; scan->packet->pkt_flow_key.forward_pair[count][0] = BIG_ENDIAN16(udp->sport); scan->packet->pkt_flow_key.forward_pair[count][1] = BIG_ENDIAN16(udp->dport); scan->packet->pkt_flow_key.id[count] = UDP_ID; scan->packet->pkt_flow_key.flags |= FLOW_KEY_FLAG_REVERSABLE_PAIRS; } switch (BIG_ENDIAN16(udp->dport)) { case 1701: scan->next_id = validate_next(L2TP_ID, scan); return; // case 5060: scan->next_id = validate_next(SIP_ID, scan); return; case 5004: scan->next_id = validate_next(RTP_ID, scan); return; } switch (BIG_ENDIAN16(udp->sport)) { case 1701: scan->next_id = validate_next(L2TP_ID, scan); return; // case 5060: scan->next_id = validate_next(SIP_ID, scan); return; case 5004: scan->next_id = validate_next(RTP_ID, scan); return; } } /* * Scan Address Resolution Protocol header */ void scan_arp(scan_t *scan) { arp_t *arp = (arp_t *)(scan->buf + scan->offset); scan->length = (arp->hlen + arp->plen) * 2 + 8; } /* * Scan IP version 6 */ void scan_ip6(scan_t *scan) { ip6_t *ip6 = (ip6_t *)(scan->buf + scan->offset); scan->length = IP6_HEADER_LENGTH; scan->hdr_payload = BIG_ENDIAN16(ip6->ip6_plen); uint8_t *buf = (uint8_t *)(scan->buf + scan->offset + sizeof(ip6_t)); if(is_accessible(scan, 40) == FALSE) { return; } /* * Set the flow key pair for Ip6. * First, we check if Ip6 has already been set by looking in the * flow_key_t and checking if it has been previously been processed */ if ((scan->packet->pkt_flow_key.header_map & (1L << IP6_ID)) == 0) { scan->packet->pkt_flow_key.header_map |= (1L << IP6_ID); /* * Ip6 always takes up 2 pairs * pair[0] is hash of addresses * pair[1] is next protocol in on both sides of the pair * */ register uint32_t t; scan->packet->pkt_flow_key.pair_count = 2; t = *(uint32_t *)&ip6->ip6_src[0] ^ *(uint32_t *)&ip6->ip6_src[4] ^ *(uint32_t *)&ip6->ip6_src[8] ^ *(uint32_t *)&ip6->ip6_src[12]; scan->packet->pkt_flow_key.forward_pair[0][0] = t; t = *(uint32_t *)&ip6->ip6_dst[0] ^ *(uint32_t *)&ip6->ip6_dst[4] ^ *(uint32_t *)&ip6->ip6_dst[8] ^ *(uint32_t *)&ip6->ip6_dst[12]; scan->packet->pkt_flow_key.forward_pair[0][1] = t; scan->packet->pkt_flow_key.forward_pair[1][0] = ip6->ip6_nxt; scan->packet->pkt_flow_key.forward_pair[1][1] = ip6->ip6_nxt; scan->packet->pkt_flow_key.id[0] = IP6_ID; scan->packet->pkt_flow_key.id[1] = IP6_ID; } int type = ip6->ip6_nxt; int len; #ifdef DEBUG printf("#%d scan_ip6() type=%d (0x%x)\n", (int)scan->packet->pkt_frame_num, type, type); fflush(stdout); #endif again: switch (type) { case 1: scan->next_id = validate_next(ICMP_ID, scan); break; case 4: scan->next_id = validate_next(IP4_ID, scan); break; case 6: scan->next_id = validate_next(TCP_ID, scan); break; case 17:scan->next_id = validate_next(UDP_ID, scan); break; case 58:scan->next_id = validate_next(PAYLOAD_ID, scan); break; // ICMPv6 not implemented yet /* Ip6 Options - see RFC2460 */ case 44: // Fragment Header /* If we are a fragment, we just set the FRAG flag and pass through */ scan->flags |= CUMULATIVE_FLAG_HEADER_FRAGMENTED; case 0: // Hop-by-hop options (has special processing) case 60: // Destination Options (with routing options) case 43: // Routing header case 51: // Authentication Header case 50: // Encapsulation Security Payload Header case 135: // Mobility Header if (is_accessible(scan, scan->length + 2) == FALSE) { return; } /* Skips over all option headers */ type = (int) *(buf + 0); // Option type len = ((int) *(buf + 1)) * 8 + 8; // Option length if (is_accessible(scan, scan->offset + len) == FALSE) { // Catch all just in case #ifdef DEBUG printf("#%ld scan_ip6() infinite loop detected. Option type=%d len=%d offset=%d\n", scan->packet->pkt_frame_num, type, len, scan->offset); fflush(stdout); #endif scan->next_id = PAYLOAD_ID; break; } scan->length += len; scan->hdr_payload -= len; // Options are part of the main payload length buf += len; #ifdef DEBUG printf("#%d scan_ip6() OPTION type=%d (0x%x) len=%d\n", (int)scan->packet->pkt_frame_num, type, type, len); fflush(stdout); #endif goto again; case 59: // No next header default: if (scan->hdr_payload == 0) { scan->next_id = END_OF_HEADERS; } else { scan->next_id = PAYLOAD_ID; } break; } } inline header_t *get_subheader_storage(scanner_t *scanner, int min) { /* Check if we need to wrap */ if ((scanner->sc_subindex + min) * sizeof(header_t) >= scanner->sc_sublen) { scanner->sc_subindex = 0; } return &scanner->sc_subheader[scanner->sc_subindex]; } void debug_ip4(ip4_t *ip) { debug_enter("debug_ip4"); int flags = BIG_ENDIAN16(ip->frag_off); debug_trace("struct ip4_t", "ver=%d hlen=%d tot_len=%d flags=0x%x(%s%s%s) protocol=%d", (int) ip->version, (int) ip->ihl, (int) BIG_ENDIAN16(ip->tot_len), (int) flags >> 13, ((flags & IP4_FLAG_RESERVED)?"R":""), ((flags & IP4_FLAG_DF)?"D":""), ((flags & IP4_FLAG_MF)?"M":""), (int) ip->protocol); debug_exit("debug_ip4"); } void dissect_ip4_headers(dissect_t *dissect) { uint8_t *buf = (dissect->d_buf + dissect->d_offset); ip4_t *ip = (ip4_t *) buf; if (ip->ihl == 5) { return; // No options } header_t *header = dissect->d_header; header->hdr_flags |= HEADER_FLAG_SUBHEADERS_DISSECTED; scanner_t *scanner = dissect->d_scanner; int end = ip->ihl * 4; // End of IP header int len = 0; // Length of current option header_t *sub; sub = header->hdr_subheader = get_subheader_storage(scanner, 10); for (int offset = 20; offset < end;) { int id = buf[offset] & 0x1F; sub->hdr_id = id; // Id is same as Ip4 spec switch (id) { case 0: // End of Option List - setup as header gap len = end - offset; header->hdr_gap = len; header->hdr_length -= len; break; case 1: // NoOp offset ++; break; case 2: // Security case 3: // Loose Source Route case 4: // Timestamp case 7: // Record Route case 8: // Stream ID case 9: // Strick Source Route len = buf[offset + 1]; /* Use offset into the Ip4 header not the packetoffset */ sub = &scanner->sc_subheader[scanner->sc_subindex++]; // Our subheader sub->hdr_offset = offset; sub->hdr_length = len; sub->hdr_subcount = 0; sub->hdr_subheader = NULL; break; } } } /* * Scan IP version 4 */ void scan_ip4(register scan_t *scan) { register ip4_t *ip4 = (ip4_t *) (scan->buf + scan->offset); scan->length = ip4->ihl * 4; scan->hdr_payload = BIG_ENDIAN16(ip4->tot_len) - scan->length; if (is_accessible(scan, 8) == FALSE) { return; } /* Check if this IP packet is a fragment and record in flags */ int frag = BIG_ENDIAN16(ip4->frag_off); if (frag & IP4_FLAG_MF || (frag & IP4_FRAG_OFF_MASK > 0)) { scan->flags |= CUMULATIVE_FLAG_HEADER_FRAGMENTED; /* Adjust payload length for a fragment */ scan->hdr_payload = scan->buf_len - scan->length - scan->offset; } #ifdef DEBUG printf("ip4->frag_off=%x\n", frag); fflush(stdout); #endif if (is_accessible(scan, 16) == FALSE) { return; } /* * Set the flow key pair for Ip4. * First, we check if Ip4 has already been set by looking in the * flow_key_t and checking if Ip4 has previously been processed */ if ((scan->packet->pkt_flow_key.header_map & (1L << IP4_ID)) == 0) { scan->packet->pkt_flow_key.header_map |= (1L << IP4_ID); /* * Ip4 always takes up pair[0] and pair[1] * pair[0] is Ip addresses * pair[1] is next protocol in on both sides of the pair */ scan->packet->pkt_flow_key.pair_count = 2; scan->packet->pkt_flow_key.forward_pair[0][0] = BIG_ENDIAN32(ip4->saddr); scan->packet->pkt_flow_key.forward_pair[0][1] = BIG_ENDIAN32(ip4->daddr); scan->packet->pkt_flow_key.forward_pair[1][0] = ip4->protocol; scan->packet->pkt_flow_key.forward_pair[1][1] = ip4->protocol; scan->packet->pkt_flow_key.id[0] = IP4_ID; scan->packet->pkt_flow_key.id[1] = IP4_ID; } #ifdef DEBUG printf("scan_ip4(): type=%d frag_off=%d @ frag_off.pos=%X\n", ip4->protocol, BIG_ENDIAN16(ip4->frag_off) & IP4_FRAG_OFF_MASK, (int)((char *)&ip4->frag_off - scan->buf)); fflush(stdout); #endif if ( (BIG_ENDIAN16(ip4->frag_off) & IP4_FRAG_OFF_MASK) != 0) { scan->next_id = PAYLOAD_ID; return; } switch (ip4->protocol) { case 1: scan->next_id = validate_next(ICMP_ID, scan); break; case 4: scan->next_id = validate_next(IP4_ID, scan); break; case 6: scan->next_id = validate_next(TCP_ID, scan); break; case 17:scan->next_id = validate_next(UDP_ID, scan); break; case 115: scan->next_id = validate_next(L2TP_ID, scan); break; // case 1: // ICMP // case 2: // IGMP // case 6: // TCP // case 8: // EGP // case 9: // IGRP // case 17: // UDP // case 41: // Ip6 over Ip4 // case 46: // RSVP // case 47: // GRE // case 58: // ICMPv6 // case 89: // OSPF // case 90: // MOSPF // case 97: // EtherIP // case 132: // SCTP, Stream Control Transmission Protocol // case 137: // MPLS in IP } } /* * Scan IEEE 802.3 ethernet */ void scan_802dot3(scan_t *scan) { ethernet_t *eth = (ethernet_t *) (scan->buf + scan->offset); scan->length = sizeof(ethernet_t); if (is_accessible(scan, 14) == FALSE) { return; } if (BIG_ENDIAN16(eth->type) >= 0x600) { // We have an Ethernet frame scan->id = ETHERNET_ID; scan->next_id = validate_next(lookup_ethertype(eth->type), scan); return; } else { scan->next_id = validate_next(IEEE_802DOT2_ID, scan); // LLC v2 } if (is_accessible(scan, 12) == FALSE) { return; } /* * Set the flow key pair for Ethernet. * First, we check if Ethernet has already been set by looking in the * flow_key_t and checking if it has been previously been processed */ if ((scan->packet->pkt_flow_key.header_map & (1L << IEEE_802DOT3_ID)) == 0) { scan->packet->pkt_flow_key.header_map |= (1L << IEEE_802DOT3_ID); /* * Ethernet always takes up 2 pairs * pair[0] is hash of addresses * pair[1] is next protocol in on both sides of the pair * * Our hash takes the last 4 bytes of address literally and XORs the * remaining bytes with first 2 bytes */ register uint32_t t; scan->packet->pkt_flow_key.pair_count = 1; t = *(uint32_t *)&eth->dhost[2] ^ (*(uint16_t *)&eth->dhost[0]); scan->packet->pkt_flow_key.forward_pair[0][0] = t; t = *(uint32_t *)&eth->shost[2] ^ (*(uint16_t *)&eth->shost[0]); scan->packet->pkt_flow_key.forward_pair[0][1] = t; scan->packet->pkt_flow_key.id[0] = IEEE_802DOT3_ID; } } /* * Scan ethertype */ void scan_ethernet(scan_t *scan) { ethernet_t *eth = (ethernet_t *) (scan->buf + scan->offset); scan->length = sizeof(ethernet_t); if (is_accessible(scan, 12) == FALSE) { return; } /* * Set the flow key pair for Ethernet. * First, we check if Ethernet has already been set by looking in the * flow_key_t and checking if it has been previously been processed */ if ((scan->packet->pkt_flow_key.header_map & (1L << ETHERNET_ID)) == 0) { scan->packet->pkt_flow_key.header_map |= (1L << ETHERNET_ID); /* * Ethernet always takes up 2 pairs * pair[0] is hash of addresses * pair[1] is next protocol in on both sides of the pair * * Our hash takes the last 4 bytes of address literally and XORs the * remaining bytes with first 2 bytes */ register uint32_t t; scan->packet->pkt_flow_key.pair_count = 2; t = *(uint32_t *)&eth->dhost[2] ^ (*(uint16_t *)&eth->dhost[0]); scan->packet->pkt_flow_key.forward_pair[0][0] = t; t = *(uint32_t *)&eth->shost[2] ^ (*(uint16_t *)&eth->shost[0]); scan->packet->pkt_flow_key.forward_pair[0][1] = t; scan->packet->pkt_flow_key.forward_pair[1][0] = eth->type; scan->packet->pkt_flow_key.forward_pair[1][1] = eth->type; scan->packet->pkt_flow_key.id[0] = ETHERNET_ID; scan->packet->pkt_flow_key.id[1] = ETHERNET_ID; } if (is_accessible(scan, 14) == FALSE) { return; } if (BIG_ENDIAN16(eth->type) < 0x600) { // We have an IEEE 802.3 frame scan->id = IEEE_802DOT3_ID; scan->next_id = validate_next(IEEE_802DOT2_ID, scan); // LLC v2 } else { scan->next_id = validate_next(lookup_ethertype(eth->type), scan); } } /* * Payload is what's left over in the packet when no more header can be * identified. */ void scan_payload(scan_t *scan) { scan->id = PAYLOAD_ID; scan->next_id = END_OF_HEADERS; scan->length = scan->buf_len - scan->offset; } /** * Validates the protocol with ID by advancing offset to next header. * If a validation function is not found, INVALID is returned. Offset is * restored to original value before this method retuns. */ int validate_next(register int id, register scan_t *scan) { register native_validate_func_t validate_func = validate_table[id]; if (validate_func == NULL) { return id; } int saved_offset = scan->offset; scan->offset += scan->length + scan->hdr_gap; int result = validate_func(scan); scan->offset = saved_offset; return result; } /** * Validates the protocol with ID. If a validation function is not found, * INVALID is returned. */ int validate(register int id, register scan_t *scan) { register native_validate_func_t validate_func = validate_table[id]; if (validate_func == NULL) { return id; } return validate_func(scan); } int lookup_ethertype(uint16_t type) { // printf("type=0x%x\n", BIG_ENDIAN16(type)); switch (BIG_ENDIAN16(type)) { case 0x0800: return IP4_ID; case 0x0806: return ARP_ID; case 0x86DD: return IP6_ID; case 0x8100: return IEEE_802DOT1Q_ID; } return PAYLOAD_ID; } /**************************************************************** * ************************************************************** * * NON Java declared native functions. Private scan function * * ************************************************************** ****************************************************************/ void init_native_protocols() { /* * Initialize the inmemory tables */ memset(native_protocols, 0, MAX_ID_COUNT * sizeof(native_protocol_func_t)); memset(native_heuristics, 0, MAX_ID_COUNT * MAX_ID_COUNT * sizeof(native_validate_func_t)); memset(validate_table, 0, MAX_ID_COUNT * sizeof(native_validate_func_t)); memset(native_debug, 0, MAX_ID_COUNT * sizeof(native_debug_func_t)); // Builtin families native_protocols[PAYLOAD_ID] = &scan_payload; // Datalink families native_protocols[ETHERNET_ID] = &scan_ethernet; native_protocols[IEEE_802DOT2_ID] = &scan_llc; native_protocols[IEEE_SNAP_ID] = &scan_snap; native_protocols[IEEE_802DOT1Q_ID] = &scan_vlan; native_protocols[L2TP_ID] = &scan_l2tp; native_protocols[PPP_ID] = &scan_ppp; native_protocols[IEEE_802DOT3_ID] = &scan_802dot3; native_protocols[SLL_ID] = &scan_sll; // TCP/IP families native_protocols[IP4_ID] = &scan_ip4; native_protocols[IP6_ID] = &scan_ip6; native_protocols[UDP_ID] = &scan_udp; native_protocols[TCP_ID] = &scan_tcp; native_protocols[ICMP_ID] = &scan_icmp; native_protocols[HTTP_ID] = &scan_http; native_protocols[HTML_ID] = &scan_html; native_protocols[ARP_ID] = &scan_arp; // Voice and Video native_protocols[SIP_ID] = &scan_sip; native_protocols[SDP_ID] = &scan_sdp; native_protocols[RTP_ID] = &scan_rtp; /* * Validation function table. This isn't the list of bindings, but 1 per * protocol. Used by validate(scan) function. */ validate_table[HTTP_ID] = &validate_http; validate_table[SIP_ID] = &validate_sip; validate_table[RTP_ID] = &validate_rtp; /* * Heuristic bindings (guesses) to protocols. Used by main scan loop to * check heuristic bindings. */ native_heuristics[TCP_ID][0] = &validate_http; native_heuristics[TCP_ID][1] = &validate_sip; native_heuristics[UDP_ID][0] = &validate_rtp; native_heuristics[UDP_ID][1] = &validate_sip; /* * Dissector tables. Dissection == discovery of optional fields and * sub-headers. */ subheader_dissectors[IP4_ID] = &dissect_ip4_headers; // field_dissectors[IP4_ID] = &dissect_ip4_fields; /* * Debug trace functions for some protocols. Debug trace functions are * optional and provide a low-level dump of the header values and possibly * other related information used for debugging. The dump is performed using * debug_trace() calls. */ native_debug[IP4_ID] = (native_debug_func_t) debug_ip4; native_debug[UDP_ID] = (native_debug_func_t) debug_udp; native_debug[RTP_ID] = (native_debug_func_t) debug_rtp; /* * Now store the names of each header, used for debuggin purposes */ native_protocol_names[PAYLOAD_ID] = "PAYLOAD"; native_protocol_names[ETHERNET_ID] = "ETHERNET"; native_protocol_names[TCP_ID] = "TCP"; native_protocol_names[UDP_ID] = "UDP"; native_protocol_names[IEEE_802DOT3_ID] = "802DOT3"; native_protocol_names[IEEE_802DOT2_ID] = "802DOT2"; native_protocol_names[IEEE_SNAP_ID] = "SNAP"; native_protocol_names[IP4_ID] = "IP4"; native_protocol_names[IP6_ID] = "IP6"; native_protocol_names[IEEE_802DOT1Q_ID] = "802DOT1Q"; native_protocol_names[L2TP_ID] = "L2TP"; native_protocol_names[PPP_ID] = "PPP"; native_protocol_names[ICMP_ID] = "ICMP"; native_protocol_names[HTTP_ID] = "HTTP"; native_protocol_names[HTML_ID] = "HTML"; native_protocol_names[ARP_ID] = "ARP"; native_protocol_names[SIP_ID] = "SIP"; native_protocol_names[SDP_ID] = "SDP"; native_protocol_names[RTP_ID] = "RTP"; native_protocol_names[SLL_ID] = "SLL"; // Initialize debug loggers #ifdef DEBUG // for (int i = 0; i < MAX_ID_COUNT; i ++) { // protocol_loggers[i] = new Debug(id2str(i), &protocol_logger); // } #endif }
[ "voytechs@905ad56a-9210-0410-a722-a9c141187570" ]
voytechs@905ad56a-9210-0410-a722-a9c141187570
25beb2e6b421d89f1b40a3446c0bf82c07a2bb93
2e8f8aea30c4d5e30d155a815f649cc605759926
/exemplo_utilizacao_LCD_2/exemplo_utilizacao_LCD_2.ino
8c624fb5fa13a5a471a0fc69fd81c6e15474f6fa
[]
no_license
wsurkamp/Projects_arduino
9820bb976882465ee8fcaa09e9536d431cabe486
84f6dc9ebb1394743e89ea1d3171317d8a8e4890
refs/heads/master
2021-01-10T01:53:30.205191
2015-12-11T05:23:32
2015-12-11T05:23:32
45,489,691
0
0
null
null
null
null
UTF-8
C++
false
false
406
ino
#include <LiquidCrystal.h> LiquidCrystal lcd(12,11,5,4,3,2); int incomingByte, x, y; void setup(){ lcd.begin(16,2); Serial.begin(9600); } void loop(){ if (Serial.available() > 0){ incomingByte = Serial.read(); lcd.print(char(incomingByte)); x++; y++; if (x > 15){ lcd.setCursor(0,1); x = 0; } if (y > 31){ lcd.setCursor(0,0); y = 0; } } }
[ "christianwkamp1@gmail.com" ]
christianwkamp1@gmail.com
6f77b9d63188c578a13fdad008731285ddeaa722
90c95fd7a5687b1095bf499892b8c9ba40f59533
/sprout/compost/effects/compressed.hpp
739d55bc56f9748eb648c0707d18cb7a1b446919
[ "BSL-1.0" ]
permissive
CreativeLabs0X3CF/Sprout
af60a938fd12e8439a831d4d538c4c48011ca54f
f08464943fbe2ac2030060e6ff20e4bb9782cd8e
refs/heads/master
2021-01-20T17:03:24.630813
2016-08-15T04:44:46
2016-08-15T04:44:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,142
hpp
/*============================================================================= Copyright (c) 2011-2016 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout 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 SPROUT_COMPOST_EFFECTS_COMPRESEDS_HPP #define SPROUT_COMPOST_EFFECTS_COMPRESEDS_HPP #include <sprout/config.hpp> #include <sprout/utility/forward.hpp> #include <sprout/range/adaptor/transformed.hpp> namespace sprout { namespace compost { namespace detail { template<typename Value, typename T> SPROUT_CONSTEXPR T compress_value(T const& x, Value const& threshold, Value const& ratio, Value const& gain) { return (x > threshold ? threshold + (x - threshold) * ratio : x < -threshold ? -threshold + (x + threshold) * ratio : x ) * gain ; } } // namespace detail // // compress_value // template<typename Value, typename T = void> struct compress_value { public: typedef Value value_type; typedef T argument_type; typedef T result_type; private: value_type threshold_; value_type ratio_; value_type gain_; public: SPROUT_CONSTEXPR compress_value(Value const& threshold, Value const& ratio) : threshold_(threshold), ratio_(ratio), gain_(1 / (threshold + (1 - threshold) * ratio)) {} SPROUT_CONSTEXPR result_type operator()(T const& x) const { return sprout::compost::detail::compress_value(x, threshold_, ratio_, gain_); } }; template<typename Value> struct compress_value<Value, void> { public: typedef Value value_type; private: value_type threshold_; value_type ratio_; value_type gain_; public: SPROUT_CONSTEXPR compress_value(Value const& threshold, Value const& ratio) : threshold_(threshold), ratio_(ratio), gain_(1 / (threshold + (1 - threshold) * ratio)) {} template<typename T> SPROUT_CONSTEXPR T operator()(T const& x) const { return sprout::compost::detail::compress_value(x, threshold_, ratio_, gain_); } }; namespace effects { // // compress_holder // template<typename T> class compress_holder { public: typedef T value_type; private: value_type threshold_; value_type ratio_; public: SPROUT_CONSTEXPR compress_holder() SPROUT_DEFAULTED_DEFAULT_CONSTRUCTOR_DECL compress_holder(compress_holder const&) = default; SPROUT_CONSTEXPR compress_holder(value_type const& threshold, value_type const& ratio) : threshold_(threshold), ratio_(ratio) {} SPROUT_CONSTEXPR value_type const& threshold() const { return threshold_; } SPROUT_CONSTEXPR value_type const& ratio() const { return ratio_; } }; // // compressed_forwarder // class compressed_forwarder { public: template<typename T> SPROUT_CONSTEXPR sprout::compost::effects::compress_holder<T> operator()(T const& threshold, T const& ratio) const { return sprout::compost::effects::compress_holder<T>(threshold, ratio); } }; // // compressed // namespace { SPROUT_STATIC_CONSTEXPR sprout::compost::effects::compressed_forwarder compressed = {}; } // anonymous-namespace // // operator| // template<typename Range, typename T> inline SPROUT_CONSTEXPR auto operator|(Range&& lhs, sprout::compost::effects::compress_holder<T> const& rhs) -> decltype( SPROUT_FORWARD(Range, lhs) | sprout::adaptors::transformed(sprout::compost::compress_value<T>(rhs.threshold(), rhs.ratio())) ) { return SPROUT_FORWARD(Range, lhs) | sprout::adaptors::transformed(sprout::compost::compress_value<T>(rhs.threshold(), rhs.ratio())) ; } } // namespace effects using sprout::compost::effects::compressed; } // namespace compost } // namespace sprout #endif // #ifndef SPROUT_COMPOST_EFFECTS_COMPRESEDS_HPP
[ "bolero.murakami@gmail.com" ]
bolero.murakami@gmail.com
5f3820b18d5fa43ac832ca7e626552fadce45d3c
cf086a1895e22c9ecb6841a71def0f43a18a004e
/libraries/db/include/graphene/db/fwd.hpp
1737c8322e7d6ae63b544506f30795fb42d8988e
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
justshabir/VINchain-blockchain
95de7c4547043185c800f526d20802f88dcecfe6
c52ec3bf67c6d4700bbaf5ec903185d31a2d63ec
refs/heads/master
2022-02-28T23:28:45.551508
2019-10-27T12:08:01
2019-10-27T12:17:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,423
hpp
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <memory> namespace graphene { namespace db { class peer; typedef std::shared_ptr <peer> peer_ptr; class peer_ram; typedef std::shared_ptr <peer_ram> peer_ram_ptr; } } // namespace graphene::db
[ "info@vinchain.io" ]
info@vinchain.io
76a048a543ffa216ee107ba84fba9eabbed3a709
6be464ae66cce516d485b535f2f4429ba874cc0f
/StPicoDstMaker/StPicoDstMaker.cxx
d6c8099c8105d4e270372cedce9a3ff099aa623f
[]
no_license
ZWMiller/run14purityOnline
ca4c0c70d17eb339911a3e42b753e5fcf5f7948c
dfd71efb5a39c910bba6fa5c269de69d16588c39
refs/heads/master
2021-05-30T18:43:54.265306
2016-03-10T16:07:21
2016-03-10T16:07:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
42,683
cxx
#include <bitset> #include "TRegexp.h" #include "StChain.h" #include "StPicoDstMaker.h" #include "StPicoDst.h" #include "StPicoEvent.h" #include "StPicoTrack.h" #include "StPicoV0.h" #include "StPicoEmcTrigger.h" #include "StPicoMtdTrigger.h" #include "StPicoBTOWHit.h" #include "StPicoBTofHit.h" #include "StPicoMtdHit.h" #include "StPicoEmcPidTraits.h" #include "StPicoBTofPidTraits.h" #include "StPicoMtdPidTraits.h" #include "StPicoArrays.h" #include "StPicoCut.h" #include "StPicoConstants.h" #include "THack.h" #include "TChain.h" #include "TTree.h" #include "TH1D.h" #include "TBranch.h" #include "TRandom3.h" #include "TRandom.h" #include "StMuDSTMaker/COMMON/StMuDstMaker.h" #include "StMuDSTMaker/COMMON/StMuDst.h" #include "StMuDSTMaker/COMMON/StMuEvent.h" #include "StMuDSTMaker/COMMON/StMuBTofHit.h" #include "StMuDSTMaker/COMMON/StMuTrack.h" #include "StMuDSTMaker/COMMON/StMuPrimaryVertex.h" #include "StMuDSTMaker/COMMON/StMuBTofPidTraits.h" #include "StBTofHeader.h" #include "StMuDSTMaker/COMMON/StMuMtdHit.h" #include "StMuDSTMaker/COMMON/StMuMtdPidTraits.h" #include "tables/St_mtdModuleToQTmap_Table.h" #include "StMuDSTMaker/COMMON/StMuEmcCollection.h" #include "StMuDSTMaker/COMMON/StMuEmcPoint.h" #include "StEmcUtil/projection/StEmcPosition.h" //StEmc #include "StEmcCollection.h" #include "StEmcCluster.h" #include "StEmcDetector.h" #include "StEmcModule.h" #include "StEmcClusterCollection.h" #include "StEmcPoint.h" #include "StEmcRawHit.h" #include "StEmcUtil/geometry/StEmcGeom.h" #include "StEmcUtil/others/emcDetectorName.h" #include "StEmcADCtoEMaker/StBemcData.h" #include "StEmcADCtoEMaker/StEmcADCtoEMaker.h" #include "StEmcRawMaker/defines.h" #include "StEmcRawMaker/StBemcRaw.h" #include "StEmcRawMaker/StBemcTables.h" #include "StEmcRawMaker/StEmcRawMaker.h" #include "StEmcRawMaker/defines.h" #include "StTriggerUtilities/StTriggerSimuMaker.h" #include "StTriggerUtilities/Bemc/StBemcTriggerSimu.h" #include "StTriggerUtilities/Eemc/StEemcTriggerSimu.h" #include "StTriggerUtilities/Emc/StEmcTriggerSimu.h" #include "StTriggerData.h" #include "StDcaGeometry.h" ClassImp(StPicoDstMaker) #if !(ST_NO_NAMESPACES) using namespace units; #endif // Set maximum file size to 1.9 GB (Root has a 2GB limit) #define MAXFILESIZE 1900000000 const char* StPicoDstMaker::mEW[nEW*nDet] = {"EE","EW","WE","WW","FarWest","West","East","FarEast"}; //----------------------------------------------------------------------- StPicoDstMaker::StPicoDstMaker(const char* name) : StMaker(name), mMuDst(0), mMuEvent(0), mBTofHeader(0), mEmcCollection(0), mCentrality(0), mIoMode(0), mCreatingPhiWgt(0), mProdMode(0), mEmcMode(1), mOutputFile(0), mPhiWgtFile(0), mChain(0), mTTree(0), mSplit(99), mCompression(9), mBufferSize(65536*4) { assignArrays(); streamerOff(); zeroArrays(); createArrays(); mPicoDst = new StPicoDst(); mPicoCut = new StPicoCut(); mInputFileName=""; mOutputFileName=""; mPhiWgtFileName=""; mPhiTestFileName=""; mEventCounter=0; memset(mEmcIndex, 0, sizeof(mEmcIndex)); for(int i=0;i<nCen+1;i++) { for(int j=0;j<nEW*nDet;j++) mPhiWgtHist[i][j] = 0; for(int j=0;j<nEW*nDet*nPhi;j++) mPhiWeightRead[i][j] = 1.; } memset(mModuleToQT,-1,sizeof(mModuleToQT)); memset(mModuleToQTPos,-1,sizeof(mModuleToQTPos)); } //----------------------------------------------------------------------- StPicoDstMaker::StPicoDstMaker(int mode, const char* fileName, const char* name) : StMaker(name), mMuDst(0), mMuEvent(0), mBTofHeader(0), mEmcCollection(0), mCentrality(0), mIoMode(mode), mCreatingPhiWgt(0), mProdMode(0), mEmcMode(1), mOutputFile(0), mPhiWgtFile(0), mChain(0), mTTree(0), mSplit(99), mCompression(9), mBufferSize(65536*4) { assignArrays(); streamerOff(); zeroArrays(); createArrays(); mPicoDst = new StPicoDst(); mPicoCut = new StPicoCut(); if(mIoMode==ioWrite) { TString inputDirFile = fileName; // input is actually the full name including path Int_t index = inputDirFile.Index("st_"); mInputFileName=""; for(int i=index;i<(int)inputDirFile.Length();i++) { mInputFileName.Append(inputDirFile(i)); } mOutputFileName=mInputFileName; mOutputFileName.ReplaceAll("MuDst.root","picoDst.root"); } if(mIoMode==ioRead) { mInputFileName = fileName; } mEventCounter=0; memset(mEmcIndex, 0, sizeof(mEmcIndex)); for(int i=0;i<nCen+1;i++) { for(int j=0;j<nEW*nDet;j++) mPhiWgtHist[i][j] = 0; for(int j=0;j<nEW*nDet*nPhi;j++) mPhiWeightRead[i][j] = 1.; } memset(mModuleToQT,-1,sizeof(mModuleToQT)); memset(mModuleToQTPos,-1,sizeof(mModuleToQTPos)); } //----------------------------------------------------------------------- StPicoDstMaker::~StPicoDstMaker() { // if (mIoMode== ioWrite ) closeWrite(); // if (mIoMode== ioRead ) closeRead(); saveDelete(mChain); } //----------------------------------------------------------------------- void StPicoDstMaker::clearIndices() { for(size_t i=0;i<nTrk;i++) mIndex2Primary[i] = -1; for(size_t i=0;i<nTrk;i++) mMap2Track[i] = -1; for(size_t i=0;i<nEW*nDet*nPhi;i++) mPhiWeightWrite[i] = 0.; } //----------------------------------------------------------------------- void StPicoDstMaker::assignArrays() { mPicoArrays = mPicoAllArrays + 0; mPicoV0Arrays = mPicoArrays + __NPICOARRAYS__; } //----------------------------------------------------------------------- void StPicoDstMaker::clearArrays() { for ( int i=0; i<__NALLPICOARRAYS__; i++) { mPicoAllArrays[i]->Clear(); StPicoArrays::picoArrayCounters[i] = 0; } } //----------------------------------------------------------------------- void StPicoDstMaker::zeroArrays() { memset(mPicoAllArrays, 0, sizeof(void*)*__NALLPICOARRAYS__); memset(mStatusArrays, (char)1, sizeof(mStatusArrays)); // defaul all ON } //----------------------------------------------------------------------- void StPicoDstMaker::SetStatus(const char *arrType, int status) { static const char *specNames[] = {"EventAll","V0All",0}; static const int specIndex[] = { 0, __NPICOARRAYS__, -1}; if (strncmp(arrType,"St",2)==0) arrType+=2; //Ignore first "St" for (int i=0;specNames[i];i++) { if (strcmp(arrType,specNames[i])) continue; char *sta=mStatusArrays+specIndex[i]; int num=specIndex[i+1]-specIndex[i]; memset(sta,status,num); LOG_INFO << "StPicoDstMaker::SetStatus " << status << " to " << specNames[i] << endm; if (mIoMode==ioRead) setBranchAddresses(mChain); return; } TRegexp re(arrType,1); for (int i=0;i<__NALLARRAYS__;i++) { Ssiz_t len; if (re.Index(StPicoArrays::picoArrayNames[i],&len) < 0) continue; LOG_INFO << "StPicoDstMaker::SetStatus " << status << " to " << StPicoArrays::picoArrayNames[i] << endm; mStatusArrays[i]=status; } if (mIoMode==ioRead) setBranchAddresses(mChain); } //----------------------------------------------------------------------- void StPicoDstMaker::setBranchAddresses(TChain* chain) { if(!chain) return; chain->SetBranchStatus("*",0); TString ts; for ( int i=0; i<__NALLPICOARRAYS__; i++) { if (mStatusArrays[i]==0) continue; const char *bname=StPicoArrays::picoArrayNames[i]; TBranch *tb = chain->GetBranch(bname); if(!tb) { LOG_WARN << "setBranchAddress: Branch name " << bname << " does not exist!" << endm; continue; } ts = bname; ts += "*"; chain->SetBranchStatus(ts,1); chain->SetBranchAddress(bname,mPicoAllArrays+i); assert(tb->GetAddress()==(char*)(mPicoAllArrays+i)); } mTTree = mChain->GetTree(); } //----------------------------------------------------------------------- void StPicoDstMaker::streamerOff() { StPicoEvent::Class()->IgnoreTObjectStreamer(); StPicoTrack::Class()->IgnoreTObjectStreamer(); StPicoV0::Class()->IgnoreTObjectStreamer(); } //----------------------------------------------------------------------- void StPicoDstMaker::createArrays() { for ( int i=0; i<__NALLPICOARRAYS__; i++) { clonesArray(mPicoAllArrays[i],StPicoArrays::picoArrayTypes[i],StPicoArrays::picoArraySizes[i],StPicoArrays::picoArrayCounters[i]); } mPicoDst->set(this); } //----------------------------------------------------------------------- TClonesArray* StPicoDstMaker::clonesArray(TClonesArray*& p, const char* type, int size, int& counter) { if(p) return p; p = new TClonesArray(type, size); counter=0; return p; } //----------------------------------------------------------------------- Int_t StPicoDstMaker::Init(){ if (mIoMode == ioRead) { openRead(); // if read, don't care about phi weight files } else if (mIoMode == ioWrite) { openWrite(); if(!initMtd()) { LOG_ERROR << " MTD initialization error!!! " << endm; return kStErr; } if(mEmcMode) initEmc(); } return kStOK; } //----------------------------------------------------------------------- Bool_t StPicoDstMaker::initMtd() { // initialize MTD maps memset(mModuleToQT,-1,sizeof(mModuleToQT)); memset(mModuleToQTPos,-1,sizeof(mModuleToQTPos)); // obtain maps from DB LOG_INFO << "Retrieving mtdModuleToQTmap table from database ..." << endm; TDataSet *dataset = GetDataBase("Geometry/mtd/mtdModuleToQTmap"); St_mtdModuleToQTmap *mtdModuleToQTmap = static_cast<St_mtdModuleToQTmap*>(dataset->Find("mtdModuleToQTmap")); if(!mtdModuleToQTmap) { LOG_ERROR << "No mtdModuleToQTmap table found in database" << endm; return kStErr; } mtdModuleToQTmap_st *mtdModuleToQTtable = static_cast<mtdModuleToQTmap_st*>(mtdModuleToQTmap->GetTable()); for(Int_t i=0; i<30; i++) { for(Int_t j=0; j<5; j++) { Int_t index = i*5 + j; Int_t qt = mtdModuleToQTtable->qtBoardId[index]; Int_t channel = mtdModuleToQTtable->qtChannelId[index]; mModuleToQT[i][j] = qt; if(channel<0) { mModuleToQTPos[i][j] = channel; } else { if(channel%8==1) mModuleToQTPos[i][j] = 1 + channel/8 * 2; else mModuleToQTPos[i][j] = 2 + channel/8 * 2; } } } return kTRUE; } //----------------------------------------------------------------------- Int_t StPicoDstMaker::Finish(){ if (mIoMode == ioRead) { closeRead(); // if read, don't care about phi weight files } else if (mIoMode == ioWrite) { closeWrite(); if(mEmcMode) finishEmc(); } return kStOK; } //----------------------------------------------------------------------- Int_t StPicoDstMaker::openRead() { if(!mChain) mChain = new TChain("PicoDst"); string dirFile = mInputFileName.Data(); if (dirFile.find(".list")!=string::npos) { ifstream inputStream(dirFile.c_str()); if(!(inputStream.good())) { LOG_ERROR << "ERROR: Cannot open list file " << dirFile << endm; } char line[512]; int nFile=0; string ltest; while (inputStream.good()) { inputStream.getline(line,512); string aFile = line; if (inputStream.good() && aFile.find(".picoDst.root")!=string::npos) { // TFile *ftmp = new TFile(line); TFile *ftmp = TFile::Open(line); if(ftmp && ftmp->IsOpen() && ftmp->GetNkeys()) { LOG_INFO << " Read in picoDst file " << line << endm; mChain->Add(line); nFile++; } } } LOG_INFO << " Total " << nFile << " files have been read in. " << endm; } else if (dirFile.find(".picoDst.root")!=string::npos) { mChain->Add(dirFile.c_str()); } else { LOG_WARN << " No good input file to read ... " << endm; } if(mChain) { setBranchAddresses(mChain); mPicoDst->set(this); } return kStOK; } //----------------------------------------------------------------------- void StPicoDstMaker::openWrite() { if(mProdMode==minbias2) { // use phi weight files for mb2 production char name[100]; sprintf(name,"%d.flowPhiWgt.inv.root", mRunNumber); mPhiWgtFileName=name; mPhiTestFileName=mInputFileName; mPhiTestFileName.ReplaceAll("MuDst.root","flowPhiWgt.test.root"); mPhiWgtFile = new TFile(mPhiWgtFileName.Data(),"READ"); if(!mPhiWgtFile->IsOpen()) { LOG_INFO<<"*********************************************************************************************************"<<endm; LOG_INFO<<"** Phi weight file '"<<mPhiWgtFileName.Data()<<"' not found. Only phi weight files will be generated. **"<<endm; LOG_INFO<<"*********************************************************************************************************"<<endm; mCreatingPhiWgt = kTRUE; mPhiWgtFileName = mInputFileName; mPhiWgtFileName.ReplaceAll("MuDst.root","flowPhiWgt.hist.root"); mPhiWgtFile = new TFile(mPhiWgtFileName.Data(), "RECREATE"); LOG_INFO << " Creating file " << mPhiWgtFileName.Data() << endm; DeclareHistos(); } else { mCreatingPhiWgt = kFALSE; LOG_INFO<<"*******************************************************"<<endm; LOG_INFO<<"** Reading phi weights from '"<<mPhiWgtFileName.Data()<<"'. **"<<endm; LOG_INFO<<"*******************************************************"<<endm; for(int ic = 0; ic < nCen+1; ic++) { for(int iew = 0; iew < nEW*nDet; iew++) { char hisname[100]; sprintf(hisname,"Phi_Weight_Cent_%d_%s",ic,mEW[iew]); TH1* phiWgtHist = dynamic_cast<TH1*>(mPhiWgtFile->Get(hisname)); for(int iphi = 0; iphi < nPhi; iphi++) { mPhiWeightRead[ic][iphi+nPhi*iew] = phiWgtHist->GetBinContent(iphi+1); } } } mPhiWgtFile->Close(); mPhiTestFileName = mInputFileName; mPhiTestFileName.ReplaceAll("MuDst.root","flowPhiWgt.test.root"); mPhiWgtFile = new TFile(mPhiTestFileName.Data(),"RECREATE"); LOG_INFO << " Test file: " << mPhiTestFileName.Data() << " created." << endm; DeclareHistos(); } // end if mPhiWgtFile } else { mCreatingPhiWgt = kFALSE; LOG_INFO<<"*********************************************************************************************************"<<endm; LOG_INFO<<"** This production mode doesn't require the phi weight files. Start to produce the picoDst directly... **"<<endm; LOG_INFO<<"*********************************************************************************************************"<<endm; } if(!mCreatingPhiWgt) { mOutputFile = new TFile(mOutputFileName.Data(),"RECREATE"); LOG_INFO << " Output file: " << mOutputFileName.Data() << " created." << endm; mOutputFile->SetCompressionLevel(mCompression); TBranch* branch; int bufsize = mBufferSize; if (mSplit) bufsize /= 4; mTTree = new TTree("PicoDst","StPicoDst",mSplit); mTTree->SetMaxTreeSize(MAXFILESIZE); mTTree->SetAutoSave(1000000); for ( int i=0; i<__NALLPICOARRAYS__; i++) { if (mStatusArrays[i]==0) { cout << " Branch " << StPicoArrays::picoArrayNames[i] << " status is OFF! " << endl; continue; } branch = mTTree->Branch(StPicoArrays::picoArrayNames[i],&mPicoAllArrays[i],bufsize,mSplit); } } } //----------------------------------------------------------------------- void StPicoDstMaker::initEmc() { mEmcPosition = new StEmcPosition(); for(int i=0;i<4;i++) { mEmcGeom[i] = StEmcGeom::getEmcGeom(detname[i].Data()); } } //----------------------------------------------------------------------- void StPicoDstMaker::buildEmcIndex() { StEmcDetector *mEmcDet = mMuDst->emcCollection()->detector(kBarrelEmcTowerId); memset(mEmcIndex, 0, sizeof(mEmcIndex)); if(!mEmcDet) return; for (size_t iMod=1; iMod<=mEmcDet->numberOfModules(); ++iMod) { StSPtrVecEmcRawHit& modHits = mEmcDet->module(iMod)->hits(); for (size_t iHit=0; iHit<modHits.size(); ++iHit) { StEmcRawHit* rawHit = modHits[iHit]; if(!rawHit) continue; unsigned int softId = rawHit->softId(1); if (mEmcGeom[0]->checkId(softId)==0) { // OK mEmcIndex[softId-1] = rawHit; } } } } //----------------------------------------------------------------------- void StPicoDstMaker::finishEmc() { if(mEmcPosition) delete mEmcPosition; for(int i=0;i<4;i++) { mEmcGeom[i] = 0; } //mEmcDet = 0; } ///----------------------------------------------------------------------- void StPicoDstMaker::DeclareHistos() { LOG_INFO << " StPicoDstMaker::DeclareHistos() " << endm; for(int ic = 0; ic < nCen+1; ic++) { for(int iew = 0; iew < nEW*nDet; iew++) { char hisname[100]; sprintf(hisname,"Phi_Weight_Cent_%d_%s",ic,mEW[iew]); mPhiWgtHist[ic][iew] = new TH1D(hisname,hisname,nPhi,0.,TMath::Pi()*2.); } } } //_____________________________________________________________________________ void StPicoDstMaker::WriteHistos() { LOG_INFO << "StPicoDstMaker::WriteHistos() " << endm; for(int ic = 0; ic < nCen+1; ic++) { for(int iew = 0; iew < nEW*nDet; iew++) { char hisname[100]; sprintf(hisname,"Phi_Weight_Cent_%d_%s",ic,mEW[iew]); mPhiWgtHist[ic][iew]->Write(); } } } //----------------------------------------------------------------------- void StPicoDstMaker::Clear(const char *){ if (mIoMode==ioRead) return; clearArrays(); } //_____________________________________________________________________________ void StPicoDstMaker::closeRead() { if (mChain) mChain->Delete(); mChain = 0; } //_____________________________________________________________________________ void StPicoDstMaker::closeWrite() { if(mIoMode==ioWrite) { if(mPhiWgtFile && mPhiWgtFile->IsOpen()) { mPhiWgtFile->cd(); WriteHistos(); mPhiWgtFile->Close(); } if(mOutputFile) { if(!mCreatingPhiWgt) mOutputFile->Write(); mOutputFile->Close(); } } } //----------------------------------------------------------------------- int StPicoDstMaker::Make(){ int returnStarCode = kStOK; if (mIoMode == ioWrite){ returnStarCode = MakeWrite(); } else if (mIoMode == ioRead) returnStarCode = MakeRead(); return returnStarCode; } //----------------------------------------------------------------------- Int_t StPicoDstMaker::MakeRead() { if (!mChain) { LOG_WARN << " No input files ... ! EXIT" << endm; return kStWarn; } mChain->GetEntry(mEventCounter++); mPicoDst->set(this); return kStOK; } //----------------------------------------------------------------------- Int_t StPicoDstMaker::MakeWrite() { StMuDstMaker *muDstMaker = (StMuDstMaker*)GetMaker("MuDst"); if(!muDstMaker) { LOG_WARN << " No MuDstMaker " << endm; return kStWarn; } mMuDst = muDstMaker->muDst(); if(!mMuDst) { LOG_WARN << " No MuDst " << endm; return kStWarn; } mMuEvent = mMuDst->event(); if(!mMuEvent) { LOG_WARN << " No MuEvent " << endm; return kStWarn; } mBTofHeader = mMuDst->btofHeader(); ////////////////////////////////////// // select the right vertex using VPD ///////////////////////////////////// Float_t vzVpd = -999; if(mBTofHeader) vzVpd = mBTofHeader->vpdVz(); for(unsigned int i=0;i<mMuDst->numberOfPrimaryVertices();i++) { StMuPrimaryVertex *vtx = mMuDst->primaryVertex(i); if(!vtx) continue; Float_t vz = vtx->position().z(); if(fabs(vzVpd)<100 && fabs(vzVpd-vz)<3.) { mMuDst->setVertexIndex(i); break; } } ///////////////////////////////////// if(mEmcMode){ mEmcCollection = mMuDst->emcCollection(); if(mEmcCollection) buildEmcIndex(); } clearIndices(); Int_t refMult = mMuEvent->refMult(); mCentrality = centrality(refMult); mBField = mMuEvent->magneticField(); StThreeVectorF pVtx(0.,0.,0.); if(mMuDst->primaryVertex()) pVtx = mMuDst->primaryVertex()->position(); LOG_DEBUG << " eventId = " << mMuEvent->eventId() << " refMult = " << refMult << " vtx = " << pVtx << endm; if(mPicoCut->passEvent(mMuEvent)) { // keep all events in pp collisions to monitor triggers fillTracks(); if(!mCreatingPhiWgt) { fillEvent(); // Do not fill v0 for 39 GeV // if(mProdMode==minbias || mProdMode==minbias2) fillV0(); // only fill V0 branches for minbias data //fillV0(); fillEmcTrigger(); fillMtdTrigger(); // This must be called before fillMtdHits() fillBTOWHits(); //fillBTofHits(); fillMtdHits(); } if(Debug()) mPicoDst->printTracks(); // if(mProdMode==minbias2) FillHistograms(mCentrality, mPhiWeightWrite); // central data, not fill the phi weight anymore if(!mCreatingPhiWgt) { mTTree->Fill(); THack::IsTreeWritable(mTTree); } } else { if(!mCreatingPhiWgt) { //fillEvent(); //mTTree->Fill(); THack::IsTreeWritable(mTTree); } //LOG_INFO << "Event did not pass " << endm; } return kStOK; } //----------------------------------------------------------------------- void StPicoDstMaker::fillTracks() { Int_t nPrimarys = mMuDst->numberOfPrimaryTracks(); for(int i=0;i<nPrimarys;i++) { StMuTrack *pTrk = (StMuTrack *)mMuDst->primaryTracks(i); if(!pTrk) continue; if(pTrk->id()<0 || pTrk->id()>=50000) { LOG_WARN << " This primary track has a track id out of the range : " << pTrk->id() << endm; continue; } mIndex2Primary[pTrk->id()] = i; } Int_t nGlobals = mMuDst->numberOfGlobalTracks(); for(int i=0;i<nGlobals;i++) { StMuTrack *gTrk = (StMuTrack *)mMuDst->globalTracks(i); if(!gTrk) continue; if(!mPicoCut->passTrack(gTrk)) continue; if(gTrk->id()<0 || gTrk->id()>=50000) { LOG_WARN << " This global track has a track id out of the range : " << gTrk->id() << endm; continue; } int index = mIndex2Primary[gTrk->id()]; StMuTrack *pTrk = (index>=0) ? (StMuTrack *)mMuDst->primaryTracks(index) : 0; if(mCreatingPhiWgt && !pTrk) continue; // Int_t flowFlag = mPicoCut->flowFlag(pTrk); Int_t flowFlag = 1; Float_t Vz = mMuDst->primaryVertex()->position().z(); Int_t iPhi = phiBin(flowFlag, pTrk, Vz); float phi_wgt_read = 1.; if(iPhi>=0) phi_wgt_read = mPhiWeightRead[mCentrality][iPhi]; int id = -1; int adc0; float e[5]; float dist[4]; int nhit[2]; int ntow[3]; if(mEmcMode) getBEMC(gTrk, &id, &adc0, e, dist, nhit, ntow); if(mProdMode==4) { // save only electron or muon candidates Double_t nsigmaE = gTrk->nSigmaElectron(); Double_t beta = (gTrk) ? gTrk->btofPidTraits().beta() : -999.; // running on st_mtd data Bool_t isTPC = kFALSE, isTOF = kFALSE, isEMC = kFALSE, isMTD = kFALSE; if(gTrk->index2MtdHit()>=0) isMTD = kTRUE; if(nsigmaE>=-3 && nsigmaE<=3) isTPC = kTRUE; if(TMath::Abs(1/beta-1)<0.05) isTOF = kTRUE; if(gTrk->pt()>1.5 && id>=0) isEMC = kTRUE; if( ! ( (isTPC&&isTOF) || (isTPC&&isEMC) || isMTD) ) continue; } if(gTrk->index2Cov()<0) continue; StDcaGeometry *dcaG = mMuDst->covGlobTracks(gTrk->index2Cov()); if(!dcaG) { cout << "No dca Geometry for this track !!! " << i << endm; } int counter = mPicoArrays[picoTrack]->GetEntries(); new((*(mPicoArrays[picoTrack]))[counter]) StPicoTrack(gTrk, pTrk, phi_wgt_read, flowFlag, mBField, dcaG); if(iPhi>=nEW*nDet*nPhi) { cout << " flowFlag = " << flowFlag << " eta=" << pTrk->eta() << " q=" << pTrk->charge() << " vz=" << Vz << endl; cout << " WARN !!! " << iPhi << endl; } if(iPhi>=0) addPhiWeight(pTrk, phi_wgt_read, &mPhiWeightWrite[iPhi]); StPicoTrack *picoTrk = (StPicoTrack*)mPicoArrays[picoTrack]->At(counter); // Fill pid traits if(id>=0) { Int_t emc_index = mPicoArrays[picoEmcPidTraits]->GetEntries(); new((*(mPicoArrays[picoEmcPidTraits]))[emc_index]) StPicoEmcPidTraits(counter, id, adc0, e, dist, nhit, ntow); picoTrk->setEmcPidTraitsIndex(emc_index); } if(gTrk->tofHit()) { Int_t btof_index = mPicoArrays[picoBTofPidTraits]->GetEntries(); new((*(mPicoArrays[picoBTofPidTraits]))[btof_index]) StPicoBTofPidTraits(gTrk, pTrk, counter); picoTrk->setBTofPidTraitsIndex(btof_index); } if(gTrk->mtdHit()) { Int_t emc_index = mPicoArrays[picoMtdPidTraits]->GetEntries(); new((*(mPicoArrays[picoMtdPidTraits]))[emc_index]) StPicoMtdPidTraits(gTrk->mtdHit(), &(gTrk->mtdPidTraits()),counter); picoTrk->setMtdPidTraitsIndex(emc_index); } } // cout << " ++ track branch size = " << mPicoArrays[picoTrack]->GetEntries() << endl; } //----------------------------------------------------------------------- bool StPicoDstMaker::getBEMC(StMuTrack *t, int *id, int *adc, float *ene, float *d, int *nep, int *towid) { *id = -1; *adc = 0; for(int i=0;i<5;i++) { ene[i] = 0.; } for(int i=0;i<4;i++) { d[i] = 1.e9; } for(int i=0;i<2;i++) { nep[i] = 0; } for(int i=0;i<3;i++) { towid[i] = -1; } if(!mEmcCollection) { LOG_WARN << " No Emc Collection for this event " << endm; return kFALSE; } StThreeVectorD position, momentum; StThreeVectorD positionBSMDE, momentumBSMDE; StThreeVectorD positionBSMDP, momentumBSMDP; Double_t bFld = mBField*kilogauss/tesla; // bFld in Tesla bool ok = false; bool okBSMDE = false; bool okBSMDP = false; if(mEmcPosition) { ok = mEmcPosition->projTrack(&position, &momentum, t, bFld, mEmcGeom[0]->Radius()); okBSMDE = mEmcPosition->projTrack(&positionBSMDE, &momentumBSMDE, t, bFld, mEmcGeom[2]->Radius()); okBSMDP = mEmcPosition->projTrack(&positionBSMDP, &momentumBSMDP, t, bFld, mEmcGeom[3]->Radius()); } // if(!ok || !okBSMDE || !okBSMDP) { if(!ok) { LOG_WARN << " Projection failed for this track ... " << endm; return kFALSE; } if(ok && okBSMDE && okBSMDP) { Int_t mod, eta, sub; StSPtrVecEmcPoint& bEmcPoints = mEmcCollection->barrelPoints(); int index=0; float mindist=1.e9; mEmcGeom[0]->getBin(positionBSMDP.phi(), positionBSMDE.pseudoRapidity(), mod, eta, sub); //project on SMD plan for(StSPtrVecEmcPointIterator it = bEmcPoints.begin(); it != bEmcPoints.end(); it++, index++) { bool associated=false; StPtrVecEmcCluster& bEmcClusters = (*it)->cluster(kBarrelEmcTowerId); if(bEmcClusters.size()==0 ) continue; if(bEmcClusters[0]==NULL) continue; for(StPtrVecEmcClusterIterator cIter = bEmcClusters.begin(); cIter != bEmcClusters.end(); cIter++) { StPtrVecEmcRawHit& bEmcHits = (*cIter)->hit(); for(StPtrVecEmcRawHitIterator hIter = bEmcHits.begin(); hIter != bEmcHits.end(); hIter++) { if(mod == (Int_t)(*hIter)->module() && eta == (Int_t)(*hIter)->eta() && sub == (Int_t)(*hIter)->sub()) { associated=true; break; } } if(associated) { for(StPtrVecEmcRawHitIterator hitit=bEmcHits.begin(); hitit!=bEmcHits.end();hitit++) { if((*hitit)->energy()>ene[0]) ene[0]=(*hitit)->energy(); if((int)(*hitit)->adc()>(*adc)) *adc=(*hitit)->adc(); } } } StPtrVecEmcCluster& smdeClusters = (*it)->cluster(kBarrelSmdEtaStripId); StPtrVecEmcCluster& smdpClusters = (*it)->cluster(kBarrelSmdPhiStripId); if(associated) { *id = index; ene[1] = ene[1] + (*it)->energy(); //use point's energy, not tower cluster's energy float deltaphi=(*it)->position().phi()-positionBSMDP.phi(); if(deltaphi>=TMath::Pi()) deltaphi=deltaphi-TMath::TwoPi(); if(deltaphi<-TMath::Pi()) deltaphi=deltaphi+TMath::TwoPi(); float rsmdp=mEmcGeom[3]->Radius(); float pointz=(*it)->position().z(); float deltaz=pointz-positionBSMDE.z(); if(sqrt(deltaphi*deltaphi*rsmdp*rsmdp+deltaz*deltaz)<mindist) { d[1]=deltaphi; d[0]=deltaz; if(smdeClusters.size()>=1) nep[0]=smdeClusters[0]->nHits(); if(smdpClusters.size()>=1) nep[1]=smdpClusters[0]->nHits(); mindist=sqrt(deltaphi*deltaphi*rsmdp*rsmdp+deltaz*deltaz); } }//associated } } // end if (ok && okBSMDE && okBSMDP) //Get BEMC tower energy from matched tower + 2 nearest towers int towerId; int localTowerId = -1; int localId1 = -1; int localId2 = -1; double energy1 = 0, energy2 = 0; double energyTemp; double dist1 = 1000, dist2 = 1000; double distTemp; Float_t etaTemp, phiTemp; mEmcGeom[0]->getId(position.phi(),position.pseudoRapidity(),towerId); for(int ieta=-1;ieta<2;ieta++){ for(int iphi=-1;iphi<2;iphi++){ localTowerId++;//loops from 0 to 8 int nextTowerId = mEmcPosition->getNextTowerId(towerId, ieta, iphi); if(nextTowerId < 1 || nextTowerId > 4800) continue; StEmcRawHit* emcHit = mEmcIndex[nextTowerId-1]; if (emcHit==0) continue; if (emcHit->energy()<0.2) continue; // don't include any noise tower if(ieta==0&&iphi==0) { mEmcGeom[0]->getEta(nextTowerId, etaTemp); mEmcGeom[0]->getPhi(nextTowerId, phiTemp); ene[2] = emcHit->energy(); d[2] = position.pseudoRapidity() - etaTemp; d[3] = position.phi() - phiTemp; } else { energyTemp = emcHit->energy(); mEmcGeom[0]->getEta(nextTowerId, etaTemp); mEmcGeom[0]->getPhi(nextTowerId, phiTemp); distTemp = sqrt((etaTemp-position.pseudoRapidity())*(etaTemp-position.pseudoRapidity()) + (phiTemp-position.phi())*(phiTemp-position.phi())); if(distTemp < dist1) { dist2 = dist1; dist1 = distTemp; energy2 = energy1; energy1 = energyTemp; localId1 = localTowerId; } else if(distTemp < dist2){ dist2 = distTemp; energy2 = energyTemp; localId2 = localTowerId; } } } } towid[0] = towerId; ene[3] = energy1;//closest tower towid[1] = localId1; ene[4] = energy2;//2nd closest tower towid[2] = localId2; if(Debug()) { // if(1) { cout << " ====== BEMC results ====== " << endl; cout << " Energy = " << ene[0] << " " << ene[1] << " " << ene[2] << " " << ene[3] << " " << ene[4] << endl; cout << " BSMD = " << nep[0] << " " << nep[1] << endl; cout << " TowerId = " << towid[0] << " " << towid[1] << " " << towid[2] << endl; } return kTRUE; } //----------------------------------------------------------------------- Int_t StPicoDstMaker::phiBin(int flag, StMuTrack *p, float vz) { int iPhi = -1; if(!p) return iPhi; if(flag<=0) return iPhi; float phi = p->phi(); if(phi<0) phi += 2.*TMath::Pi(); int bin = (int)floor(360.0*phi/(2.*TMath::Pi())); float eta = p->eta(); int iew; if ( flag==tpcFlow ) { int q = p->charge(); if ( eta > 0 && q > 0 ) iew = EE; else if ( eta > 0 && q < 0 ) iew = EW; else if ( eta < 0 && q > 0 ) iew = WE; else iew = WW; } else if ( flag==ftpcFlow ) { if ( eta > 0 && vz > 0 ) iew = FarWest; else if ( eta > 0 && vz < 0 ) iew = West; else if ( eta < 0 && vz > 0 ) iew = East; else iew = FarEast; } iPhi = bin + iew * nPhi + (flag-1) * nPhi * nEW; return iPhi; } //----------------------------------------------------------------------- void StPicoDstMaker::addPhiWeight(StMuTrack *p, float read_phi_wgt, float* write_phi_wgt) { if(!p) return; float pt = p->p().perp(); float pt_weight = (pt < 2.) ? pt : 2.; *write_phi_wgt += pt_weight * read_phi_wgt; } //----------------------------------------------------------------------- void StPicoDstMaker::FillHistograms(int cent, float* phi_wgt_write) { for(int i=0;i<nDet;i++) { for(int j=0;j<nEW;j++) { for(int k=0;k<nPhi;k++) { float tmp1 = mPhiWgtHist[cent][j+i*nEW]->GetBinContent(k+1); float tmp2 = phi_wgt_write[k+j*nPhi+i*nEW*nPhi]; mPhiWgtHist[cent][j+i*nEW]->SetBinContent(k+1, tmp1+tmp2); } } } } //----------------------------------------------------------------------- void StPicoDstMaker::fillEvent() { Float_t Q[40]; for(int i=0;i<40;i++) Q[i] = 0.; Int_t nTracks = mPicoArrays[picoTrack]->GetEntries(); #if 0 int Fcount = 0, Ecount = 0, Wcount = 0; for(int i=0;i<nTracks;i++) { StPicoTrack *t = (StPicoTrack *)mPicoArrays[picoTrack]->UncheckedAt(i); if(!t) continue; if(!t->flowFlag()) continue; if(t->flowFlag()==tpcFlow) Fcount++; } int iTrack[Fcount], Scount = Fcount/2 -1; for(int q=0;q<Fcount;q++) iTrack[q] = q; random_shuffle(iTrack,iTrack+Fcount); Fcount = 0; #endif for(int i=0;i<nTracks;i++) { StPicoTrack *t = (StPicoTrack *)mPicoArrays[picoTrack]->UncheckedAt(i); if(!t) continue; mMap2Track[t->id()] = i; // map2track index - used for v0 branch #if 0 if(!t->flowFlag()) continue; int q = t->charge(); float eta = t->pMom().pseudoRapidity(); TVector2 Qi = t->Qi(); if(t->flowFlag()==tpcFlow) { if(iTrack[Fcount] > Scount) { // random subevent Q[0] += Qi.X(); Q[1] += Qi.Y(); Ecount++; } else { Q[2] += Qi.X(); Q[3] += Qi.Y(); Wcount++; } Fcount++; if(q>0) { // charge subevent Q[4] += Qi.X(); Q[5] += Qi.Y(); } else { Q[6] += Qi.X(); Q[7] += Qi.Y(); } if(eta>+0.075) { // eta subevent Q[8] += Qi.X(); Q[9] += Qi.Y(); } else if (eta<-0.075) { Q[10] += Qi.X(); Q[11] += Qi.Y(); } } #endif } int counter = mPicoArrays[picoEvent]->GetEntries(); // new((*(mPicoArrays[picoEvent]))[counter]) StPicoEvent(mMuEvent, mBTofHeader, Q); new((*(mPicoArrays[picoEvent]))[counter]) StPicoEvent(*mMuDst, Q); // mPicoDst->Print() ; } //----------------------------------------------------------------------- void StPicoDstMaker::fillEmcTrigger() { // test for EMC trigger StTriggerSimuMaker *trigSimu = (StTriggerSimuMaker *)GetMaker("StarTrigSimu"); if(!trigSimu) return; int trgId = mPicoDst->event()->triggerWord(); int bht0 = trigSimu->bemc->barrelHighTowerTh(0); int bht1 = trigSimu->bemc->barrelHighTowerTh(1); int bht2 = trigSimu->bemc->barrelHighTowerTh(2); int bht3 = trigSimu->bemc->barrelHighTowerTh(3); LOG_DEBUG << " bht thresholds " << bht0 << " " << bht1 << " " << bht2 << " " << bht3 << endm; for(int i=0;i<4;i++) mPicoDst->event()->setHT_Th(i, trigSimu->bemc->barrelHighTowerTh(i)); bool fireBHT0 = false; bool fireBHT1 = false; bool fireBHT2 = false; bool fireBHT3 = false; for (int towerId = 1; towerId <= 4800; ++towerId) { int status; trigSimu->bemc->getTables()->getStatus(BTOW, towerId, status); int adc = trigSimu->bemc->barrelHighTowerAdc(towerId); // if(towerId==4684) cout << " Id = " << towerId << " status = " << status << " adc = " << adc << endl; int flag = 0; if( ( trgId>>19 & 0x3 ) ) { // BHT1*VPDMB-30 if(adc>bht1) { LOG_DEBUG << " id = " << towerId << " adc = " << adc << endm; fireBHT1 = true; flag |= 1<<1; } } if( ( trgId>>21 & 0x3 ) ) { // BHT2*VPDMB-30 if(adc>bht2) { LOG_DEBUG << " id = " << towerId << " adc = " << adc << endm; fireBHT2 = true; flag |= 1<<2; } } if( ( trgId>>23 & 0x3 ) ) { // BHT3 if(adc>bht3) { LOG_DEBUG << " id = " << towerId << " adc = " << adc << endm; fireBHT3 = true; flag |= 1<<3; } } if( flag & 0xf ) { int counter = mPicoArrays[picoEmcTrigger]->GetEntries(); new((*(mPicoArrays[picoEmcTrigger]))[counter]) StPicoEmcTrigger(flag, towerId, adc); } } if( ( ( trgId>>19 & 0x3 ) ) && !fireBHT1 ) { LOG_WARN << " something is wrong with the bht1 in this event!!! " << endm; } if( ( ( trgId>>21 & 0x3 ) ) && !fireBHT2 ) { LOG_WARN << " something is wrong with the bht2 in this event!!! " << endm; //for (int towerId = 1; towerId <= 4800; ++towerId) { // int status; // trigSimu->bemc->getTables()->getStatus(BTOW, towerId, status); // int adc = trigSimu->bemc->barrelHighTowerAdc(towerId); //cout << " Id = " << towerId << " status = " << status << " adc = " << adc << endl; //} } if( ( ( trgId>>23 & 0x3 ) ) && !fireBHT3 ) { LOG_WARN << " something is wrong with the bht3 in this event!!! " << endm; } return; } //----------------------------------------------------------------------- void StPicoDstMaker::fillMtdTrigger() { StTriggerData *trigger = const_cast<StTriggerData*>(mMuDst->event()->triggerData()); int counter = mPicoArrays[picoMtdTrigger]->GetEntries(); new((*(mPicoArrays[picoMtdTrigger]))[counter]) StPicoMtdTrigger(trigger); } //----------------------------------------------------------------------- void StPicoDstMaker::fillBTOWHits() { #if 0 if(!mEmcCollection) { LOG_WARN << " No Emc Collection for this event " << endm; return; } StSPtrVecEmcPoint& bEmcPoints = mEmcCollection->barrelPoints(); for(StSPtrVecEmcPointIterator it = bEmcPoints.begin(); it != bEmcPoints.end(); it++) { StPtrVecEmcCluster& bEmcClusters = (*it)->cluster(kBarrelEmcTowerId); if(bEmcClusters.size()==0 ) continue; if(bEmcClusters[0]==NULL) continue; for(StPtrVecEmcClusterIterator cIter = bEmcClusters.begin(); cIter != bEmcClusters.end(); cIter++) { StPtrVecEmcRawHit& bEmcHits = (*cIter)->hit(); for(StPtrVecEmcRawHitIterator hIter = bEmcHits.begin(); hIter != bEmcHits.end(); hIter++) { int softId = (*hIter)->softId(1); int adc = (*hIter)->adc(); float energy = (*hIter)->energy(); int counter = mPicoArrays[picoBTOWHit]->GetEntries(); new((*(mPicoArrays[picoBTOWHit]))[counter]) StPicoBTOWHit(softId, adc, energy); } } } #endif #if 1 for(int i=0;i<4800;i++) { StEmcRawHit *aHit = mEmcIndex[i]; if(!aHit) continue; if(aHit->energy()<0.2) continue; // remove noise towers int softId = aHit->softId(1); int adc = aHit->adc(); float energy = aHit->energy(); int counter = mPicoArrays[picoBTOWHit]->GetEntries(); new((*(mPicoArrays[picoBTOWHit]))[counter]) StPicoBTOWHit(softId, adc, energy); } #endif } //----------------------------------------------------------------------- void StPicoDstMaker::fillBTofHits() { if(!mMuDst) { LOG_WARN << " No MuDst for this event " << endm; return; } for(unsigned int i=0;i<mMuDst->numberOfBTofHit();i++) { StMuBTofHit *aHit = (StMuBTofHit *)mMuDst->btofHit(i); if(aHit->tray()>120) continue; int cellId = (aHit->tray()-1)*192+(aHit->module()-1)*6+(aHit->cell()-1); int counter = mPicoArrays[picoBTofHit]->GetEntries(); new((*(mPicoArrays[picoBTofHit]))[counter]) StPicoBTofHit(cellId); } } //----------------------------------------------------------------------- void StPicoDstMaker::fillMtdHits() { if(!mMuDst) { LOG_WARN << " No MuDst for this event " << endm; return; } Int_t nMtdHits = mMuDst->numberOfMTDHit(); for(Int_t i=0; i<nMtdHits; i++) { StMuMtdHit *hit = (StMuMtdHit *)mMuDst->mtdHit(i); if(!hit) continue; Int_t counter = mPicoArrays[picoMtdHit]->GetEntries(); new((*(mPicoArrays[picoMtdHit]))[counter]) StPicoMtdHit(hit); } // check the firing hits if(mPicoArrays[picoMtdTrigger]->GetEntries()!=1) { LOG_ERROR << "There are " << mPicoArrays[picoMtdTrigger]->GetEntries() << " MTD trigger. Check it!" << endm; return; } StPicoMtdTrigger *trigger = dynamic_cast<StPicoMtdTrigger*>(mPicoArrays[picoMtdTrigger]->At(0)); Int_t triggerQT[4][2]; Bool_t triggerBit[4][8]; Int_t pos1 = 0, pos2 = 0; for(Int_t i=0; i<4; i++) { for(Int_t j=0; j<2; j++) triggerQT[i][j] = 0; for(Int_t j=0; j<8; j++) triggerBit[i][j] = kFALSE; trigger->getMaximumQTtac(i+1,pos1,pos2); triggerQT[i][0] = pos1; triggerQT[i][1] = pos2; for(Int_t j=0; j<2; j++) { if( triggerQT[i][j]>0 && ((trigger->getTF201TriggerBit()>>(i*2+j))&0x1) ) { triggerBit[i][triggerQT[i][j]-1] = kTRUE; } } } Int_t nHits = mPicoArrays[picoMtdHit]->GetEntries(); vector<Int_t> triggerPos; vector<Int_t> hitIndex; for(Int_t i=0; i<nHits; i++) { StPicoMtdHit *hit = dynamic_cast<StPicoMtdHit*>(mPicoArrays[picoMtdHit]->At(i)); Int_t backleg = hit->backleg(); Int_t module = hit->module(); Int_t qt = mModuleToQT[backleg-1][module-1]; Int_t pos = mModuleToQTPos[backleg-1][module-1]; if(qt>0 && pos>0 && triggerBit[qt-1][pos-1]) { triggerPos.push_back(qt*10+pos); hitIndex.push_back(i); } else { hit->setTriggerFlag(0); } } vector<Int_t> hits; hits.clear(); while(triggerPos.size()>0) { hits.clear(); hits.push_back(0); for(Int_t j=1; j<(Int_t)triggerPos.size(); j++) { if(triggerPos[j] == triggerPos[0]) hits.push_back(j); } for(Int_t k=(Int_t)hits.size()-1; k>-1; k--) { StPicoMtdHit *hit = dynamic_cast<StPicoMtdHit*>(mPicoArrays[picoMtdHit]->At(hitIndex[hits[k]])); hit->setTriggerFlag((Int_t)hits.size()); triggerPos.erase(triggerPos.begin()+hits[k]); hitIndex.erase(hitIndex.begin()+hits[k]); } } } /* //----------------------------------------------------------------------- void StPicoDstMaker::fillV0() { int nTracks = mPicoArrays[picoTrack]->GetEntries(); for(int i=0;i<nTracks;i++) { StPicoTrack *t_pos = (StPicoTrack *)mPicoArrays[picoTrack]->UncheckedAt(i); if(!t_pos) continue; if(t_pos->charge()!=+1) continue; if(!mPicoCut->passV0Daughter(t_pos)) continue; for(int j=0;j<nTracks;j++) { StPicoTrack *t_neg = (StPicoTrack *)mPicoArrays[picoTrack]->UncheckedAt(j); if(!t_neg) continue; if(t_neg->charge()!=-1) continue; if(!mPicoCut->passV0Daughter(t_neg)) continue; StPicoV0 *aV0 = new StPicoV0(t_pos, t_neg, mMuEvent, mMap2Track); if(!mPicoCut->passV0(aV0, mMuEvent)) { delete aV0; continue; } if(mPicoCut->passKs(aV0)) { int counter = mPicoV0Arrays[picoV0Ks]->GetEntries(); new((*(mPicoV0Arrays[picoV0Ks]))[counter]) StPicoV0(aV0); } if(mPicoCut->passLambda(aV0)) { int counter = mPicoV0Arrays[picoV0L]->GetEntries(); new((*(mPicoV0Arrays[picoV0L]))[counter]) StPicoV0(aV0); } if(mPicoCut->passLbar(aV0)) { int counter = mPicoV0Arrays[picoV0Lbar]->GetEntries(); new((*(mPicoV0Arrays[picoV0Lbar]))[counter]) StPicoV0(aV0); } delete aV0; } // end j } // end i } */ //----------------------------------------------------------------------- Int_t StPicoDstMaker::centrality(int refMult) { for(int i=0;i<nCen;i++) { // if(refMult <= Pico::mCent_Year10_39GeV[i]) { // if(refMult <= Pico::mCent_Year10_7_7GeV[i]) { // if(refMult <= Pico::mCent_Year11_19_6GeV[i]) { if(refMult <= Pico::mCent_Year11_200GeV[i]) { return i; } } return nCen; }
[ "zamiller@rcas6007.rcf.bnl.gov" ]
zamiller@rcas6007.rcf.bnl.gov
7c7e3eb095789c7b2dce7cc99377d367ae082350
5f76398d1ca25560f77d5a985704fb47ff3b205d
/7/7.5.cpp
ec97dfb52c383f76c122224c1c7a409d1e45ebf3
[]
no_license
jackandjoke/C-plus-plus-exercises
01edbdb3cd35bd80fb0c1b1036c86f901b20bca5
c5b44799bad28b30e3829740920726aea578b750
refs/heads/master
2020-03-13T15:15:15.741470
2018-08-05T07:17:47
2018-08-05T07:17:47
131,173,555
0
0
null
null
null
null
UTF-8
C++
false
false
184
cpp
#include<string> struct Person{ std::string name; std::string address; std::string get_name() const{ return name;} std::string get_address() const{return address;} };
[ "shzhaohao@gmail.com" ]
shzhaohao@gmail.com
23b9a099d614d64ed76e0023fe5a5fdea58b362c
8c1b22d1edef0748da6c9039599415864f22492a
/src/General.cpp
9a17f328fa1b755187534192ae18b7443a5496db
[]
no_license
HelloUSTC114/ImagingAlgorithm
23c648a077ef8b1c525edc0e809a08e07495e27b
9ea72368f4252dd9bdf35794ebe8f4607c957f5d
refs/heads/master
2021-05-17T22:45:54.247846
2020-04-27T10:46:36
2020-04-27T10:46:36
250,986,789
1
0
null
null
null
null
UTF-8
C++
false
false
1,690
cpp
#include "General.h" int ImagingAlgorithm::ErrorInt() { static int fErrorInt = -999999; return fErrorInt; } double ImagingAlgorithm::ErrorDouble() { static double fErrorDouble = -1e10; return fErrorDouble; } TChain *ImagingAlgorithm::GenerateChain(std::string treeName, const std::vector<std::string> &keyWord, TChain *chain, string sFolder, vector<std::string> notInclude) { gSystem->Exec(Form("ls %s/ 1> .~filelist 2> /dev/null", sFolder.c_str())); auto ch = chain; if (ch == NULL) { ch = new TChain(treeName.c_str()); } ifstream file_list(".~filelist"); for (int i = 0; file_list.is_open() && file_list.eof() == false; i++) { string s_temp; file_list >> s_temp; bool continueFlag = 0; for (size_t keyCount = 0; keyCount < keyWord.size(); keyCount++) { if (s_temp.find(keyWord[keyCount]) == string::npos) { continueFlag = 1; } else { // find in notInclude vector for (size_t i = 0; i < notInclude.size(); i++) { if (s_temp.find(notInclude[i]) != string::npos) { continueFlag = 1; } } } } if (continueFlag) continue; cout << "File: " << s_temp << " Read" << endl; string fileName = sFolder + "/" + s_temp; // ch->Add(s_temp.c_str()); ch->Add(fileName.c_str()); } cout << "Totally get " << ch->GetEntries() << " Entries" << endl; gSystem->Exec("rm .~filelist"); return ch; }
[ "john@Johns-MacBook-Pro.local" ]
john@Johns-MacBook-Pro.local
6ddfc3ddce305c7fa9d7ca03a62398fa69bf029f
1e58c1501d082f3084d77f51b3f0a7b7699f48a2
/3rdparty/src/qt_rpfm_extensions/src/tips_item_delegate.cpp
7f0b77938b79cd94bb9034a3fb0cb67aa3e542b2
[ "MIT" ]
permissive
Frodo45127/rpfm
f65c171e44b404ce41467f09216f5775e194b93f
a3a540c2dd332c750f892d3d5c0625f368bc6ca6
refs/heads/master
2023-08-25T06:22:22.054978
2023-08-20T01:14:28
2023-08-20T01:14:28
110,712,025
317
64
MIT
2023-05-13T22:56:14
2017-11-14T15:59:42
Rust
UTF-8
C++
false
false
6,387
cpp
#include "tips_item_delegate.h" #include <QDebug> #include <QAbstractItemView> #include <QSortFilterProxyModel> #include <QPen> #include <QColor> #include <QPainter> #include <QStandardItem> #include <QStyle> #include <QSettings> #include <QPainterPath> #include <QAbstractTextDocumentLayout> #include <QTextDocument> // Function to be called from any other language. This assing to the provided column of the provided TableView a QTreeItemDelegate. extern "C" void new_tips_item_delegate(QObject *parent, bool is_dark_theme_enabled, bool has_filter) { QTipsItemDelegate* delegate = new QTipsItemDelegate(parent, is_dark_theme_enabled, has_filter); dynamic_cast<QAbstractItemView*>(parent)->setItemDelegateForColumn(0, delegate); } QTipsItemDelegate::QTipsItemDelegate(QObject *parent, bool is_dark_theme_enabled, bool has_filter): QExtendedStyledItemDelegate(parent) { dark_theme = is_dark_theme_enabled; use_filter = has_filter; d_radius = 5; d_toppadding = 5; d_bottompadding = 3; d_leftpadding = 5; d_rightpadding = 5; d_verticalmargin = 15; d_horizontalmargin = 10; d_pointerwidth = 10; d_pointerheight = 17; d_widthfraction = 0.7; // TODO: Move this to the main stylesheet or palette. colour = QColor("#363636"); } // Function for the delegate to showup properly. void QTipsItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (use_filter && index.isValid()) { const QSortFilterProxyModel* filterModel = dynamic_cast<const QSortFilterProxyModel*>(index.model()); const QStandardItemModel* standardModel = dynamic_cast<const QStandardItemModel*>(filterModel->sourceModel()); QStandardItem* item = standardModel->itemFromIndex(filterModel->mapToSource(index)); if (item != nullptr) { QTextDocument bodydoc; QTextOption textOption(bodydoc.defaultTextOption()); textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); bodydoc.setDefaultTextOption(textOption); QString bodytext(item->data(Qt::DisplayRole).toString()); bodydoc.setHtml(bodytext); qreal contentswidth = option.rect.width() * d_widthfraction - d_horizontalmargin - d_pointerwidth - d_leftpadding - d_rightpadding; bodydoc.setTextWidth(contentswidth); qreal bodyheight = bodydoc.size().height(); painter->save(); painter->setRenderHint(QPainter::Antialiasing); painter->translate(option.rect.left() + d_horizontalmargin, option.rect.top() + ((item->row() == 0) ? d_verticalmargin : 0)); // background color for chat bubble QColor bgcolor = colour; // create chat bubble QPainterPath pointie; // left bottom pointie.moveTo(0, bodyheight + d_toppadding + d_bottompadding); // right bottom pointie.lineTo(0 + contentswidth + d_pointerwidth + d_leftpadding + d_rightpadding - d_radius, bodyheight + d_toppadding + d_bottompadding); pointie.arcTo(0 + contentswidth + d_pointerwidth + d_leftpadding + d_rightpadding - 2 * d_radius, bodyheight + d_toppadding + d_bottompadding - 2 * d_radius, 2 * d_radius, 2 * d_radius, 270, 90); // right top pointie.lineTo(0 + contentswidth + d_pointerwidth + d_leftpadding + d_rightpadding, 0 + d_radius); pointie.arcTo(0 + contentswidth + d_pointerwidth + d_leftpadding + d_rightpadding - 2 * d_radius, 0, 2 * d_radius, 2 * d_radius, 0, 90); // left top pointie.lineTo(0 + d_pointerwidth + d_radius, 0); pointie.arcTo(0 + d_pointerwidth, 0, 2 * d_radius, 2 * d_radius, 90, 90); // left bottom almost (here is the pointie) pointie.lineTo(0 + d_pointerwidth, bodyheight + d_toppadding + d_bottompadding - d_pointerheight); pointie.closeSubpath(); // now paint it! painter->setPen(QPen(bgcolor)); painter->drawPath(pointie); painter->fillPath(pointie, QBrush(bgcolor)); // set text color used to draw message body QAbstractTextDocumentLayout::PaintContext ctx; // draw body text painter->translate(d_pointerwidth + d_leftpadding, 0); bodydoc.documentLayout()->draw(painter, ctx); painter->restore(); } } } QSize QTipsItemDelegate::sizeHint(QStyleOptionViewItem const &option, QModelIndex const &index) const { if (use_filter && index.isValid()) { const QSortFilterProxyModel* filterModel = dynamic_cast<const QSortFilterProxyModel*>(index.model()); const QStandardItemModel* standardModel = dynamic_cast<const QStandardItemModel*>(filterModel->sourceModel()); QStandardItem* item = standardModel->itemFromIndex(filterModel->mapToSource(index)); if (item != nullptr) { QTextDocument bodydoc; QTextOption textOption(bodydoc.defaultTextOption()); textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); bodydoc.setDefaultTextOption(textOption); QString bodytext(item->data(Qt::DisplayRole).toString()); bodydoc.setHtml(bodytext); // the width of the contents are the (a fraction of the window width) minus (margins + padding + width of the bubble's tail) qreal contentswidth = option.rect.width() * d_widthfraction - d_horizontalmargin - d_pointerwidth - d_leftpadding - d_rightpadding; // set this available width on the text document bodydoc.setTextWidth(contentswidth); QSize size( bodydoc.idealWidth() + d_horizontalmargin + d_pointerwidth + d_leftpadding + d_rightpadding, bodydoc.size().height() + d_bottompadding + d_toppadding + d_verticalmargin + 1 ); // I dont remember why +1, haha, might not be necessary if (item->row() == 0) // have extra margin at top of first item size += QSize(0, d_verticalmargin); return size; } else { return QSize(0, 0); } } else { return QSize(0, 0); } }
[ "frodo_gv@hotmail.com" ]
frodo_gv@hotmail.com
1b12522c596c45f354d39221257cf83f8619df8b
e94e3961378a3a693c1c7b256e509e1afc10d218
/source/csp_data_buffer.h
06b15db406f469dcc18c1577cb3477c47416e247
[]
no_license
chaindge/csp_render
464978333f986caec75c050783d5ba8c86842ab7
afa1bd5a18439d4886d31d1ad9f56f9beb6544ff
refs/heads/master
2020-12-03T05:09:41.221378
2017-07-12T02:13:27
2017-07-12T02:13:27
95,740,285
0
0
null
null
null
null
UTF-8
C++
false
false
1,337
h
#ifndef CSP_DATA_BUFFER_H #define CSP_DATA_BUFFER_H #include <vector> #include <iostream> #include "csp_render_type.h" class csp_data_buffer { public: csp_data_buffer(float* vertex, unsigned int vertex_size, unsigned int * index, unsigned int index_size); void set_vertex(float* data, unsigned int data_size); void add_vertex(float* data, unsigned int data_size); void set_index(unsigned int* data, unsigned int data_size); void add_index(unsigned int* data, unsigned int data_size); bool get_data_from_vertex(std::vector<float>& data, unsigned int begin, unsigned int count); bool get_data_from_index(std::vector<float>& data, unsigned int begin, unsigned int count); std::vector<float>& get_vertex(); std::vector<unsigned int>& get_index(); protected: std::vector<float> m_vertex; std::vector<unsigned int> m_index; }; template<class T> void print_vector(std::ostream& out,const std::vector<T>& vec) { for (auto& item : vec) out << item << " "; } inline void print(std::ostream& out,csp_data_buffer& buffer) { out << "vertex :"; print_vector(out,buffer.get_vertex()); out << std::endl; out << "index :"; print_vector(out,buffer.get_index()); out << std::endl; } inline std::ostream& operator<<(std::ostream& out,csp_data_buffer& buffer) { print(out, buffer); return out; } #endif // !CSP_DATA_BUFFER_H
[ "243012279@qq.com" ]
243012279@qq.com
f79265e34a00f2469336babb5a5f245180d4eef1
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
/storage/browser/database/database_tracker.cc
1539b0cd64327d54474b7ebf4c6a2f43530d47d0
[ "BSD-3-Clause" ]
permissive
massnetwork/mass-browser
7de0dfc541cbac00ffa7308541394bac1e945b76
67526da9358734698c067b7775be491423884339
refs/heads/master
2022-12-07T09:01:31.027715
2017-01-19T14:29:18
2017-01-19T14:29:18
73,799,690
4
4
BSD-3-Clause
2022-11-26T11:53:23
2016-11-15T09:49:29
null
UTF-8
C++
false
false
30,738
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "storage/browser/database/database_tracker.h" #include <stdint.h> #include <algorithm> #include <utility> #include <vector> #include "base/bind.h" #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "net/base/net_errors.h" #include "sql/connection.h" #include "sql/meta_table.h" #include "sql/transaction.h" #include "storage/browser/database/database_quota_client.h" #include "storage/browser/database/database_util.h" #include "storage/browser/database/databases_table.h" #include "storage/browser/quota/quota_manager_proxy.h" #include "storage/browser/quota/special_storage_policy.h" #include "storage/common/database/database_identifier.h" #include "third_party/sqlite/sqlite3.h" namespace storage { const base::FilePath::CharType kDatabaseDirectoryName[] = FILE_PATH_LITERAL("databases"); const base::FilePath::CharType kIncognitoDatabaseDirectoryName[] = FILE_PATH_LITERAL("databases-incognito"); const base::FilePath::CharType kTrackerDatabaseFileName[] = FILE_PATH_LITERAL("Databases.db"); static const int kCurrentVersion = 2; static const int kCompatibleVersion = 1; const base::FilePath::CharType kTemporaryDirectoryPrefix[] = FILE_PATH_LITERAL("DeleteMe"); const base::FilePath::CharType kTemporaryDirectoryPattern[] = FILE_PATH_LITERAL("DeleteMe*"); OriginInfo::OriginInfo() : total_size_(0) {} OriginInfo::OriginInfo(const OriginInfo& origin_info) : origin_identifier_(origin_info.origin_identifier_), total_size_(origin_info.total_size_), database_info_(origin_info.database_info_) {} OriginInfo::~OriginInfo() {} void OriginInfo::GetAllDatabaseNames( std::vector<base::string16>* databases) const { for (DatabaseInfoMap::const_iterator it = database_info_.begin(); it != database_info_.end(); it++) { databases->push_back(it->first); } } int64_t OriginInfo::GetDatabaseSize(const base::string16& database_name) const { DatabaseInfoMap::const_iterator it = database_info_.find(database_name); if (it != database_info_.end()) return it->second.first; return 0; } base::string16 OriginInfo::GetDatabaseDescription( const base::string16& database_name) const { DatabaseInfoMap::const_iterator it = database_info_.find(database_name); if (it != database_info_.end()) return it->second.second; return base::string16(); } OriginInfo::OriginInfo(const std::string& origin_identifier, int64_t total_size) : origin_identifier_(origin_identifier), total_size_(total_size) {} DatabaseTracker::DatabaseTracker( const base::FilePath& profile_path, bool is_incognito, storage::SpecialStoragePolicy* special_storage_policy, storage::QuotaManagerProxy* quota_manager_proxy, base::SingleThreadTaskRunner* db_tracker_thread) : is_initialized_(false), is_incognito_(is_incognito), force_keep_session_state_(false), shutting_down_(false), profile_path_(profile_path), db_dir_(is_incognito_ ? profile_path_.Append(kIncognitoDatabaseDirectoryName) : profile_path_.Append(kDatabaseDirectoryName)), db_(new sql::Connection()), special_storage_policy_(special_storage_policy), quota_manager_proxy_(quota_manager_proxy), db_tracker_thread_(db_tracker_thread), incognito_origin_directories_generator_(0) { if (quota_manager_proxy) { quota_manager_proxy->RegisterClient( new DatabaseQuotaClient(db_tracker_thread, this)); } } DatabaseTracker::~DatabaseTracker() { DCHECK(dbs_to_be_deleted_.empty()); DCHECK(deletion_callbacks_.empty()); } void DatabaseTracker::DatabaseOpened(const std::string& origin_identifier, const base::string16& database_name, const base::string16& database_description, int64_t estimated_size, int64_t* database_size) { if (shutting_down_ || !LazyInit()) { *database_size = 0; return; } if (quota_manager_proxy_.get()) quota_manager_proxy_->NotifyStorageAccessed( storage::QuotaClient::kDatabase, storage::GetOriginFromIdentifier(origin_identifier), storage::kStorageTypeTemporary); InsertOrUpdateDatabaseDetails(origin_identifier, database_name, database_description, estimated_size); if (database_connections_.AddConnection(origin_identifier, database_name)) { *database_size = SeedOpenDatabaseInfo(origin_identifier, database_name, database_description); return; } *database_size = UpdateOpenDatabaseInfoAndNotify(origin_identifier, database_name, &database_description); } void DatabaseTracker::DatabaseModified(const std::string& origin_identifier, const base::string16& database_name) { if (!LazyInit()) return; UpdateOpenDatabaseSizeAndNotify(origin_identifier, database_name); } void DatabaseTracker::DatabaseClosed(const std::string& origin_identifier, const base::string16& database_name) { if (database_connections_.IsEmpty()) { DCHECK(!is_initialized_); return; } // We call NotifiyStorageAccessed when a db is opened and also when // closed because we don't call it for read while open. if (quota_manager_proxy_.get()) quota_manager_proxy_->NotifyStorageAccessed( storage::QuotaClient::kDatabase, storage::GetOriginFromIdentifier(origin_identifier), storage::kStorageTypeTemporary); UpdateOpenDatabaseSizeAndNotify(origin_identifier, database_name); if (database_connections_.RemoveConnection(origin_identifier, database_name)) DeleteDatabaseIfNeeded(origin_identifier, database_name); } void DatabaseTracker::HandleSqliteError( const std::string& origin_identifier, const base::string16& database_name, int error) { // We only handle errors that indicate corruption and we // do so with a heavy hand, we delete it. Any renderers/workers // with this database open will receive a message to close it // immediately, once all have closed, the files will be deleted. // In the interim, all attempts to open a new connection to that // database will fail. // Note: the client-side filters out all but these two errors as // a small optimization, see WebDatabaseObserverImpl::HandleSqliteError. if (error == SQLITE_CORRUPT || error == SQLITE_NOTADB) { DeleteDatabase(origin_identifier, database_name, net::CompletionCallback()); } } void DatabaseTracker::CloseDatabases(const DatabaseConnections& connections) { if (database_connections_.IsEmpty()) { DCHECK(!is_initialized_ || connections.IsEmpty()); return; } // When being closed by this route, there's a chance that // the tracker missed some DatabseModified calls. This method is used // when a renderer crashes to cleanup its open resources. // We need to examine what we have in connections for the // size of each open databases and notify any differences between the // actual file sizes now. std::vector<std::pair<std::string, base::string16> > open_dbs; connections.ListConnections(&open_dbs); for (std::vector<std::pair<std::string, base::string16> >::iterator it = open_dbs.begin(); it != open_dbs.end(); ++it) UpdateOpenDatabaseSizeAndNotify(it->first, it->second); std::vector<std::pair<std::string, base::string16> > closed_dbs; database_connections_.RemoveConnections(connections, &closed_dbs); for (std::vector<std::pair<std::string, base::string16> >::iterator it = closed_dbs.begin(); it != closed_dbs.end(); ++it) { DeleteDatabaseIfNeeded(it->first, it->second); } } void DatabaseTracker::DeleteDatabaseIfNeeded( const std::string& origin_identifier, const base::string16& database_name) { DCHECK(!database_connections_.IsDatabaseOpened(origin_identifier, database_name)); if (IsDatabaseScheduledForDeletion(origin_identifier, database_name)) { DeleteClosedDatabase(origin_identifier, database_name); dbs_to_be_deleted_[origin_identifier].erase(database_name); if (dbs_to_be_deleted_[origin_identifier].empty()) dbs_to_be_deleted_.erase(origin_identifier); PendingDeletionCallbacks::iterator callback = deletion_callbacks_.begin(); while (callback != deletion_callbacks_.end()) { DatabaseSet::iterator found_origin = callback->second.find(origin_identifier); if (found_origin != callback->second.end()) { std::set<base::string16>& databases = found_origin->second; databases.erase(database_name); if (databases.empty()) { callback->second.erase(found_origin); if (callback->second.empty()) { net::CompletionCallback cb = callback->first; cb.Run(net::OK); callback = deletion_callbacks_.erase(callback); continue; } } } ++callback; } } } void DatabaseTracker::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void DatabaseTracker::RemoveObserver(Observer* observer) { // When we remove a listener, we do not know which cached information // is still needed and which information can be discarded. So we just // clear all caches and re-populate them as needed. observers_.RemoveObserver(observer); ClearAllCachedOriginInfo(); } void DatabaseTracker::CloseTrackerDatabaseAndClearCaches() { ClearAllCachedOriginInfo(); if (!is_incognito_) { meta_table_.reset(NULL); databases_table_.reset(NULL); db_->Close(); is_initialized_ = false; } } base::string16 DatabaseTracker::GetOriginDirectory( const std::string& origin_identifier) { if (!is_incognito_) return base::UTF8ToUTF16(origin_identifier); OriginDirectoriesMap::const_iterator it = incognito_origin_directories_.find(origin_identifier); if (it != incognito_origin_directories_.end()) return it->second; base::string16 origin_directory = base::IntToString16(incognito_origin_directories_generator_++); incognito_origin_directories_[origin_identifier] = origin_directory; return origin_directory; } base::FilePath DatabaseTracker::GetFullDBFilePath( const std::string& origin_identifier, const base::string16& database_name) { DCHECK(!origin_identifier.empty()); if (!LazyInit()) return base::FilePath(); int64_t id = databases_table_->GetDatabaseID(origin_identifier, database_name); if (id < 0) return base::FilePath(); return db_dir_.Append(base::FilePath::FromUTF16Unsafe( GetOriginDirectory(origin_identifier))).AppendASCII( base::Int64ToString(id)); } bool DatabaseTracker::GetOriginInfo(const std::string& origin_identifier, OriginInfo* info) { DCHECK(info); CachedOriginInfo* cached_info = GetCachedOriginInfo(origin_identifier); if (!cached_info) return false; *info = OriginInfo(*cached_info); return true; } bool DatabaseTracker::GetAllOriginIdentifiers( std::vector<std::string>* origin_identifiers) { DCHECK(origin_identifiers); DCHECK(origin_identifiers->empty()); if (!LazyInit()) return false; return databases_table_->GetAllOriginIdentifiers(origin_identifiers); } bool DatabaseTracker::GetAllOriginsInfo( std::vector<OriginInfo>* origins_info) { DCHECK(origins_info); DCHECK(origins_info->empty()); std::vector<std::string> origins; if (!GetAllOriginIdentifiers(&origins)) return false; for (std::vector<std::string>::const_iterator it = origins.begin(); it != origins.end(); it++) { CachedOriginInfo* origin_info = GetCachedOriginInfo(*it); if (!origin_info) { // Restore 'origins_info' to its initial state. origins_info->clear(); return false; } origins_info->push_back(OriginInfo(*origin_info)); } return true; } bool DatabaseTracker::DeleteClosedDatabase( const std::string& origin_identifier, const base::string16& database_name) { if (!LazyInit()) return false; // Check if the database is opened by any renderer. if (database_connections_.IsDatabaseOpened(origin_identifier, database_name)) return false; int64_t db_file_size = quota_manager_proxy_.get() ? GetDBFileSize(origin_identifier, database_name) : 0; // Try to delete the file on the hard drive. base::FilePath db_file = GetFullDBFilePath(origin_identifier, database_name); if (!sql::Connection::Delete(db_file)) return false; if (quota_manager_proxy_.get() && db_file_size) quota_manager_proxy_->NotifyStorageModified( storage::QuotaClient::kDatabase, storage::GetOriginFromIdentifier(origin_identifier), storage::kStorageTypeTemporary, -db_file_size); // Clean up the main database and invalidate the cached record. databases_table_->DeleteDatabaseDetails(origin_identifier, database_name); origins_info_map_.erase(origin_identifier); std::vector<DatabaseDetails> details; if (databases_table_->GetAllDatabaseDetailsForOriginIdentifier( origin_identifier, &details) && details.empty()) { // Try to delete the origin in case this was the last database. DeleteOrigin(origin_identifier, false); } return true; } bool DatabaseTracker::DeleteOrigin(const std::string& origin_identifier, bool force) { if (!LazyInit()) return false; // Check if any database in this origin is opened by any renderer. if (database_connections_.IsOriginUsed(origin_identifier) && !force) return false; int64_t deleted_size = 0; if (quota_manager_proxy_.get()) { CachedOriginInfo* origin_info = GetCachedOriginInfo(origin_identifier); if (origin_info) deleted_size = origin_info->TotalSize(); } origins_info_map_.erase(origin_identifier); base::FilePath origin_dir = db_dir_.AppendASCII(origin_identifier); // Create a temporary directory to move possibly still existing databases to, // as we can't delete the origin directory on windows if it contains opened // files. base::FilePath new_origin_dir; base::CreateTemporaryDirInDir(db_dir_, kTemporaryDirectoryPrefix, &new_origin_dir); base::FileEnumerator databases( origin_dir, false, base::FileEnumerator::FILES); for (base::FilePath database = databases.Next(); !database.empty(); database = databases.Next()) { base::FilePath new_file = new_origin_dir.Append(database.BaseName()); base::Move(database, new_file); } base::DeleteFile(origin_dir, true); base::DeleteFile(new_origin_dir, true); // might fail on windows. databases_table_->DeleteOriginIdentifier(origin_identifier); if (quota_manager_proxy_.get() && deleted_size) { quota_manager_proxy_->NotifyStorageModified( storage::QuotaClient::kDatabase, storage::GetOriginFromIdentifier(origin_identifier), storage::kStorageTypeTemporary, -deleted_size); } return true; } bool DatabaseTracker::IsDatabaseScheduledForDeletion( const std::string& origin_identifier, const base::string16& database_name) { DatabaseSet::iterator it = dbs_to_be_deleted_.find(origin_identifier); if (it == dbs_to_be_deleted_.end()) return false; std::set<base::string16>& databases = it->second; return (databases.find(database_name) != databases.end()); } bool DatabaseTracker::LazyInit() { if (!is_initialized_ && !shutting_down_) { DCHECK(!db_->is_open()); DCHECK(!databases_table_.get()); DCHECK(!meta_table_.get()); // If there are left-over directories from failed deletion attempts, clean // them up. if (base::DirectoryExists(db_dir_)) { base::FileEnumerator directories( db_dir_, false, base::FileEnumerator::DIRECTORIES, kTemporaryDirectoryPattern); for (base::FilePath directory = directories.Next(); !directory.empty(); directory = directories.Next()) { base::DeleteFile(directory, true); } } db_->set_histogram_tag("DatabaseTracker"); // If the tracker database exists, but it's corrupt or doesn't // have a meta table, delete the database directory. const base::FilePath kTrackerDatabaseFullPath = db_dir_.Append(base::FilePath(kTrackerDatabaseFileName)); if (base::DirectoryExists(db_dir_) && base::PathExists(kTrackerDatabaseFullPath) && (!db_->Open(kTrackerDatabaseFullPath) || !sql::MetaTable::DoesTableExist(db_.get()))) { db_->Close(); if (!base::DeleteFile(db_dir_, true)) return false; } databases_table_.reset(new DatabasesTable(db_.get())); meta_table_.reset(new sql::MetaTable()); is_initialized_ = base::CreateDirectory(db_dir_) && (db_->is_open() || (is_incognito_ ? db_->OpenInMemory() : db_->Open(kTrackerDatabaseFullPath))) && UpgradeToCurrentVersion(); if (!is_initialized_) { databases_table_.reset(NULL); meta_table_.reset(NULL); db_->Close(); } } return is_initialized_; } bool DatabaseTracker::UpgradeToCurrentVersion() { sql::Transaction transaction(db_.get()); if (!transaction.Begin() || !meta_table_->Init(db_.get(), kCurrentVersion, kCompatibleVersion) || (meta_table_->GetCompatibleVersionNumber() > kCurrentVersion) || !databases_table_->Init()) return false; if (meta_table_->GetVersionNumber() < kCurrentVersion) meta_table_->SetVersionNumber(kCurrentVersion); return transaction.Commit(); } void DatabaseTracker::InsertOrUpdateDatabaseDetails( const std::string& origin_identifier, const base::string16& database_name, const base::string16& database_description, int64_t estimated_size) { DatabaseDetails details; if (!databases_table_->GetDatabaseDetails( origin_identifier, database_name, &details)) { details.origin_identifier = origin_identifier; details.database_name = database_name; details.description = database_description; details.estimated_size = estimated_size; databases_table_->InsertDatabaseDetails(details); } else if ((details.description != database_description) || (details.estimated_size != estimated_size)) { details.description = database_description; details.estimated_size = estimated_size; databases_table_->UpdateDatabaseDetails(details); } } void DatabaseTracker::ClearAllCachedOriginInfo() { origins_info_map_.clear(); } DatabaseTracker::CachedOriginInfo* DatabaseTracker::MaybeGetCachedOriginInfo( const std::string& origin_identifier, bool create_if_needed) { if (!LazyInit()) return NULL; // Populate the cache with data for this origin if needed. if (origins_info_map_.find(origin_identifier) == origins_info_map_.end()) { if (!create_if_needed) return NULL; std::vector<DatabaseDetails> details; if (!databases_table_->GetAllDatabaseDetailsForOriginIdentifier( origin_identifier, &details)) { return NULL; } CachedOriginInfo& origin_info = origins_info_map_[origin_identifier]; origin_info.SetOriginIdentifier(origin_identifier); for (std::vector<DatabaseDetails>::const_iterator it = details.begin(); it != details.end(); it++) { int64_t db_file_size; if (database_connections_.IsDatabaseOpened( origin_identifier, it->database_name)) { db_file_size = database_connections_.GetOpenDatabaseSize( origin_identifier, it->database_name); } else { db_file_size = GetDBFileSize(origin_identifier, it->database_name); } origin_info.SetDatabaseSize(it->database_name, db_file_size); origin_info.SetDatabaseDescription(it->database_name, it->description); } } return &origins_info_map_[origin_identifier]; } int64_t DatabaseTracker::GetDBFileSize(const std::string& origin_identifier, const base::string16& database_name) { base::FilePath db_file_name = GetFullDBFilePath(origin_identifier, database_name); int64_t db_file_size = 0; if (!base::GetFileSize(db_file_name, &db_file_size)) db_file_size = 0; return db_file_size; } int64_t DatabaseTracker::SeedOpenDatabaseInfo( const std::string& origin_id, const base::string16& name, const base::string16& description) { DCHECK(database_connections_.IsDatabaseOpened(origin_id, name)); int64_t size = GetDBFileSize(origin_id, name); database_connections_.SetOpenDatabaseSize(origin_id, name, size); CachedOriginInfo* info = MaybeGetCachedOriginInfo(origin_id, false); if (info) { info->SetDatabaseSize(name, size); info->SetDatabaseDescription(name, description); } return size; } int64_t DatabaseTracker::UpdateOpenDatabaseInfoAndNotify( const std::string& origin_id, const base::string16& name, const base::string16* opt_description) { DCHECK(database_connections_.IsDatabaseOpened(origin_id, name)); int64_t new_size = GetDBFileSize(origin_id, name); int64_t old_size = database_connections_.GetOpenDatabaseSize(origin_id, name); CachedOriginInfo* info = MaybeGetCachedOriginInfo(origin_id, false); if (info && opt_description) info->SetDatabaseDescription(name, *opt_description); if (old_size != new_size) { database_connections_.SetOpenDatabaseSize(origin_id, name, new_size); if (info) info->SetDatabaseSize(name, new_size); if (quota_manager_proxy_.get()) quota_manager_proxy_->NotifyStorageModified( storage::QuotaClient::kDatabase, storage::GetOriginFromIdentifier(origin_id), storage::kStorageTypeTemporary, new_size - old_size); for (auto& observer : observers_) observer.OnDatabaseSizeChanged(origin_id, name, new_size); } return new_size; } void DatabaseTracker::ScheduleDatabaseForDeletion( const std::string& origin_identifier, const base::string16& database_name) { DCHECK(database_connections_.IsDatabaseOpened(origin_identifier, database_name)); dbs_to_be_deleted_[origin_identifier].insert(database_name); for (auto& observer : observers_) observer.OnDatabaseScheduledForDeletion(origin_identifier, database_name); } void DatabaseTracker::ScheduleDatabasesForDeletion( const DatabaseSet& databases, const net::CompletionCallback& callback) { DCHECK(!databases.empty()); if (!callback.is_null()) deletion_callbacks_.push_back(std::make_pair(callback, databases)); for (DatabaseSet::const_iterator ori = databases.begin(); ori != databases.end(); ++ori) { for (std::set<base::string16>::const_iterator db = ori->second.begin(); db != ori->second.end(); ++db) ScheduleDatabaseForDeletion(ori->first, *db); } } int DatabaseTracker::DeleteDatabase(const std::string& origin_identifier, const base::string16& database_name, const net::CompletionCallback& callback) { if (!LazyInit()) return net::ERR_FAILED; if (database_connections_.IsDatabaseOpened(origin_identifier, database_name)) { if (!callback.is_null()) { DatabaseSet set; set[origin_identifier].insert(database_name); deletion_callbacks_.push_back(std::make_pair(callback, set)); } ScheduleDatabaseForDeletion(origin_identifier, database_name); return net::ERR_IO_PENDING; } DeleteClosedDatabase(origin_identifier, database_name); return net::OK; } int DatabaseTracker::DeleteDataModifiedSince( const base::Time& cutoff, const net::CompletionCallback& callback) { if (!LazyInit()) return net::ERR_FAILED; DatabaseSet to_be_deleted; std::vector<std::string> origins_identifiers; if (!databases_table_->GetAllOriginIdentifiers(&origins_identifiers)) return net::ERR_FAILED; int rv = net::OK; for (std::vector<std::string>::const_iterator ori = origins_identifiers.begin(); ori != origins_identifiers.end(); ++ori) { if (special_storage_policy_.get() && special_storage_policy_->IsStorageProtected( storage::GetOriginFromIdentifier(*ori))) { continue; } std::vector<DatabaseDetails> details; if (!databases_table_-> GetAllDatabaseDetailsForOriginIdentifier(*ori, &details)) rv = net::ERR_FAILED; for (std::vector<DatabaseDetails>::const_iterator db = details.begin(); db != details.end(); ++db) { base::FilePath db_file = GetFullDBFilePath(*ori, db->database_name); base::File::Info file_info; base::GetFileInfo(db_file, &file_info); if (file_info.last_modified < cutoff) continue; // Check if the database is opened by any renderer. if (database_connections_.IsDatabaseOpened(*ori, db->database_name)) to_be_deleted[*ori].insert(db->database_name); else DeleteClosedDatabase(*ori, db->database_name); } } if (rv != net::OK) return rv; if (!to_be_deleted.empty()) { ScheduleDatabasesForDeletion(to_be_deleted, callback); return net::ERR_IO_PENDING; } return net::OK; } int DatabaseTracker::DeleteDataForOrigin( const std::string& origin, const net::CompletionCallback& callback) { if (!LazyInit()) return net::ERR_FAILED; DatabaseSet to_be_deleted; std::vector<DatabaseDetails> details; if (!databases_table_-> GetAllDatabaseDetailsForOriginIdentifier(origin, &details)) return net::ERR_FAILED; for (std::vector<DatabaseDetails>::const_iterator db = details.begin(); db != details.end(); ++db) { // Check if the database is opened by any renderer. if (database_connections_.IsDatabaseOpened(origin, db->database_name)) to_be_deleted[origin].insert(db->database_name); else DeleteClosedDatabase(origin, db->database_name); } if (!to_be_deleted.empty()) { ScheduleDatabasesForDeletion(to_be_deleted, callback); return net::ERR_IO_PENDING; } return net::OK; } const base::File* DatabaseTracker::GetIncognitoFile( const base::string16& vfs_file_name) const { DCHECK(is_incognito_); FileHandlesMap::const_iterator it = incognito_file_handles_.find(vfs_file_name); if (it != incognito_file_handles_.end()) return it->second; return NULL; } const base::File* DatabaseTracker::SaveIncognitoFile( const base::string16& vfs_file_name, base::File file) { DCHECK(is_incognito_); if (!file.IsValid()) return NULL; base::File* to_insert = new base::File(std::move(file)); std::pair<FileHandlesMap::iterator, bool> rv = incognito_file_handles_.insert(std::make_pair(vfs_file_name, to_insert)); DCHECK(rv.second); return rv.first->second; } void DatabaseTracker::CloseIncognitoFileHandle( const base::string16& vfs_file_name) { DCHECK(is_incognito_); DCHECK(incognito_file_handles_.find(vfs_file_name) != incognito_file_handles_.end()); FileHandlesMap::iterator it = incognito_file_handles_.find(vfs_file_name); if (it != incognito_file_handles_.end()) { delete it->second; incognito_file_handles_.erase(it); } } bool DatabaseTracker::HasSavedIncognitoFileHandle( const base::string16& vfs_file_name) const { return (incognito_file_handles_.find(vfs_file_name) != incognito_file_handles_.end()); } void DatabaseTracker::DeleteIncognitoDBDirectory() { is_initialized_ = false; for (FileHandlesMap::iterator it = incognito_file_handles_.begin(); it != incognito_file_handles_.end(); it++) { delete it->second; } base::FilePath incognito_db_dir = profile_path_.Append(kIncognitoDatabaseDirectoryName); if (base::DirectoryExists(incognito_db_dir)) base::DeleteFile(incognito_db_dir, true); } void DatabaseTracker::ClearSessionOnlyOrigins() { bool has_session_only_databases = special_storage_policy_.get() && special_storage_policy_->HasSessionOnlyOrigins(); // Clearing only session-only databases, and there are none. if (!has_session_only_databases) return; if (!LazyInit()) return; std::vector<std::string> origin_identifiers; GetAllOriginIdentifiers(&origin_identifiers); for (std::vector<std::string>::iterator origin = origin_identifiers.begin(); origin != origin_identifiers.end(); ++origin) { GURL origin_url = storage::GetOriginFromIdentifier(*origin); if (!special_storage_policy_->IsStorageSessionOnly(origin_url)) continue; if (special_storage_policy_->IsStorageProtected(origin_url)) continue; storage::OriginInfo origin_info; std::vector<base::string16> databases; GetOriginInfo(*origin, &origin_info); origin_info.GetAllDatabaseNames(&databases); for (std::vector<base::string16>::iterator database = databases.begin(); database != databases.end(); ++database) { base::File file(GetFullDBFilePath(*origin, *database), base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_SHARE_DELETE | base::File::FLAG_DELETE_ON_CLOSE | base::File::FLAG_READ); } DeleteOrigin(*origin, true); } } void DatabaseTracker::Shutdown() { DCHECK(db_tracker_thread_.get()); DCHECK(db_tracker_thread_->BelongsToCurrentThread()); if (shutting_down_) { NOTREACHED(); return; } shutting_down_ = true; if (is_incognito_) DeleteIncognitoDBDirectory(); else if (!force_keep_session_state_) ClearSessionOnlyOrigins(); CloseTrackerDatabaseAndClearCaches(); } void DatabaseTracker::SetForceKeepSessionState() { DCHECK(db_tracker_thread_.get()); if (!db_tracker_thread_->BelongsToCurrentThread()) { db_tracker_thread_->PostTask( FROM_HERE, base::Bind(&DatabaseTracker::SetForceKeepSessionState, this)); return; } force_keep_session_state_ = true; } } // namespace storage
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
3dfd20417b3c1dd212982f418fcad194decf5fc0
7f73763935257ce9305b06c41ed7dd25076d4c99
/Graphics/Camera/Camera.h
9835e23d3d83597cadf271a7a4377ae4d25b39d1
[]
no_license
MarcVinas/mastervj-basic-engine
08f57fa66a339e325c1787b7f5f15d3aa1633109
109342c9a7c30ee40af0fd845e92ecb0f8aa870a
refs/heads/master
2021-01-18T02:04:39.456741
2015-12-02T20:14:01
2015-12-02T20:14:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,607
h
#ifndef INC_CAMERA_H_ #define INC_CAMERA_H_ #include "Math/Matrix44.h" #include "Math/Vector3.h" class CCamera { private: Mat44f m_View; Mat44f m_Projection; Vect3f m_Position; Vect3f m_LookAt; Vect3f m_Up; float m_FOV; float m_AspectRatio; float m_ZNear; float m_ZFar; public: CCamera() : m_FOV(/*60.0f*/ 1.047198f) , m_AspectRatio(1.0f) , m_ZNear(0.1f) , m_ZFar(100.0f) , m_Position(5.0f, 5.0f, 0.0f) , m_LookAt(0.0f, 0.0f, 0.0f) , m_Up(0.0f, 1.0f, 0.0f) {} virtual ~CCamera() {} void SetFOV(float FOV) {m_FOV=FOV;} float GetFOV() const {return m_FOV;} void SetAspectRatio(float AspectRatio) {m_AspectRatio=AspectRatio;} float GetAspectRatio() const {return m_AspectRatio;} void SetZNear(float ZNear) {m_ZNear=ZNear;} float GetZNear() const {return m_ZNear;} void SetZFar(float ZFar) {m_ZFar=ZFar;} float GetZFar() const {return m_ZFar;} void SetPosition(const Vect3f &Position) { m_Position=Position; } const Vect3f & GetPosition() const { return m_Position; } void SetLookAt(const Vect3f &LookAt) { m_LookAt=LookAt; } const Vect3f & GetLookAt() const { return m_LookAt; } void SetUp(const Vect3f &Up) { m_Up=Up; } const Vect3f & GetUp() const { return m_Up; } const Mat44f & GetView() const { return m_View; } const Mat44f & GetProjection() const { return m_Projection; } void SetMatrixs() { m_View.SetIdentity(); m_View.SetFromLookAt(m_Position, m_LookAt, m_Up); m_Projection.SetIdentity(); m_Projection.SetFromPerspective(m_FOV, m_AspectRatio, m_ZNear, m_ZFar); } }; #endif
[ "rcrmn16@gmail.com" ]
rcrmn16@gmail.com
337660502eceea0db078bce0acbb47503fbe4058
727c574f0b5d84ae485b852ccf318063cc51772e
/ZOJ/ACM answer/zp1200_p.cpp
a74efdf16b1ae8e2f1120f05b179aab04b714a9a
[]
no_license
cowtony/ACM
36cf2202e3878a3dac1f15265ba8f902f9f67ac8
307707b2b2a37c58bc2632ef872dfccdee3264ce
refs/heads/master
2023-09-01T01:21:28.777542
2023-08-04T03:10:23
2023-08-04T03:10:23
245,681,952
7
3
null
null
null
null
UTF-8
C++
false
false
934
cpp
#include <iostream.h> long long max,tt,mt,i,s,w,nc,c,k,m; long long a[10000]; void work() { long t,t1,nn; t=1;nn=a[1]; while (t<k) { t1=t<<1; if (t1>k) break; if (t1<k) if (a[t1]>a[t1+1]) t1=t1+1; if (nn<=a[t1]) break; a[t]=a[t1]; t=t1; } a[t]=nn; } int main() { while (cin>>s>>w>>c>>k>>m) { nc=10000/c; if (10000%c!=0) nc++; if (k>nc) k=nc; tt=m; for (i=1;i<=k;i++) { a[i]=tt; tt=tt+m; } max=0; mt=0; for (i=1;i<=nc;i++) { tt=a[1]; tt=tt+s; if (tt<mt) tt=mt; tt=tt+w; mt=tt; tt=tt+s; if (max<tt) max=tt; a[1]=tt; work; } cout<<tt<<endl; } return 0; } //---------------------------------------------------------------------------
[ "cowtony@163.com" ]
cowtony@163.com
724feeb00c5ac15beb188aed421dbdb839faac9c
c77a8579ab98ba0c6eaaf36ac1382cb2b1a4046c
/1183G - Candy Box (hard version).cpp
e7cda4a5f2c31e7481ac8dd4034251d28a2efe94
[]
no_license
arjunbhatt670/CodeForces
2dadb9f53bcd6cfa1b1146524624320434991995
b358049e3da7d9c3bbc8f03986e364be1925688b
refs/heads/master
2022-04-07T19:02:42.320001
2020-03-21T06:44:02
2020-03-21T06:44:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
964
cpp
/* * User: Isanchez_Aguilar * Problem: CodeForces 1183G - Candy Box (hard version) */ #include <bits/stdc++.h> using namespace std; int main(void) { ios_base::sync_with_stdio(0); cin.tie(0); int q; cin >> q; while (q--) { int n; cin >> n; vector<int> freq(n); vector<int> goodFreq(n); for (int i = 0; i < n; ++i) { int a, f; cin >> a >> f; --a; ++freq[a]; if (f == 1) ++goodFreq[a]; } vector<int> candiesFreq[n + 1]; for (int i = 0; i < n; ++i) candiesFreq[freq[i]].push_back(goodFreq[i]); int ansGood = 0; int ansCandies = 0; multiset< int, greater<int> > goodCandies; for (int i = n; i > 0; --i) { for (int freqGood : candiesFreq[i]) goodCandies.insert(freqGood); if (not goodCandies.empty()) { ansCandies += i; ansGood += min(i, *begin(goodCandies)); goodCandies.erase(begin(goodCandies)); } } cout << ansCandies << " " << ansGood << "\n"; } return 0; }
[ "saais31@gmail.com" ]
saais31@gmail.com
dadd17a4fd8810ff4871563e9a88956584ae94f6
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir35435/file40639.cpp
5f687f3142e19ad58ffd290077be4674877a9848
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#ifndef file40639 #error "macro file40639 must be defined" #endif static const char* file40639String = "file40639";
[ "tgeng@google.com" ]
tgeng@google.com
fc247281e32f65b78047eba4127de61132975d4d
e4a6238014f6522ed5c2bc15e85e1012bf1e9514
/11-QuickSort/03-QuickSort/SortingHelper.h
40df6b852ca1eb0bc025ce766c43ea64c5c719e0
[]
no_license
jiangyang118/Play-Algorithms-and-Data-Structures-CPP
dcd527a1ee778047592b1ae0dd575b43a15ed902
03b9872071c1da6f514207b87a0b224e834c9f8b
refs/heads/main
2023-04-25T07:55:42.697351
2021-05-17T17:20:48
2021-05-17T17:20:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,584
h
#ifndef __SORTINGHELPER_H__ #define __SORTINGHELPER_H__ #include <iostream> #include <string> #include "SelectionSort.h" #include "InsertionSort.h" #include "MergeSort.h" #include "QuickSort.h" using namespace std; class SortingHelper { private: SortingHelper() { } public: template <typename T> static bool isSorted(T arr[], int n) { for(int i = 1; i < n; i++) { if(arr[i - 1] > arr[i]) { return false; } } return true; } template <typename T> static void sortTest(const string& sortname, T arr[], int n) { auto start = std::chrono::steady_clock::now(); if(sortname.compare("SelectionSort") == 0) { SelectionSort::sort(arr, n); } else if(sortname.compare("InsertionSort") == 0) { InsertionSort::sort(arr, n); } else if(sortname.compare("MergeSort") == 0) { MergeSort::sort(arr, n); } else if(sortname.compare("MergeSortBU") == 0) { MergeSort::sortBU(arr, n); } else if(sortname.compare("QuickSort") == 0) { QuickSort::sort(arr, n); } auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> time = end - start; if(!SortingHelper::isSorted(arr, n)) { throw std::runtime_error(sortname + " Failed"); } cout << sortname << ", n = " << n << " : " << time.count() << " s" << endl; } }; #endif
[ "ywj123450@gmail.com" ]
ywj123450@gmail.com
c9faa5be29ded4ebe18a85ec7e0cd0d3c80e8b83
e7d1fa9c5093d20550d2664be236106f3830d172
/main.cpp
b39aff9cd1ad991bbfa5e46141ce51bb24fa124f
[]
no_license
rcsteins/effective_noname
b644b7ec810b232c930704b625ff7b9c419de1c0
eee0a965d242a892ee5826c84bcd7070a5a75048
refs/heads/master
2020-04-07T09:02:53.749835
2018-11-19T14:37:30
2018-11-19T14:37:30
158,238,068
0
0
null
null
null
null
UTF-8
C++
false
false
130
cpp
#include <ctime> #include "main_loop.h" int main () { std::srand (time(NULL)); MainLoop gm; gm.run(); return 0; }
[ "rcsteins@gmail.com" ]
rcsteins@gmail.com
ddf4d3017d70c90a73563729e3f5f780f519306b
38616fa53a78f61d866ad4f2d3251ef471366229
/3rdparty/RobustGNSS/gtsam/gtsam/nonlinear/IncrementalFixedLagSmoother.h
3df22c0ac0c4eabd86cf88d74116744521a0f857
[ "MIT", "BSD-3-Clause", "LGPL-2.1-only", "MPL-2.0", "LGPL-2.0-or-later", "BSD-2-Clause" ]
permissive
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
3b467fa6d3f34cabbd5ee59596ac1950aabf2522
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
refs/heads/master
2020-06-08T12:42:31.977541
2019-06-10T15:04:33
2019-06-10T15:04:33
193,229,646
1
0
MIT
2019-06-22T12:07:29
2019-06-22T12:07:29
null
UTF-8
C++
false
false
4,999
h
/* ---------------------------------------------------------------------------- * GTSAM Copyright 2010, Georgia Tech Research Corporation, * Atlanta, Georgia 30332-0415 * All Rights Reserved * Authors: Frank Dellaert, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file IncrementalFixedLagSmoother.h * @brief An iSAM2-based fixed-lag smoother. * * @author Michael Kaess, Stephen Williams * @date Oct 14, 2012 */ // \callgraph #pragma once #include <gtsam/nonlinear/FixedLagSmoother.h> #include <gtsam/nonlinear/ISAM2.h> namespace gtsam { /** * This is a base class for the various HMF2 implementations. The HMF2 eliminates the factor graph * such that the active states are placed in/near the root. This base class implements a function * to calculate the ordering, and an update function to incorporate new factors into the HMF. */ class GTSAM_EXPORT IncrementalFixedLagSmoother : public FixedLagSmoother { public: /// Typedef for a shared pointer to an Incremental Fixed-Lag Smoother typedef boost::shared_ptr<IncrementalFixedLagSmoother> shared_ptr; /** default constructor */ IncrementalFixedLagSmoother(double smootherLag = 0.0, const ISAM2Params& parameters = ISAM2Params()) : FixedLagSmoother(smootherLag), isam_(parameters) { } /** destructor */ virtual ~IncrementalFixedLagSmoother() { } /** Print the factor for debugging and testing (implementing Testable) */ virtual void print(const std::string& s = "IncrementalFixedLagSmoother:\n", const KeyFormatter& keyFormatter = DefaultKeyFormatter) const; /** Check if two IncrementalFixedLagSmoother Objects are equal */ virtual bool equals(const FixedLagSmoother& rhs, double tol = 1e-9) const; /** * Add new factors, updating the solution and re-linearizing as needed. * @param newFactors new factors on old and/or new variables * @param newTheta new values for new variables only * @param timestamps an (optional) map from keys to real time stamps */ Result update(const NonlinearFactorGraph& newFactors = NonlinearFactorGraph(), const Values& newTheta = Values(), // const KeyTimestampMap& timestamps = KeyTimestampMap()); /** Compute an estimate from the incomplete linear delta computed during the last update. * This delta is incomplete because it was not updated below wildfire_threshold. If only * a single variable is needed, it is faster to call calculateEstimate(const KEY&). */ Values calculateEstimate() const { return isam_.calculateEstimate(); } /** Compute an estimate for a single variable using its incomplete linear delta computed * during the last update. This is faster than calling the no-argument version of * calculateEstimate, which operates on all variables. * @param key * @return */ template<class VALUE> VALUE calculateEstimate(Key key) const { return isam_.calculateEstimate<VALUE>(key); } /** return the current set of iSAM2 parameters */ const ISAM2Params& params() const { return isam_.params(); } /** Access the current set of factors */ const NonlinearFactorGraph& getFactors() const { return isam_.getFactorsUnsafe(); } /** Access the current linearization point */ const Values& getLinearizationPoint() const { return isam_.getLinearizationPoint(); } /** Access the current set of deltas to the linearization point */ const VectorValues& getDelta() const { return isam_.getDelta(); } /// Calculate marginal covariance on given variable Matrix marginalCovariance(Key key) const { return isam_.marginalCovariance(key); } protected: /** An iSAM2 object used to perform inference. The smoother lag is controlled * by what factors are removed each iteration */ ISAM2 isam_; /** Erase any keys associated with timestamps before the provided time */ void eraseKeysBefore(double timestamp); /** Fill in an iSAM2 ConstrainedKeys structure such that the provided keys are eliminated before all others */ void createOrderingConstraints(const KeyVector& marginalizableKeys, boost::optional<FastMap<Key, int> >& constrainedKeys) const; private: /** Private methods for printing debug information */ static void PrintKeySet(const std::set<Key>& keys, const std::string& label = "Keys:"); static void PrintSymbolicFactor(const GaussianFactor::shared_ptr& factor); static void PrintSymbolicGraph(const GaussianFactorGraph& graph, const std::string& label = "Factor Graph:"); static void PrintSymbolicTree(const gtsam::ISAM2& isam, const std::string& label = "Bayes Tree:"); static void PrintSymbolicTreeHelper( const gtsam::ISAM2Clique::shared_ptr& clique, const std::string indent = ""); }; // IncrementalFixedLagSmoother } /// namespace gtsam
[ "rwatso12@gmail.com" ]
rwatso12@gmail.com
ba0f366fe24e3a11382a5729a702ccc627e000f2
257345713b716359e17956f4c2a9565b35095faa
/src/collision/BIH.h
b76b3147b260e81506cbac1ed97ba7a261cc5800
[]
no_license
romseguy/Trinitycore_Azshara_2.4.3
632856d0df8fa36a9309dcd7a8cf9565d0ab2a53
699c956afefe9e06c5ec526ca3c34439a0178b7a
refs/heads/master
2021-01-01T17:22:07.623920
2014-07-31T16:31:27
2014-07-31T16:31:27
22,476,550
1
5
null
null
null
null
UTF-8
C++
false
false
14,273
h
/* * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/> * * Copyright (C) 2010 Oregon <http://www.oregoncore.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _BIH_H #define _BIH_H #include <G3D/Vector3.h> #include <G3D/Ray.h> #include <G3D/AABox.h> #include <Platform/Define.h> #include <stdexcept> #include <vector> #include <algorithm> #include <limits> #include <cmath> #define MAX_STACK_SIZE 64 #ifdef _MSC_VER #define isnan(x) _isnan(x) #else #define isnan(x) std::isnan(x) #endif using G3D::Vector3; using G3D::AABox; using G3D::Ray; static inline uint32 floatToRawIntBits(float f) { union { uint32 ival; float fval; } temp; temp.fval=f; return temp.ival; } static inline float intBitsToFloat(uint32 i) { union { uint32 ival; float fval; } temp; temp.ival=i; return temp.fval; } struct AABound { Vector3 lo, hi; }; /* Bounding Interval Hierarchy Class. Building and Ray-Intersection functions based on BIH from Sunflow, a Java Raytracer, released under MIT/X11 License http://sunflow.sourceforge.net/ Copyright (c) 2003-2007 Christopher Kulla */ class BIH { public: BIH() {}; template< class T, class BoundsFunc > void build(const std::vector<T> &primitives, BoundsFunc &getBounds, uint32 leafSize = 3, bool printStats=false) { if (primitives.size() == 0) return; buildData dat; dat.maxPrims = leafSize; dat.numPrims = primitives.size(); dat.indices = new uint32[dat.numPrims]; dat.primBound = new AABox[dat.numPrims]; getBounds(primitives[0], bounds); for (uint32 i=0; i<dat.numPrims; ++i) { dat.indices[i] = i; AABox tb; getBounds(primitives[i], dat.primBound[i]); bounds.merge(dat.primBound[i]); } std::vector<uint32> tempTree; BuildStats stats; buildHierarchy(tempTree, dat, stats); if (printStats) stats.printStats(); objects.resize(dat.numPrims); for (uint32 i=0; i<dat.numPrims; ++i) objects[i] = dat.indices[i]; //nObjects = dat.numPrims; tree = tempTree; delete[] dat.primBound; delete[] dat.indices; } uint32 primCount() { return objects.size(); } template<typename RayCallback> void intersectRay(const Ray &r, RayCallback& intersectCallback, float &maxDist, bool stopAtFirst=false) const { float intervalMin = -1.f; float intervalMax = -1.f; Vector3 org = r.origin(); Vector3 dir = r.direction(); Vector3 invDir; for (int i=0; i<3; ++i) { invDir[i] = 1.f / dir[i]; if (G3D::fuzzyNe(dir[i], 0.0f)) { float t1 = (bounds.low()[i] - org[i]) * invDir[i]; float t2 = (bounds.high()[i] - org[i]) * invDir[i]; if (t1 > t2) std::swap(t1, t2); if (t1 > intervalMin) intervalMin = t1; if (t2 < intervalMax || intervalMax < 0.f) intervalMax = t2; // intervalMax can only become smaller for other axis, // and intervalMin only larger respectively, so stop early if (intervalMax <= 0 || intervalMin >= maxDist) return; } } if (intervalMin > intervalMax) return; intervalMin = std::max(intervalMin, 0.f); intervalMax = std::min(intervalMax, maxDist); uint32 offsetFront[3]; uint32 offsetBack[3]; uint32 offsetFront3[3]; uint32 offsetBack3[3]; // compute custom offsets from direction sign bit for (int i=0; i<3; ++i) { offsetFront[i] = floatToRawIntBits(dir[i]) >> 31; offsetBack[i] = offsetFront[i] ^ 1; offsetFront3[i] = offsetFront[i] * 3; offsetBack3[i] = offsetBack[i] * 3; // avoid always adding 1 during the inner loop ++offsetFront[i]; ++offsetBack[i]; } StackNode stack[MAX_STACK_SIZE]; int stackPos = 0; int node = 0; while (true) { while (true) { uint32 tn = tree[node]; uint32 axis = (tn & (3 << 30)) >> 30; bool BVH2 = tn & (1 << 29); int offset = tn & ~(7 << 29); if (!BVH2) { if (axis < 3) { // "normal" interior node float tf = (intBitsToFloat(tree[node + offsetFront[axis]]) - org[axis]) * invDir[axis]; float tb = (intBitsToFloat(tree[node + offsetBack[axis]]) - org[axis]) * invDir[axis]; // ray passes between clip zones if (tf < intervalMin && tb > intervalMax) break; int back = offset + offsetBack3[axis]; node = back; // ray passes through far node only if (tf < intervalMin) { intervalMin = (tb >= intervalMin) ? tb : intervalMin; continue; } node = offset + offsetFront3[axis]; // front // ray passes through near node only if (tb > intervalMax) { intervalMax = (tf <= intervalMax) ? tf : intervalMax; continue; } // ray passes through both nodes // push back node stack[stackPos].node = back; stack[stackPos].tnear = (tb >= intervalMin) ? tb : intervalMin; stack[stackPos].tfar = intervalMax; stackPos++; // update ray interval for front node intervalMax = (tf <= intervalMax) ? tf : intervalMax; continue; } else { // leaf - test some objects int n = tree[node + 1]; while (n > 0) { bool hit = intersectCallback(r, objects[offset], maxDist, stopAtFirst); if (stopAtFirst && hit) return; --n; ++offset; } break; } } else { if (axis>2) return; // should not happen float tf = (intBitsToFloat(tree[node + offsetFront[axis]]) - org[axis]) * invDir[axis]; float tb = (intBitsToFloat(tree[node + offsetBack[axis]]) - org[axis]) * invDir[axis]; node = offset; intervalMin = (tf >= intervalMin) ? tf : intervalMin; intervalMax = (tb <= intervalMax) ? tb : intervalMax; if (intervalMin > intervalMax) break; continue; } } // traversal loop do { // stack is empty? if (stackPos == 0) return; // move back up the stack stackPos--; intervalMin = stack[stackPos].tnear; if (maxDist < intervalMin) continue; node = stack[stackPos].node; intervalMax = stack[stackPos].tfar; break; } while (true); } } template<typename IsectCallback> void intersectPoint(const Vector3 &p, IsectCallback& intersectCallback) const { if (!bounds.contains(p)) return; StackNode stack[MAX_STACK_SIZE]; int stackPos = 0; int node = 0; while (true) { while (true) { uint32 tn = tree[node]; uint32 axis = (tn & (3 << 30)) >> 30; bool BVH2 = tn & (1 << 29); int offset = tn & ~(7 << 29); if (!BVH2) { if (axis < 3) { // "normal" interior node float tl = intBitsToFloat(tree[node + 1]); float tr = intBitsToFloat(tree[node + 2]); // point is between clip zones if (tl < p[axis] && tr > p[axis]) break; int right = offset + 3; node = right; // point is in right node only if (tl < p[axis]) { continue; } node = offset; // left // point is in left node only if (tr > p[axis]) { continue; } // point is in both nodes // push back right node stack[stackPos].node = right; stackPos++; continue; } else { // leaf - test some objects int n = tree[node + 1]; while (n > 0) { intersectCallback(p, objects[offset]); // !!! --n; ++offset; } break; } } else // BVH2 node (empty space cut off left and right) { if (axis>2) return; // should not happen float tl = intBitsToFloat(tree[node + 1]); float tr = intBitsToFloat(tree[node + 2]); node = offset; if (tl > p[axis] || tr < p[axis]) break; continue; } } // traversal loop // stack is empty? if (stackPos == 0) return; // move back up the stack stackPos--; node = stack[stackPos].node; } } bool writeToFile(FILE *wf) const; bool readFromFile(FILE *rf); protected: std::vector<uint32> tree; std::vector<uint32> objects; AABox bounds; struct buildData { uint32 *indices; AABox *primBound; uint32 numPrims; int maxPrims; }; struct StackNode { uint32 node; float tnear; float tfar; }; class BuildStats { private: int numNodes; int numLeaves; int sumObjects; int minObjects; int maxObjects; int sumDepth; int minDepth; int maxDepth; int numLeavesN[6]; int numBVH2; public: BuildStats(): numNodes(0), numLeaves(0), sumObjects(0), minObjects(0x0FFFFFFF), maxObjects(0xFFFFFFFF), sumDepth(0), minDepth(0x0FFFFFFF), maxDepth(0xFFFFFFFF), numBVH2(0) { for (int i=0; i<6; ++i) numLeavesN[i] = 0; } void updateInner() { numNodes++; } void updateBVH2() { numBVH2++; } void updateLeaf(int depth, int n); void printStats(); }; void buildHierarchy(std::vector<uint32> &tempTree, buildData &dat, BuildStats &stats); void createNode(std::vector<uint32> &tempTree, int nodeIndex, uint32 left, uint32 right) { // write leaf node tempTree[nodeIndex + 0] = (3 << 30) | left; tempTree[nodeIndex + 1] = right - left + 1; } void subdivide(int left, int right, std::vector<uint32> &tempTree, buildData &dat, AABound &gridBox, AABound &nodeBox, int nodeIndex, int depth, BuildStats &stats); }; #endif // _BIH_H
[ "Réda@Réda-PC" ]
Réda@Réda-PC
3578dbc3aad15ff3fa04faa6537bd3cc483ed72f
312ac2db68db9bae2ea5db87ca05329a77564216
/998/B [Cutting].cpp
6a689cd10deaf51a2052395b88e6799b8396e515
[]
no_license
Nikhil-Medam/Codeforces-Solutions
3107023a4bbfc6bcf82ab05ed840a6d621567876
71f6304d7b9d87aac05f5b5c27a9f277ffdad4cd
refs/heads/master
2020-06-17T07:30:24.618634
2019-07-08T16:13:35
2019-07-08T16:13:35
195,846,206
1
0
null
null
null
null
UTF-8
C++
false
false
1,829
cpp
#include<bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define ll long long #define int long long #define double long double #define pb push_back #define max(a,b) (a>b?a:b) #define min(a,b) (a<b?a:b) #define diff(a,b) (a>b?a-b:b-a) const int N=1e5+5; void pairsort(int a[], int b[], int n){ pair<int, int> pairt[n]; for (int i = 0; i < n; i++) { pairt[i].first = a[i]; pairt[i].second = b[i]; } sort(pairt, pairt + n); for (int i = 0; i < n; i++) { a[i] = pairt[i].first; b[i] = pairt[i].second; } } int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b); } int isPrime(int n){ if(n < 2) return 0; if(n < 4) return 1; if(n % 2 == 0 or n % 3 == 0) return 0; for(int i = 5; i*i <= n; i += 6) if(n % i == 0 or n % (i+2) == 0) return 0; return 1; } long long C(int n, int r) { if(r>n-r) r=n-r; long long ans=1; for(int i=1;i<=r;i++){ ans*=n-r+i; ans/=i; } return ans; } int mod = 1e9+7; int modexpo(int x,int p){ int res = 1; x = x%mod; while(p){ if(p%2) res = res * x; p >>= 1; x = x*x % mod; res %= mod; } return res; } int n,m,a[101],cnt,ans; vector<int> v1,v2,v; int32_t main() { IOS; cin>>n>>m; for(int i=1;i<=n;i++) cin>>a[i]; for(int i=1;i<=n;i++) { if(a[i]%2) cnt++; if(cnt==i/2&&i%2==0&&i!=n) v1.push_back(a[i]),v2.push_back(a[i+1]); } for(int i=0;i<v1.size();i++) v.push_back(diff(v1[i],v2[i])); sort(v.begin(),v.end()); for(int i=0;i<v.size();i++) if(v[i]<=m) m-=v[i],ans++; cout<<ans; return 0; }
[ "medam.nikhil@gmail.com" ]
medam.nikhil@gmail.com
3558b59fdd40ef08d8c7906694302913138d0440
f1cb5a32bcc0c8eead9992b2bf4aaeb504a9d05f
/Projecto Robot/src/myTable.cpp
0f670623c7fb4e5ec156ce96c549fb1104a1eb18
[]
no_license
MacedoRAC/CGRA
99babb53ae53a47fbc2686cc13b53c147ca00c51
4aa483ec521ef8e15d560d71fa4b232d044028f3
refs/heads/master
2021-03-12T19:25:23.467368
2014-05-25T23:15:37
2014-05-25T23:15:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,439
cpp
#include "myTable.h" myTable:: myTable(){ // Coefficients for material C float ambC[3] = {0.2, 0.2, 0.2}; float difC[3] = {1,0.5,0.25}; float specC[3] = {0.1, 0.05, 0.025}; float shininessC = 120.f; materialC = new CGFappearance(ambC,difC,specC,shininessC); // Coefficients for material D float ambD[3] = {0.2, 0.2, 0.2}; float difD[3] = {0.5,0.5,0.5}; float specD[3] = {0.5, 0.5, 0.5}; float shininessD = 120.f; materialD = new CGFappearance(ambD,difD,specD,shininessD); // Texture table float ambT[3] = {0.2, 0.2, 0.2}; float difT[3] = {0.8,0.8,0.8}; float specT[3] = {0.1, 0.1, 0.1}; float shininessT = 80.f; tableAppearance = new CGFappearance(ambT,difT,specT,shininessT); tableAppearance->setTexture("table.png"); } void myTable:: draw(){ //desenhar pernas glPushMatrix(); materialD->apply(); glTranslatef(-2.35,1.75,-1.35); glScalef(0.3,3.5,0.3); cube.draw(); glPopMatrix(); glPushMatrix(); materialD->apply(); glTranslatef(2.35,1.75,-1.35); glScalef(0.3,3.5,0.3); cube.draw(); glPopMatrix(); glPushMatrix(); materialD->apply(); glTranslatef(-2.35,1.75,1.35); glScalef(0.3,3.5,0.3); cube.draw(); glPopMatrix(); glPushMatrix(); materialD->apply(); glTranslatef(2.35,1.75,1.35); glScalef(0.3,3.5,0.3); cube.draw(); glPopMatrix(); //desenhar tampo (parte de cima da mesa) glPushMatrix(); tableAppearance->apply(); glTranslatef(0,3.65,0); glScalef(5,0.3,3); cube.draw(); glPopMatrix(); }
[ "andr.macedo1@gmail.com" ]
andr.macedo1@gmail.com
274f1eebd307b2b996deb88067d27a1527fa98ed
7f308530daea594dd10425b68de237baecdbc4f9
/Practica 3 El juego de la vida generalizado original/include/celula2.hpp
f76fb6d5a257fde2239891d376ab194cd1bf6c23
[]
no_license
AdrianEpi/Algoritmos-y-Estructuras-de-Datos-Avanzadas
8843c1262d02c49d8d72daee1709c05db7541718
97bb06a3916569ffaa281ff06b47addc863261a3
refs/heads/master
2022-07-14T21:33:41.693439
2020-05-21T06:30:19
2020-05-21T06:30:19
241,056,042
0
0
null
null
null
null
UTF-8
C++
false
false
1,940
hpp
/*=================================================================================== ===================================================================================== = = = Proyecto: Práctica 3 El juego de la vida generalizado = = Archivo: celula2.hpp = = Autor: Adrián Epifanio Rodríguez Hernández = = Fecha: 16/03/2020 = = Asignatura: Algoritmos y Estructuras de Datos Avazados = = Lenguaje: C++ = = Correo: alu0101158280@ull.edu.es = = Lugar: Universidad De La Laguna = = Escuela Superior de Ingeniería y Tecnología = = = ===================================================================================== ===================================================================================*/ /*---------- DECLARACION DE LIBRERIAS ----------*/ #include <iostream> /*------------------------------------------------*/ /*---------- DECLARACION DE FUNCIONES ----------*/ #pragma once #include "celula.hpp" /*------------------------------------------------*/ class Tablero; class Celula2 : public Celula { public: // Builders & Destroyer Celula2 (); Celula2 (int i, int j); ~Celula2 (); // Getters & Setters int getEstado (void) const; // Functions int contarVecinas (const Tablero& board); int actualizarEstado (void); // Read & Write std::ostream& mostrar (std::ostream& os) const; };
[ "alu0101158280@ull.edu.es" ]
alu0101158280@ull.edu.es
5c9337d6d52e409f6e6e1efcf059b03129a41df3
5c7269112efdad00573442e4f1eb58299b8cb6c6
/Linked List/Deletion.cpp
a7df8581a35e9a212adb685861d100ebd75a151e
[]
no_license
savi-1311/Data-Structures
e3315dad66163d66aa9aaa8b0813248887955153
a62c7af7d81724674e7e91a91f0b0fb3324901be
refs/heads/master
2021-04-17T05:21:29.777451
2020-10-02T10:53:20
2020-10-02T10:53:20
249,415,311
0
2
null
2020-10-02T10:53:21
2020-03-23T11:43:16
C++
UTF-8
C++
false
false
1,408
cpp
#include <bits/stdc++.h> using namespace std; class Node { public: int data; Node* next; }; void deletepos(Node** head_ref) { Node* temp = new Node(); Node* n= *head_ref; int pos,i; cout << "\nEnter the position you wish to delete-\n"; cin >> pos; for(i=1;i<pos-1;i++) { n = n->next; } temp = n->next; n->next = temp->next; cout << "\n! Deleted Node at Specified Position !\n"; } void deletefront(Node** head_ref) { Node* temp = new Node(); temp = *head_ref; *head_ref = temp->next; cout << "\n! Deleted First Node !\n"; } void deletelast(Node** head_ref) { Node* n= *head_ref; while(n->next->next != NULL) { n = n->next; } n->next = NULL; cout << "\n! Deleted Last Node !\n"; } void printList (Node* n) { cout << "\nThe Linked List Values are-\n"; while(n!= NULL) { cout<< n->data << "\n"; n = n->next; } } int main() { int i,k; cout << "Enter The no. of Nodes\n"; cin >> k; Node* List[k] = {NULL}; //allocated statically for(i=0;i<k;i++) { List[i] = new Node(); } //allocated Dynamically for(i=0;i<k;i++) { cout << i+1 << ". Enter The data in the node - \n"; cin >> List[i]->data; if(i==k-1) List[i]->next=NULL; else List[i]->next = List[i+1]; } //entering the values Node* head = List[0]; printList(head); deletefront(&head); printList(head); deletelast(&head); printList(head); deletepos(&head); printList(head); return 0; }
[ "shambhavishandilya01@gmail.com" ]
shambhavishandilya01@gmail.com
e983fb88a172970cf30f96b8b3daa4aa8250d25c
581f08ca593912aa31cb5c1ea4c19cca763be432
/src/engine/KE/Animation.cpp
0b56f4d47a424c0a7e29b419bbbe57f39f0ddd32
[]
no_license
KraterosProgramming/KraterosEngine
9e6c28c91684e6c16ef3da8d635250a8fd886565
409020fea4bc80e3d0788a1776a09eba8699d4e5
refs/heads/master
2021-01-01T05:49:16.426027
2014-06-11T01:09:49
2014-06-11T01:09:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
#include "Animation.h" namespace KE { Animation::Animation(int fps, const std::vector<size_t> &frameIDs) { this->fps = fps; this->frameIDs = frameIDs; } size_t Animation::getFrameAt(Uint32 time, bool loop, bool backwards) const { size_t frame = time * fps / 1000; if (loop) { frame %= frameIDs.size(); } else if (frame >= frameIDs.size()) { frame = frameIDs.size() - 1; } if (backwards) { frame = frameIDs.size() - 1 - frame; } return frame; } }
[ "kraterosprogramming@gmail.com" ]
kraterosprogramming@gmail.com
7f9149607d4e2f728cf5734ca865e5d552e068e9
542d85ec13acea7617b06dc375b2611b145dba70
/Lab_09/main.cpp
04fc84142c2f2cd23a01cefdb6fdd88c00696380
[]
no_license
jaredml/CSE30
50262f87a9fef4d190223fefc161e46b351ef5a1
3e5dc9334b7dcf3111107e497d6ad44ae355d515
refs/heads/master
2020-05-22T09:24:49.544773
2017-03-15T17:44:56
2017-03-15T17:44:56
18,084,074
0
0
null
null
null
null
UTF-8
C++
false
false
1,611
cpp
#include <iostream> #include <string> #include <fstream> #include <sstream> #include <stdlib.h> #include <iomanip> #include "Time.h" using namespace std; int main() { bool valid1, valid2;//stores if the number is valid or not Time start_time, end_time;//stores start time and end time //string my_line1, my_line2; cout << "Enter the start time for the lecture (format is HH:MM:SS): "; valid1 = start_time.getTimeFromUser();//calls getTimeFromUser if (!valid1)//if the start time is invalid it prints out the start time entered is invalid { cout << "The start time entered is invalid!" << endl; return 0; } else { cout << "Enter the end time for the lecture (format is HH:MM:SS): "; valid2 = end_time.getTimeFromUser(); if (!valid2)//if the second number is invalid it prints out the end time is invalid { cout << "The end time entered is invalid!" << endl; return 0; } else//if everything is valid then it prints out start time and end time of lecture { cout<<"The lecture starts at "; start_time.print24Hour();//gets the start time and prints it out cout<<" and ends at "; end_time.print24Hour();//gets the end time and prints it out cout<<endl;// ends the line } } return 0; }
[ "jaredmlipp@gmail.com" ]
jaredmlipp@gmail.com
5b37337c1fb7205fec23d526485f0ac5e19d0293
1236c4e9a5e9444dd3157f33b9fde43f56fa2aae
/src/core/rgmResource.cpp
305219313a241a8969c6da1585b97f884179b393
[]
no_license
dustpg/RubyGM
c64650f162887df5683138086baf4a2a5bd5c657
802123c582baf7b6e1f17a9b9aea5a33101dda24
refs/heads/master
2021-01-21T04:41:08.977991
2016-06-18T19:51:38
2016-06-18T19:51:38
36,666,346
0
2
null
null
null
null
UTF-8
C++
false
false
9,697
cpp
#define _WIN32_WINNT 0x0A000001 #include <core/drawable/rgmBitmap.h> #include <core/asset/rgmAssetFont.h> #include <core/graphics/rgmGraphics.h> #include <core/text/rgmTextDetail.h> #include <core/util/rgmUtil.h> #include <game/rgmGame.h> #include <bridge/rgmluiBridge.h> #include <cwchar> #include <memory> /// <summary> /// Rasterizations the specified sf. /// </summary> /// <param name="sf">The scale factor.</param> /// <param name="bs">The basic size.</param> /// <returns></returns> auto RubyGM::Drawable::Object::Rasterization( SizeF sf, SizeF bs) noexcept -> Drawable::Bitmap* { auto asset = Game::CreateBitmapAssetFromDrawable(this, sf, bs); Drawable::BitmapStatus bst(std::move(asset)); // 创建成功 if (const auto bsp = Drawable::Bitmap::Create(bst)) { bsp->des_rect.right = bs.width; bsp->des_rect.bottom = bs.height; return bsp; } return nullptr; } /// <summary> /// Initializes a new instance of the <see cref="Resource"/> class. /// </summary> RubyGM::Base::Resource::Resource() noexcept { // 设置链表指针 auto last = Bridge::GetLastResourceObject(); assert(last); // 链接后面 this->next = last; // 链接前面 this->prve = last->prve; // 前面链接自己 this->prve->next = this; // 后面链接自己 this->next->prve = this; } /// <summary> /// Recreates this instance. /// </summary> /// <returns></returns> auto RubyGM::Base::Resource::Recreate() noexcept -> Result { // 可以重建 if (m_bCouldRecreate) { m_bCouldRecreate = false; return this->recreate(); } // 已经重建完毕 else { return Result(S_OK); } } /// <summary> /// Finalizes an instance of the <see cref="Resource"/> class. /// </summary> /// <returns></returns> RubyGM::Base::Resource::~Resource() noexcept { // 前面链接自己 this->prve->next = this->next; // 后面链接自己 this->next->prve = this->prve; } /// <summary> /// Adds the reference. /// </summary> /// <returns></returns> auto RubyGM::Base::Resource::AddRef() noexcept -> uint32_t { assert(m_cRef < 1024 && "high ref-count"); return ++m_cRef; } /// <summary> /// Releases this instance. /// </summary> /// <returns></returns> auto RubyGM::Base::Resource::Release() noexcept -> uint32_t { assert(m_cRef < 1024 && "high ref-count"); uint32_t count = --m_cRef; if (!count) this->dispose(); return count; } // drawable //#include <core/drawable/rgmDrawable.h> //#include <core/util/rgmImpl.h> #if 0 /// <summary> /// Initializes a new instance of the <see cref="Object"/> class. /// </summary> /// <param name="">The .</param> RubyGM::Drawable::Object::Object(const BaseStatus& bs) noexcept : m_color(bs.color), m_pBrush(Game::GetCommonBrush()) { } /// <summary> /// Finalizes an instance of the <see cref="Object"/> class. /// </summary> /// <returns></returns> RubyGM::Drawable::Object::~Object() noexcept { // 释放笔刷 RubyGM::SafeRelease(m_pBrush); } /// <summary> /// Sets the color. /// </summary> /// <param name="color">The color.</param> /// <returns></returns> void RubyGM::Drawable::Object::SetColor(const RubyGM::ColorF& color) noexcept { // 非纯色笔刷则释放旧的笔刷 if (this->get_brush_mode() != BrushMode::Mode_Color) { RubyGM::SafeRelease(m_pBrush); m_pBrush = Game::GetCommonBrush(); this->set_brush_mode(BrushMode::Mode_Color); } // 修改颜色 m_color = color; } /// <summary> /// Sets the brush. /// </summary> /// <param name="brush">The brush.</param> /// <returns></returns> void RubyGM::Drawable::Object::SetBrush(IGMBrush* brush) noexcept { assert(brush && "bad brush"); RubyGM::SafeRelease(m_pBrush); m_pBrush = RubyGM::SafeAcquire(brush); this->set_brush_mode(BrushMode::Mode_Other); } /// <summary> /// Before_renders this instance. /// </summary> /// <returns></returns> void RubyGM::Drawable::Object::before_render() const noexcept { // 纯色笔刷 if (this->get_brush_mode() == BrushMode::Mode_Color) { auto brush = impl::d2d<ID2D1SolidColorBrush>(m_pBrush, IID_ID2D1SolidColorBrush); brush->SetColor(impl::d2d(m_color)); } } /// <summary> /// Recreates this instance. /// </summary> /// <returns></returns> auto RubyGM::Drawable::Object::recreate() noexcept -> Result { // 重建笔刷资源 RubyGM::SafeRelease(m_pBrush); m_pBrush = Game::GetCommonBrush(); return Result(S_OK); } #endif // rubygm::asset namespace namespace RubyGM { namespace Asset { /// <summary> /// Create a <see cref="Font"/> object with the specified prop . never /// </summary> /// <param name="">The .</param> /// <returns></returns> auto Font::Create(const FontProperties& prop) noexcept -> Font& { size_t lenp1 = std::wcslen(prop.name) + 1; auto ptr = RubyGM::SmallAlloc(sizeof(Font) + lenp1 * sizeof(wchar_t)); assert(ptr && "RubyGM::SmallAlloc cannot return nullptr"); auto obj = new(ptr) Asset::Font(prop, lenp1); return *obj; } /// <summary> /// Initializes a new instance of the <see cref="Font"/> class. /// </summary> /// <param name="prop">The property.</param> Font::Font(const FontProperties& prop, size_t name_len) noexcept { std::memcpy(m_bufFontProp, &prop, sizeof(prop)); std::memcpy(m_bufFontName, prop.name, name_len * sizeof(prop.name[0])); } /// <summary> /// Finalizes an instance of the <see cref="Font"/> class. /// </summary> /// <returns></returns> Font::~Font() noexcept { RubyGM::SafeRelease(m_pTextFormat); } /// <summary> /// Recreates this instance. /// </summary> /// <returns></returns> /*auto Font::recreate() noexcept -> Result { // 文本格式是CPU资源, 没有有必要重建 return Result(S_OK); }*/ /// <summary> /// Lows the occupancy. /// </summary> /// <returns></returns> void Font::LowOccupancy() noexcept { // 在没有被其他对象引用时候释放 this->LowOccupancyHelper(m_pTextFormat); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <returns></returns> void Font::dispose() noexcept { // 调用析构函数 this->Font::~Font(); // 释放数据 RubyGM::SmallFree(this); } /// <summary> /// Gets the font. /// </summary> /// <returns></returns> auto Font::GetFont() noexcept ->IGMFont* { // 没有则创建 if (!m_pTextFormat) { // 创建 auto hr = Bridge::CreateFontWithProp(this->prop(), &m_pTextFormat); // 检查错误 if (FAILED(hr)) Game::SetLastErrorCode(hr); } // 拥有直接返回 return RubyGM::SafeAcquire(m_pTextFormat); } }} // stroke #include <core/asset/rgmAssetStroke.h> // rubygm::asset namespace namespace RubyGM { namespace Asset { /// <summary> /// Creates the specified . /// </summary> /// <param name="">The .</param> /// <returns></returns> auto Stroke::Create(const StrokeStyle& ss) noexcept -> Stroke& { const size_t extra = ss.dash_count * sizeof(float); auto ptr = RubyGM::SmallAlloc(sizeof(Stroke) + extra); assert(ptr && "RubyGM::SmallAlloc cannot return nullptr"); auto obj = new(ptr) Asset::Stroke(ss); return *obj; } /// <summary> /// Initializes a new instance of the <see cref="Stroke"/> class. /// </summary> /// <param name="ss">The ss.</param> Stroke::Stroke(const StrokeStyle& ss) noexcept : m_style(ss) { std::memcpy(m_dashes, ss.dashes, ss.dash_count * sizeof(float)); } /// <summary> /// Finalizes an instance of the <see cref=""/> class. /// </summary> /// <returns></returns> Stroke::~Stroke() noexcept { RubyGM::SafeRelease(m_pStrokeStyle); } /// <summary> /// Lows the occupancy. /// </summary> /// <returns></returns> void Stroke::dispose() noexcept { this->Stroke::~Stroke(); RubyGM::SmallFree(this); } /// <summary> /// Lows the occupancy. /// </summary> /// <returns></returns> void Stroke::LowOccupancy() noexcept { this->LowOccupancyHelper(m_pStrokeStyle); } /// <summary> /// Gets the stroke. /// </summary> /// <returns></returns> auto Stroke::GetStroke() noexcept -> IGMStrokeStyle* { // 没有则创建 if (!m_pStrokeStyle) { StrokeStyle ss; static_cast<BaseStrokeStyle&>(ss) = m_style; ss.dashes = m_dashes; // 创建 auto hr = Bridge::CreateStrokeWithProp(ss, &m_pStrokeStyle); // 检查错误 if (FAILED(hr)) Game::SetLastErrorCode(hr); } // 拥有直接返回 return RubyGM::SafeAcquire(m_pStrokeStyle); } }} /// <summary> /// Creates the font asset. /// </summary> /// <param name="">The .</param> /// <returns></returns> auto RubyGM::Game::CreateFontAsset( const FontProperties& fp) noexcept -> RefPtr<Asset::Font> { auto&font = Asset::Font::Create(fp); auto* ptr = &font; return RefPtr<Asset::Font>(std::move(ptr)); } /// <summary> /// Creates the stroke asset. /// </summary> /// <param name="">The .</param> /// <returns></returns> auto RubyGM::Game::CreateStrokeAsset( const StrokeStyle& ss) noexcept -> RefPtr<Asset::Stroke> { auto&stroke = Asset::Stroke::Create(ss); auto* ptr = &stroke; return RefPtr<Asset::Stroke>(std::move(ptr)); }
[ "dustpg@gmail.com" ]
dustpg@gmail.com
72bba7845a2c8cdce6d48ee2e7fe8ca1c0d79dfe
2aa77d972bd61e1077ed48ae8502cb4c4abda33f
/RavenEngine/src/Platform/Renderer/OpenglContext.cpp
d4000b58f3a3c2b17dc8ff18e9d14c3116e152f6
[]
no_license
ArnaudDroxler/Raven-Engine
946403d70812f211e1178868dc99e9493f29ce7f
3859b4118cd44bde567bb0697e94ff628fe87a79
refs/heads/master
2020-05-31T02:28:02.593169
2019-12-26T13:24:00
2019-12-26T13:24:00
190,066,040
0
0
null
null
null
null
UTF-8
C++
false
false
457
cpp
#include "ravenpch.h" #include "OpenglContext.h" #include "GLFW/glfw3.h" #include "glad/glad.h" namespace Raven { OpenglContext::OpenglContext(GLFWwindow* window) : window(window) { } void OpenglContext::Init() { glfwMakeContextCurrent(window); int status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); RAVEN_CORE_ASSERT(status, "Could not intialize GLAD!"); } void OpenglContext::SwapBuffer() { glfwSwapBuffers(window); } }
[ "arnaud.droxler@gmail.com" ]
arnaud.droxler@gmail.com
3e5f8ea60854998d1f557282d386c5e800f99b2f
e0dacfdf4fae084bcf66f01251d229edf1851031
/src/pharmacy_counting.cpp
a4cdac44ff7c768e8ac6f851d9265a12f563a4a6
[]
no_license
zsun86/Insight-Coding-Challenge
835a5f031b7e252ebb6b276a468220c31a904c1f
5c95fef4376ec36d62beda397436f22712879332
refs/heads/master
2020-03-23T02:10:21.508966
2018-07-14T20:31:56
2018-07-14T20:31:56
140,960,254
0
1
null
null
null
null
UTF-8
C++
false
false
4,126
cpp
#include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <cmath> using namespace std; #include "patient_data.h" #include "drug_data.h" /* Extract Field, Checks if in quotes. */ void peekGetField(stringstream &ss, string &field) { if (!(ss.peek() == '"')) { getline(ss, field, ','); } else { ss.get(); getline(ss, field, '"'); field = '"' + field + '"'; // Add quotes back to field for output purposes later ss.get(); } } /* Parse a given line into individual field components, concatenates and hashes the prescriber name */ void parseLine(string line, PatientEntry &patient) { string field, lname, fname; stringstream ss(line); //patient.id = stoi(field); ss >> patient.id; peekGetField(ss, field); // To advance the sstream extraction point. peekGetField(ss, field); lname = field; peekGetField(ss, field); fname = field; patient.pname_hash = DJBHash(lname+fname); peekGetField(ss, field); patient.dname = field; //patient.dcost = stod(field); ss >> patient.dcost; peekGetField(ss, field); // To advance the sstream extraction point. } /* Reads in input file */ void parse_ifile(ifstream &ifs, patient_data &if_data) { PatientEntry p_ent; string line; getline(ifs, line); // Assume first line is header names while (getline(ifs, line)) { // Read in one line parseLine(line, p_ent); // Parses line into individual field if (p_ent.id > 0) if_data.addEntry(p_ent.id, p_ent.pname_hash, p_ent.dname, p_ent.dcost); } cout << "Found " << if_data.getNumEntries() << " entries." << endl; } /* Processes each line of read in input lines and stores the accumulated drug info while maintaining an unsorted list of drug names */ void process_data(patient_data &if_data, drug_data &of_data) { int num_patient_entries = if_data.getNumEntries(); int i; PatientEntry ent; //cout << "Processing " << num_patient_entries << " entries" << endl; for (i = 0; i < num_patient_entries; i++) { if (i % 1000000 == 0) { cout << "Processing entries " << i+1 << " through " << min(i+1000000, num_patient_entries) << " of " << num_patient_entries << " total entries\r"; cout.flush(); } ent = if_data.getEntry(i); of_data.update_with_patient_entry(ent.dname, ent.pname_hash, ent.dcost); } cout << "\nFinished processing input data" << endl; } /* Writing output file as per instructed format */ void write_ofile(ofstream &ofs, drug_data &of_data) { DrugEntry ent; int num_drugs = of_data.getNumDrugs(); int i; int precision_val; ofs << "drug_name,num_prescriber,total_cost"; for (i = 0; i < num_drugs; i++) { ent = of_data.getEntry(i); precision_val = ceil(log10(ent.tot_cost)) + 2; // Determine magnitude of cost to set output precision to include cent precision ofs << "\n" << ent.dname << "," << ent.prescribers.size() << "," << setprecision(precision_val) << ent.tot_cost; } } /* main function */ int main(int argc, char **argv) { char* fname; char* ofname; ifstream ifs; ofstream ofs; patient_data if_data; drug_data of_data; if (argc < 3) { cout << "Invalid parameters" << endl; cout << "To use this program please use the following syntax:" << endl; cout << argv[0] << " input_file output_file" << endl; return 0; } else { fname = argv[1]; ofname = argv[2]; } ifs.open(fname); if (!ifs.fail()) { cout << "Opening File: " << fname << endl; } else { cout << "File " << fname << " Failed to Open" << endl; return 0; } parse_ifile(ifs, if_data); // Reads and parses input file fname into a patient_data class ifs.close(); process_data(if_data, of_data); // Processes imported data as per Coding Challenge instructions cout << of_data.getNumDrugs() << " types of drugs prescribed" << endl; of_data.sort_drug_list(); // Sorts drug list by descending order of total cost ofs.open(ofname, ofstream::out); if (!ofs.fail()) { cout << "Writing to File: " << ofname << endl; } else { cout << "File " << ofname << " Failed to Open" << endl; return 0; } write_ofile(ofs, of_data); // Writes to output file ofs.close(); cout << "Terminating Program" << endl; return 0; }
[ "41155322+zsun86@users.noreply.github.com" ]
41155322+zsun86@users.noreply.github.com
ee5de28428796b2c304f2b573ffe3ef953f80e39
42334cb2a3d7e6102e2c86fdff7d496cf091e660
/NvEncode/NvEncoder.h
9a0edca876604d7210c2c9d338d24dc362521f83
[]
no_license
wwllww/LiveStream_MultiIntance
04b0ca3e16d4ee0f627b8bc3ecfd935cc97bf24f
447f52bdd08d3fa3ba6b6e58323740632320b131
refs/heads/master
2021-05-12T17:19:53.534922
2018-02-09T08:13:47
2018-02-09T08:13:47
117,042,806
2
3
null
null
null
null
UTF-8
C++
false
false
4,894
h
#if defined(NV_WINDOWS) #include <d3d9.h> #include <d3d10_1.h> #include <d3d11.h> #pragma warning(disable : 4996) #endif #include "inc/NvHWEncoder.h" #define MAX_ENCODE_QUEUE 32 #define FRAME_QUEUE 240 #define NUM_OF_MVHINTS_PER_BLOCK8x8 4 #define NUM_OF_MVHINTS_PER_BLOCK8x16 2 #define NUM_OF_MVHINTS_PER_BLOCK16x8 2 #define NUM_OF_MVHINTS_PER_BLOCK16x16 1 enum { PARTITION_TYPE_16x16, PARTITION_TYPE_8x8, PARTITION_TYPE_16x8, PARTITION_TYPE_8x16 }; #define SET_VER(configStruct, type) {configStruct.version = type##_VER;} template<class T> class CNvQueue { T** m_pBuffer; unsigned int m_uSize; unsigned int m_uPendingCount; unsigned int m_uAvailableIdx; unsigned int m_uPendingndex; public: CNvQueue(): m_pBuffer(NULL), m_uSize(0), m_uPendingCount(0), m_uAvailableIdx(0), m_uPendingndex(0) { } ~CNvQueue() { delete[] m_pBuffer; } bool Initialize(T *pItems, unsigned int uSize) { m_uSize = uSize; m_uPendingCount = 0; m_uAvailableIdx = 0; m_uPendingndex = 0; m_pBuffer = new T *[m_uSize]; for (unsigned int i = 0; i < m_uSize; i++) { m_pBuffer[i] = &pItems[i]; } return true; } T * GetAvailable() { T *pItem = NULL; if (m_uPendingCount == m_uSize) { return NULL; } pItem = m_pBuffer[m_uAvailableIdx]; m_uAvailableIdx = (m_uAvailableIdx+1)%m_uSize; m_uPendingCount += 1; return pItem; } T* GetPending() { if (m_uPendingCount == 0) { return NULL; } T *pItem = m_pBuffer[m_uPendingndex]; m_uPendingndex = (m_uPendingndex+1)%m_uSize; m_uPendingCount -= 1; return pItem; } unsigned int GetPendingCount() { return m_uPendingCount; } }; typedef struct _EncodeFrameConfig { uint8_t *yuv[3]; uint32_t stride[3]; uint32_t width; uint32_t height; int8_t *qpDeltaMapArray; uint32_t qpDeltaMapArraySize; NVENC_EXTERNAL_ME_HINT *meExternalHints; NVENC_EXTERNAL_ME_HINT_COUNTS_PER_BLOCKTYPE meHintCountsPerBlock[1]; }EncodeFrameConfig; typedef enum { NV_ENC_DX9 = 0, NV_ENC_DX11 = 1, NV_ENC_CUDA = 2, NV_ENC_DX10 = 3, } NvEncodeDeviceType; class CNvEncoder { public: CNvEncoder(); virtual ~CNvEncoder(); protected: CNvHWEncoder *m_pNvHWEncoder; uint32_t m_uEncodeBufferCount; uint32_t m_uPicStruct; void* m_pDevice; #if defined(NV_WINDOWS) IDirect3D9 *m_pD3D; #endif CUcontext m_cuContext; EncodeBuffer m_stEncodeBuffer[MAX_ENCODE_QUEUE]; MotionEstimationBuffer m_stMVBuffer[MAX_ENCODE_QUEUE]; CNvQueue<EncodeBuffer> m_EncodeBufferQueue; CNvQueue<MotionEstimationBuffer> m_MVBufferQueue; EncodeOutputBuffer m_stEOSOutputBfr; protected: NVENCSTATUS InitD3D9(uint32_t deviceID = 0); NVENCSTATUS InitD3D11(uint32_t deviceID = 0); NVENCSTATUS InitD3D10(uint32_t deviceID = 0); NVENCSTATUS InitCuda(uint32_t deviceID = 0); NVENCSTATUS AllocateIOBuffers(uint32_t uInputWidth, uint32_t uInputHeight, NV_ENC_BUFFER_FORMAT inputFormat); NVENCSTATUS AllocateMVIOBuffers(uint32_t uInputWidth, uint32_t uInputHeight, NV_ENC_BUFFER_FORMAT inputFormat); NVENCSTATUS ReleaseIOBuffers(); NVENCSTATUS ReleaseMVIOBuffers(); unsigned char* LockInputBuffer(void * hInputSurface, uint32_t *pLockedPitch); NVENCSTATUS FlushEncoder(VCodecBuffer** pOut); void FlushMVOutputBuffer(); /////////// public: EncodeConfig m_stEncoderConfig; VCodecBuffer* m_pTempBuffer; volatile bool m_bFlushComplete; NVENCSTATUS LoadCodecLib(); void UnLoadCodecLib(); void* NvEncodeCreate(EncodeConfig* pEncodeConfig); int NvEncodeDestroy(); int NvEncodeFrame(VCodecBuffer* pIn, VCodecBuffer** pOut); unsigned int NvGetBufferedCount(); }; // NVEncodeAPI entry point typedef NVENCSTATUS (NVENCAPI *MYPROC)(NV_ENCODE_API_FUNCTION_LIST*);
[ "393520798@qq.com" ]
393520798@qq.com
374c403536a8fdffb667cdd5e3f79c96bda69999
b73eec3a26bdcffb6a19dec6b8b048079befe04c
/3rdparty/meshlab-master/src/plugins_experimental/edit_ocme/src/utils/logging.h
f40b5d3ad8025d4f0802726f9c97dd3b68435732
[ "GPL-1.0-or-later", "GPL-3.0-only", "MIT" ]
permissive
HoEmpire/slambook2
c876494174e7f636bdf5b5743fab7d9918c52898
96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4
refs/heads/master
2020-07-24T02:35:39.488466
2019-11-25T03:08:17
2019-11-25T03:08:17
207,775,582
0
0
MIT
2019-09-11T09:35:56
2019-09-11T09:35:56
null
UTF-8
C++
false
false
1,262
h
#ifndef _LOGGING_ #define _LOGGING_ #include <string> #include <vector> #include <stdio.h> #include <assert.h> struct Logging{ public: bool off; Logging(const char * filename):off(false){ Buf() = new char[65536];Buf()[0]= '\0'; if(off) return; LF() = false; if((filename!=NULL)){ LF() = true; F() = fopen(filename,"a+"); fclose(F()); FN() = std::string(filename); } } ~Logging(){ if( Buf()) {delete [] Buf(); Buf()=0;} if(off) return; J().clear(); } void Append(const char * msg,bool onscreen = true){ if(off) return; J().push_back(std::string(msg)); if(LF()) Flush(std::string(msg)); if(onscreen) printf("%s\n",msg); } char *& Buf(){static char * buf; return buf;} std::string & FN(){ return logfilename;} void Push(bool onscreen= false){ if(off) return; Append(Buf());if(onscreen) printf("%s",Buf());} bool & LF() { return logf;} private: FILE * logfile; std::string logfilename; std::vector<std::string> journal; bool logf; FILE *& F(){ return logfile;} std::vector<std::string> & J(){ return journal;} void Flush(std::string line){ if(off) return; F() = fopen(FN().c_str(),"a+"); assert(F()); fprintf(F(),"%s\n",line.c_str()); fclose(F()); } }; #endif
[ "541218251@qq.com" ]
541218251@qq.com
efeffeecd3998153c77e2a4722f8f45baed48481
112f0138a14020681cae129b0414e41bf31b437a
/SSENTITYMANAGER/WeaponEntity.h
f923e95d6a3ab835792e721b4eccc4711dfbe676
[]
no_license
jeag2002/SpaceShooter2D-3-Test
e395b5a60debba8b3a8da7f620766336705f53cf
ca2e25cc8c9e5fe095b9100c8882808d2e2b2c6c
refs/heads/master
2020-12-28T20:42:35.947548
2016-12-31T00:18:20
2016-12-31T00:18:20
68,438,382
0
0
null
null
null
null
UTF-8
C++
false
false
1,838
h
#ifndef WEAPONENTITY_H_INCLUDED #define WEAPONENTITY_H_INCLUDED #include "Stdafx.h" #include "Entity.h" #include "CoreString.h" #include "WeaponBeanEntity.h" /* TABLE ENT_WEAPONS ID INT ID_TILE INT SCRIPT_ANIM CHAR(20) SCRIPT_AI CHAR(20) */ class WeaponEntity : public Entity{ public: WeaponEntity():Entity(WEAPON_ENT){ weaponEfects.clear(); }; WeaponEntity(uint32_t timestamp):Entity(WEAPON_ENT, timestamp){ weaponEfects.clear(); }; WeaponEntity(WeaponEntity *weaponEntityRef, uint32_t timestamp):Entity(WEAPON_ENT, timestamp){ Entity::copyTo((Entity *)weaponEntityRef); copyWeaponsBean(weaponEntityRef); }; void copyTo(WeaponEntity *weaponEntityRef){ Entity::copyTo((Entity *)weaponEntityRef); copyWeaponsBean(weaponEntityRef); }; void clear(){ Entity::clear(); weaponEfects.clear(); }; ~WeaponEntity(){ Entity::clear(); weaponEfects.clear(); }; void addWeaponBeanEntity(WeaponBeanEntity *beam){ weaponEfects.push_back(beam); }; int getWeaponBeanEntitySize(){return weaponEfects.size();} WeaponBeanEntity *getWeaponBeanEntity(int index){ if ((index >= 0) && (index < weaponEfects.size())){ return weaponEfects[index]; }else{ return NULL; } }; void copyWeaponsBean(WeaponEntity *weaponEntityRef){ weaponEfects.clear(); for (int i=0; i<weaponEntityRef->getWeaponBeanEntitySize(); i++){ WeaponBeanEntity *wBE = new WeaponBeanEntity(weaponEntityRef->getWeaponBeanEntity(i),0); weaponEfects.push_back(wBE); } }; private: std::vector<WeaponBeanEntity *>weaponEfects; }; #endif // WEAPONENTITY_H_INCLUDED
[ "jeag2002@gmail.com" ]
jeag2002@gmail.com
aca7aacf546aeb356157a709964346823e8a1647
376839698ec0fa0664db953463938776afb797a8
/CC/include/Delaunay2dMesh.h
9ce769ee711b704f9782d184888afb2cab18ebe0
[]
no_license
weimzh/CloudCompare-web
abf05c69147356bb703d25f56ab7e876fdc11b70
35f98790c5912c0cfe8adb8eb0db7cbb3593dfbf
refs/heads/main
2023-04-04T15:36:04.914206
2019-07-04T05:57:03
2019-07-04T05:57:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,915
h
//########################################################################## //# # //# 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 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) # //# # //########################################################################## #ifndef DELAUNAY2D_MESH_HEADER #define DELAUNAY2D_MESH_HEADER #include "GenericIndexedMesh.h" #include "Neighbourhood.h" #include "SimpleTriangle.h" namespace CCLib { class GenericIndexedCloud; //! A class to compute and handle a Delaunay 2D mesh on a subset of points #ifdef CC_USE_AS_DLL #include "CloudCompareDll.h" class CC_DLL_API Delaunay2dMesh : public GenericIndexedMesh #else class Delaunay2dMesh : public GenericIndexedMesh #endif { public: //! Delaunay2dMesh constructor Delaunay2dMesh(); //! Delaunay2dMesh destructor virtual ~Delaunay2dMesh(); //! Associate this mesh to a point cloud /** This particular mesh structure deals with point indexes instead of points. Therefore, it is possible to change the associated point cloud (it the new cloud has the same size). For example, it can be useful to compute the mesh on 2D points corresponding to 3D points that have been projected on a plane and then to link this structure with the 3D original points. \param aCloud a point cloud \param passOwnership if true the Delaunay2dMesh destructor will delete the cloud as well **/ virtual void linkMeshWith(GenericIndexedCloud* aCloud, bool passOwnership=false); //! Build the Delaunay mesh on top a set of 2D points /** \param the2dPoints a set of 2D points \return success **/ virtual bool build(CC2DPointsContainer &the2dPoints); //inherited methods (see GenericMesh) virtual unsigned size() const {return numberOfTriangles;}; virtual void forEach(genericTriangleAction& anAction); virtual void getBoundingBox(PointCoordinateType bbMin[], PointCoordinateType bbMax[]); virtual void placeIteratorAtBegining(); virtual GenericTriangle* _getNextTriangle(); virtual GenericTriangle* _getTriangle(unsigned triangleIndex); virtual TriangleSummitsIndexes* getNextTriangleIndexes(); virtual TriangleSummitsIndexes* getTriangleIndexes(unsigned triangleIndex); virtual void getTriangleSummits(unsigned triangleIndex, CCVector3& A, CCVector3& B, CCVector3& C); protected: //! Associated point cloud GenericIndexedCloud* m_associatedCloud; //! Triangle vertex indexes int* m_triIndexes; //! Iterator on the list of triangle vertex indexes int* m_globalIterator; //! End position of global iterator int* globalIteratorEnd; //! The number of triangles unsigned numberOfTriangles; //! Specifies if the associated cloud should be deleted when the mesh is deleted bool cloudIsOwnedByMesh; //! Dump triangle structure to transmit temporary data SimpleTriangle dumpTriangle; //! Dump triangle index structure to transmit temporary data TriangleSummitsIndexes dumpTriangleIndexes; }; } #endif //DELAUNAY2D_MESH_HEADER
[ "weimingzhi@baidu.com" ]
weimingzhi@baidu.com
5fdbee27552cd089554ecbf84bf1de8352d70ef6
7fbc9eb28a3c09abac82f32982d1448a2b54193e
/mvMotionAI/examples-src/sideproject3/lfpe-bullet/external lib examples/BspDemo.cpp
4ea66cd21c20cb3da6bb835db7e0e220a3560a69
[ "MIT" ]
permissive
tgsstdio/mvMotionAI
1a83dfef6fd6d4524ec168576a7d7a252268d3dd
26c452b90d7555872dd9d13a0733aba348e9898e
refs/heads/master
2021-01-12T15:58:06.394223
2016-09-27T06:22:22
2016-09-27T06:22:22
69,325,477
0
0
null
null
null
null
UTF-8
C++
false
false
7,673
cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ 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 "btBulletDynamicsCommon.h" #include "LinearMath/btQuickprof.h" #include "LinearMath/btIDebugDraw.h" #include "GLDebugDrawer.h" #define QUAKE_BSP_IMPORTING 1 #ifdef QUAKE_BSP_IMPORTING #include "BspLoader.h" #include "BspConverter.h" #endif //QUAKE_BSP_IMPORTING #include "BMF_Api.h" #include <stdio.h> //printf debugging #include "BspDemo.h" #include "GL_ShapeDrawer.h" #include "GlutStuff.h" #define CUBE_HALF_EXTENTS 1 #define EXTRA_HEIGHT -20.f ///BspToBulletConverter extends the BspConverter to convert to Bullet datastructures class BspToBulletConverter : public BspConverter { BspDemo* m_demoApp; public: BspToBulletConverter(BspDemo* demoApp) :m_demoApp(demoApp) { } virtual void addConvexVerticesCollider(btAlignedObjectArray<btVector3>& vertices, bool isEntity, const btVector3& entityTargetLocation) { ///perhaps we can do something special with entities (isEntity) ///like adding a collision Triggering (as example) if (vertices.size() > 0) { float mass = 0.f; btTransform startTransform; //can use a shift startTransform.setIdentity(); startTransform.setOrigin(btVector3(0,0,-10.f)); //this create an internal copy of the vertices btCollisionShape* shape = new btConvexHullShape(&(vertices[0].getX()),vertices.size()); m_demoApp->m_collisionShapes.push_back(shape); //btRigidBody* body = m_demoApp->localCreateRigidBody(mass, startTransform,shape); m_demoApp->localCreateRigidBody(mass, startTransform,shape); } } }; //////////////////////////////////// BspDemo::~BspDemo() { //cleanup in the reverse order of creation/initialization //remove the rigidbodies from the dynamics world and delete them int i; for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--) { btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i]; btRigidBody* body = btRigidBody::upcast(obj); if (body && body->getMotionState()) { delete body->getMotionState(); } m_dynamicsWorld->removeCollisionObject( obj ); delete obj; } //delete collision shapes for (int j=0;j<m_collisionShapes.size();j++) { btCollisionShape* shape = m_collisionShapes[j]; delete shape; } //delete dynamics world delete m_dynamicsWorld; //delete solver delete m_solver; //delete broadphase delete m_broadphase; //delete dispatcher delete m_dispatcher; delete m_collisionConfiguration; } void BspDemo::initPhysics(char* bspfilename) { m_cameraUp = btVector3(0,0,1); m_forwardAxis = 1; setCameraDistance(22.f); ///Setup a Physics Simulation Environment m_collisionConfiguration = new btDefaultCollisionConfiguration(); // btCollisionShape* groundShape = new btBoxShape(btVector3(50,3,50)); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); btVector3 worldMin(-1000,-1000,-1000); btVector3 worldMax(1000,1000,1000); m_broadphase = new btAxisSweep3(worldMin,worldMax); //btOverlappingPairCache* broadphase = new btSimpleBroadphase(); m_solver = new btSequentialImpulseConstraintSolver(); //ConstraintSolver* solver = new OdeConstraintSolver; m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration); m_dynamicsWorld->setGravity(-m_cameraUp * 10); #ifdef QUAKE_BSP_IMPORTING void* memoryBuffer = 0; FILE* file = fopen(bspfilename,"r"); if (!file) { //try again other path, //sight... visual studio leaves the current working directory in the projectfiles folder //instead of executable folder. who wants this default behaviour?!? bspfilename = "../../BspDemo.bsp"; file = fopen(bspfilename,"r"); } if (!file) { //try again other path, //sight... visual studio leaves the current working directory in the projectfiles folder //instead of executable folder. who wants this default behaviour?!? bspfilename = "BspDemo.bsp"; file = fopen(bspfilename,"r"); } if (file) { BspLoader bspLoader; int size=0; if (fseek(file, 0, SEEK_END) || (size = ftell(file)) == EOF || fseek(file, 0, SEEK_SET)) { /* File operations denied? ok, just close and return failure */ printf("Error: cannot get filesize from %s\n", bspfilename); } else { //how to detect file size? memoryBuffer = malloc(size+1); fread(memoryBuffer,1,size,file); bspLoader.loadBSPFile( memoryBuffer); BspToBulletConverter bsp2bullet(this); float bspScaling = 0.1f; bsp2bullet.convertBsp(bspLoader,bspScaling); } fclose(file); } #endif clientResetScene(); } void BspDemo::clientMoveAndDisplay() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); float dt = getDeltaTimeMicroseconds() * 0.000001f; m_dynamicsWorld->stepSimulation(dt); //optional but useful: debug drawing m_dynamicsWorld->debugDrawWorld(); renderme(); glFlush(); glutSwapBuffers(); } void BspDemo::displayCallback(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderme(); glFlush(); glutSwapBuffers(); } //some code that de-mangles the windows filename passed in as argument char cleaned_filename[512]; char* getLastFileName() { return cleaned_filename; } char* makeExeToBspFilename(const char* lpCmdLine) { // We might get a windows-style path on the command line, this can mess up the DOM which expects // all paths to be URI's. This block of code does some conversion to try and make the input // compliant without breaking the ability to accept a properly formatted URI. Right now this only // displays the first filename const char *in = lpCmdLine; char* out = cleaned_filename; *out = '\0'; // If the first character is a ", skip it (filenames with spaces in them are quoted) if(*in == '\"') { in++; } int i; for(i =0; i<512; i++) { //if we get '.' we stop as well, unless it's the first character. Then we add .bsp as extension // If we hit a null or a quote, stop copying. This will get just the first filename. if(i && (in[0] == '.') && (in[1] == 'e') && (in[2] == 'x') && (in[3] == 'e')) break; // If we hit a null or a quote, stop copying. This will get just the first filename. if(*in == '\0' || *in == '\"') break; // Copy while swapping backslashes for forward ones if(*in == '\\') { *out = '/'; } else { *out = *in; } in++; out++; } *(out++) = '.'; *(out++) = 'b'; *(out++) = 's'; *(out++) = 'p'; *(out++) = 0; return cleaned_filename; }
[ "tgsstdio@gmail.com" ]
tgsstdio@gmail.com
08ed28222adab6de69b3ed39fb90afb81d74ace1
50f01b16addd566bb644cc6c4c320d975caa5bff
/Classes/proto/HallInfo.h
eac2cf9508451c09aa0cf2bf20b634b6aabb35c8
[]
no_license
atom-chen/GameClient
88fdbde79550c27990dba6de42b178b392313dd4
61dcb85175e379a564940812e644e943e76bcfe1
refs/heads/master
2020-06-06T08:09:28.927488
2018-05-28T10:24:10
2018-05-28T10:24:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,243
h
 #ifndef __HallInfo__ #define __HallInfo__ #include "AppMacros.h" #include "ccEvent.h" class HallInfo:public Object { public: HallInfo(); ~HallInfo(); static HallInfo* getIns(); bool init(); public: //rank void SendCRank(int type,int index); void HandlerSRankHand(ccEvent *event); //shop void SendCShop(int type); void HandlerSShop(ccEvent *event); //firstbuy void SendCFirsyBuyData(); void HandSFirsyBuyData(ccEvent *event); //mail void SendCMail(); void HandlerSMail(ccEvent *event); void SendCMailAward(int eid); void HandlerSMailAward(ccEvent *event); //friend void SendCFriend(); void HandlerSFriend(ccEvent *event); void SendCFindFriend(string uid,int type); void HandlerSFindFriend(ccEvent *event); void SendCGiveFriend(string uid); void HandlerSGiveFriend(ccEvent *event); void SendCAddFriend(string uid); void HandlerSAddFriend(ccEvent *event); void SendCAddFriendList(); void HandlerSAddFriendList(ccEvent *event); void SendCAgreeFriend(string uid,int nid, bool agree); void HandlerSAgreeFriend(ccEvent *event); void SendCFriendChat(string uid, string content); void HandlerSFriendChat(ccEvent *event); void SendCFriendChatList(); void HandSFriendChatList(ccEvent *event); void SendCFriendChatRead(FriendChat fc); void HandSFriendChatRead(ccEvent *event); //active void SendCActive(int type); void HandlerSActive(ccEvent *event); //task void SendCTask(); void HandlerSTask(ccEvent *event); ///////////exchange void SendCReward(int id); void HandlerSReward(ccEvent *event); void SendCExchangeReward(); void HandlerSExchangeReward(ccEvent *event); void SendCExchangeCode(string excode,string yzcode); void HandlerSExchangeCode(ccEvent *event); void SendCExchangeRecord(); void HandlerSExchangeRecord(ccEvent *event); void SendCExchange(int id); void HandlerSExchange(ccEvent *event); //////////pay void SendCApplePay(int id, string receipt); void HandlerSApplePay(ccEvent *event); void SendCWxpayOrder(int id,string body); void HandlerSWxpayOrder(ccEvent *event); void SendCWxpayQuery(string transid); void HandlerSWxpayQuery(ccEvent *event); void SendCFirstBuy(int type); void HandlerSFirstBuy(ccEvent *event); void SendCAliPayOrder(int id,string body); void HandlerSAliPayOrder(ccEvent *event); void SendCAliPayResult(string content); void HandlerSAliPayResult(ccEvent *event); //feedback void SendCFeedBack(string uid,string uname,string content); void HandlerSFeedBack(ccEvent *event); //sign void SendCSign(); void HandlerSSign(ccEvent *event); void SendCSignList(); void HandlerSSignList(ccEvent *event); SignAward *getSignAward(int rid); map<int, Rank> getSRank(int type); void eraseRank(int type,int lv); SShop getSShop(int type); SMail getSMail(){ return m_pSMail; } SFindFriend getSFindFriend(){ return m_pSFindFriend; } SFriend getSFriend(){ return m_pSFriend; } SAddFriendList getSAddFriendList(){ return m_pSAddFriendList; } STask getSTask(){ return m_pSTask; } SExchangeReward getSExchangeReward(){ return m_pSExchangeReward; } SExchangeRecord getSExchangeRecord(){ return m_pSExchangeRecord; } SSignList getSSignList(){ return m_pSSignList; } SSign getSSign(){ return m_pSSign; } SFirsyBuyData getSFirsyBuyData(){ return m_pSFirsyBuyData; } Friend getFriend(string fruid); vector<FriendChat *> getFriendChat(string uid); void setFriendChat(FriendChat *p); void eraseFriendChat(FriendChat *p); private: static HallInfo *m_shareHallInfo; map<int, map<int,Rank>> m_pSRanks; map<int, SShop>m_pSShops; SActive m_pSActive; SMail m_pSMail; SFindFriend m_pSFindFriend; SFriend m_pSFriend; SAddFriendList m_pSAddFriendList; STask m_pSTask; SExchangeReward m_pSExchangeReward; SExchangeRecord m_pSExchangeRecord; SSignList m_pSSignList; SSign m_pSSign; SFirsyBuyData m_pSFirsyBuyData; map<int, SignAward *>m_pSignZhuan; map<string, Friend >m_pfriends; SAgreeFriend m_pSAgreeFriend; SFriendChat m_pSFriendChat; map<string,vector<FriendChat *>> m_pFriendChat; }; #endif
[ "37165209+qianpeng0523@users.noreply.github.com" ]
37165209+qianpeng0523@users.noreply.github.com
1882235700ea040e19dd05ecc78adf871e9bcc74
bc10911b97dc92aa044dfdae57f51eb9e96dce89
/AVWClient/Singleton.hpp
523f7b67c05af48a858eb5a60203e3cd98e9dba8
[ "MIT" ]
permissive
Sr173/AVWClient
46c34ee93ce824209d8d17a307d8b06d60d08e33
478e1c29b7b0c059d2171c01ad96fffd035c7c9d
refs/heads/master
2020-05-14T14:03:37.126432
2019-08-09T14:56:03
2019-08-09T14:56:03
181,824,831
1
0
null
null
null
null
UTF-8
C++
false
false
128
hpp
#pragma once template <class T> class Singleton { public: static T* getPtr() { static T* ptr = new T; return ptr; } };
[ "66456804@qq.com" ]
66456804@qq.com
9e2868d7e5e543e750fb0bf5b4e051f6ad76c684
36dda2f6e0d6bc9509fc905ce515e414e6aa836d
/MathVector.h
d9a4636d066f3f220c55db18f800006b649064ff
[]
no_license
denizsomer/readLog
e399dc9ec12bc1cbdc1d715303edcc5e0ed21238
db06b9e6652909ce59efeb8bb4effd6ab4591a54
refs/heads/master
2020-05-19T20:53:22.670130
2015-08-13T09:57:00
2015-08-13T09:57:00
40,651,790
0
0
null
null
null
null
UTF-8
C++
false
false
12,450
h
#ifndef incl_MathVector_h #define incl_MathVector_h #include <cmath> #include "ContainerBase.h" #include "LinkedListBase.h" #include "MathBasic.h" // vector classes // // VectorBase - abstract base class // Vector - vector based on a linked list // VectorArray - vector based on an array // VectorFixed - vector based on an array of fixed length // VectorInfinite - vector based on an infinite linked list //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // vector coefficient class needed for Vector template<typename Type> class VectorCoeff: public ListItem { public: // implicit copy constructor // implicit destructor // implicit default assignemt operator VectorCoeff(void) { val = (Type) 0; } define_generateCopy(VectorCoeff<Type>) Type val; template<class Type2> bool operator>(Type2 &b) { return val > b.val; } template<class Type2> bool operator<(Type2 &b) { return val < b.val; } }; //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // abstract vector base class template<typename Type> class VectorBase: public virtual ContainerBase, public ListItem { public: // implicit default constructor // implicit copy constructor // implicit destructor // implicit default assignment operator virtual Type &operator[](int) = 0; virtual Type &operator()(int); template<class Type2> bool operator==(Type2 &); virtual Type &firstCoeff(void); virtual Type &lastCoeff(void); virtual void print(std::ostream &os = std::cout); virtual void zero(void); virtual Type norm(void); virtual bool contains(Type, int *indx = NULL); template<class Type2> bool containsAllOf(Type2 &); template<class Type2> bool containsTheSameAs(Type2 &); virtual bool containsAllOf(Type*, int); template<class Type2> bool containsAtLeastOneOf(Type2 &, int *indx = NULL, int *indx2 = NULL); template<class Type2> bool containsSomeOf(int, Type2 &); virtual bool distinct(void); virtual void permute(int *, int *flagPtr = NULL); }; //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // // vector based on a linked list template<typename Type> class Vector: public VectorBase<Type>, public LinkedListBase< VectorCoeff<Type> > { public: // implicit default constructor // implicit copy constructor // implicit desctructor // implicit default assignment operator define_generateCopy(Vector<Type>) Type &operator[](int); template<class Type2> Vector<Type> &operator=(Type2 &); Type* append(Type val = (Type) 0); void insert(Type,int); void del(int); Type &firstCoeff(void); Type &lastCoeff(void); }; //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // // vector based on an array template<typename Type> class VectorArray: public VectorBase<Type> { public: VectorArray(void) { x = NULL; } VectorArray(VectorArray<Type> &that): VectorBase<Type>(that) { *this = that; } virtual ~VectorArray() { this->free(); } define_generateCopy(VectorArray<Type>) virtual Type &operator[](int); VectorArray<Type> &operator=(VectorArray<Type> &); // default assignment operator template<class Type2> VectorArray<Type> &operator=(Type2 &); void setDim(int); virtual void free(void); virtual void expand(int); Type *x; }; //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // // simple vector based on array of fixed length template<typename Type, int dimension> class VectorFixed: public VectorBase<Type> { public: // implicit copy constructor // implicit destructur // implicit default assignment operator VectorFixed(void) { this->n = dimension; } VectorFixed<Type,dimension> *generateCopy(void) { return new VectorFixed<Type,dimension>(*this); } template<class Type2> VectorFixed<Type,dimension> &operator=(Type2 &b) { if (this->n == b.n) for (int i=0; i<this->n; i++) x[i] = b[i]; return *this; } virtual Type &operator[](int i) { return x[i]; } Type x[dimension]; }; //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // // vector based on an infinite linked list template<typename Type> class VectorInfinite: public Vector<Type> { public: // implicit default constructor // implicit copy constructor // implicit destructur // implicit default assignment operator define_generateCopy(VectorInfinite<Type>) template<class Type2> VectorInfinite<Type> &operator=(Type2 &b) { this->Vector<Type>::operator=(b); return *this; } virtual Type &operator[](int i) { while (i > this->n-1) this->append((Type) 0); return LinkedListBase< VectorCoeff<Type> >::getItem(i).val; } }; //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<typename Type> Type &VectorBase<Type>::operator()(int i) { return (*this)[i-1]; } template<typename Type> Type &VectorBase<Type>::firstCoeff(void) { return (*this)[0]; } template<typename Type> Type &VectorBase<Type>::lastCoeff(void) { return (*this)[this->n-1]; } template<typename Type> void VectorBase<Type>::print(std::ostream &os) { os << "{"; if (this->n > 0) os << (*this)[0]; else os << " "; for (int i=1; i<this->n; i++) os << "," << (*this)[i]; os << "}"; return; } template<typename Type> void VectorBase<Type>::zero(void) { for (int i=0; i<this->n; i++) (*this)[i] = (Type) 0; return; } template<typename Type> Type VectorBase<Type>::norm(void) { std::cout << " Warning! norm only works for Vector<double> or Vector<int>!\n\n"; return (Type) 0; } template<> inline double VectorBase<double>::norm(void) { double y = 0.; for (int i=0; i<this->n; i++) y += (*this)[i] * (*this)[i]; return sqrt(y); } template<> inline int VectorBase<int>::norm(void) { int y = 0; for (int i=0; i<this->n; i++) y += (*this)[i] * (*this)[i]; return roundToInt(sqrt((double)y)); } template<> inline unsigned int VectorBase<unsigned int>::norm(void) { unsigned int y = 0; for (int i=0; i<this->n; i++) y += (*this)[i] * (*this)[i]; return (unsigned int) roundToInt(sqrt((double)y)); } template<typename Type> bool VectorBase<Type>::contains(Type xx, int *indx) { int i = 0; while (i < this->n) if ((*this)[i] == xx) break; else i++; if (i < this->n) { if (indx != NULL) *indx = i; return true; } if (indx != NULL) *indx = -1; return false; } template<typename Type> template<class Type2> bool VectorBase<Type>::containsAllOf(Type2 &vec2) { for (int i=0; i<vec2.n; i++) if (!this->contains(vec2[i])) return false; return true; } template<typename Type> template<class Type2> bool VectorBase<Type>::containsTheSameAs(Type2 &vec2) { int i; if (this->n != vec2.n) return false; // returns false as soon as one element of myself is not found in vec2 for (int i=0; i<vec2.n; i++) if (!this->contains(vec2[i])) return false; return true; } template<typename Type> bool VectorBase<Type>::containsAllOf(Type *a, int m) { for (int i=0; i<m; i++) if (!this->contains(a[i])) return false; return true; } template<typename Type> template<class Type2> bool VectorBase<Type>::containsAtLeastOneOf(Type2 &vec2, int *indx, int *indx2) { int i = 0, j; while (i < this->n) { j = 0; while (j < vec2.n && (*this)[i] != vec2[j]) j++; if (j < vec2.n) { if (indx != NULL) *indx = i; if (indx2 != NULL) *indx2 = j; return true; } i++; } return false; } template<typename Type> template<class Type2> bool VectorBase<Type>::containsSomeOf(int m, Type2 &vec2) { int i = 0, j, c = 0; while (i < this->n) { j = 0; while (j < vec2.n && (*this)[i] != vec2[j]) j++; if (j < vec2.n) { c++; if (c == m) return true; } i++; } return false; } template<typename Type> bool VectorBase<Type>::distinct(void) { int i, j; for (i=1; i<this->n; i++) for (j=0; j<i; j++) if ((*this)[i] == (*this)[j]) return false; return true; } template<typename Type> template<class Type2> bool VectorBase<Type>::operator==(Type2 &b) { if (this->n != b.n) return false; int i = 0; while (i < this->n) if ((*this)[i] == b[i]) i++; else return false; return true; } template<typename Type> void VectorBase<Type>::permute(int *perm, int *flagPtr) { Type dmy, *p1, *p2; int i, j = 0, *flag = flagPtr, m = this->n; if (flag == NULL) flag = new int [m]; for (i=0; i<m; i++) flag[i] = 1; i = 0; while (i < m) { p2 = &((*this)[i]); dmy = *p2; do { p1 = p2; p2 = &((*this)[perm[j]]); *p1 = *p2; //cout << *p1 << " A\n"; flag[j] = 0; j = perm[j]; //cout << *this << "\n"; } while (i != perm[j]); *p2 = dmy; flag[j] = 0; //cout << *p2 << " B\n"; i++; while (i < m) if (flag[i]) break; else i++; //cout << *this << "," << i << "\n"; j = i; } if (flagPtr == NULL) delete [] flag; return; } template<typename Type> std::ostream &operator<<(std::ostream &os, VectorBase<Type> &vec) { vec.print(os); return os; } //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<typename Type> Type &Vector<Type>::operator[](int i) { return LinkedListBase< VectorCoeff<Type> >::getItem(i).val; } //template<typename Type> Vector<Type> &Vector<Type>::operator=(Vector<Type> &b) //{ // cout << "Vector<Type>::operator= (1)\n"; // // this->free(); // // for (int i=0; i<b.n; i++) append(b[i]); // // return *this; //} template<typename Type> template<class Type2> Vector<Type> &Vector<Type>::operator=(Type2 &b) { //cout << "Vector<Type>::operator=\n"; this->free(); for (int i=0; i<b.n; i++) append(b[i]); return *this; } template<typename Type> Type *Vector<Type>::append(Type x) { VectorCoeff<Type> *c = new VectorCoeff<Type>; c->val = x; this->add(c); return &(c->val); } template<typename Type> void Vector<Type>::insert(Type x, int pos) { VectorCoeff<Type> *c = new VectorCoeff<Type>; c->val = x; LinkedListBase< VectorCoeff<Type> >::insert(c,pos); return; } template<typename Type> void Vector<Type>::del(int pos) { LinkedListBase< VectorCoeff<Type> >::del(pos); return; } template<typename Type> Type &Vector<Type>::firstCoeff(void) { return ((VectorCoeff<Type>*)(this->first.next))->val; } template<typename Type> Type &Vector<Type>::lastCoeff(void) { return ((VectorCoeff<Type>*)(this->last.prev))->val; } //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<typename Type> Type &VectorArray<Type>::operator[](int i) { if (i < 0 || i+1 > this->n) cout << " ERROR: VectorArray<Type>::operator[]: invalid index!\n\n"; return x[i]; } template<typename Type> VectorArray<Type> &VectorArray<Type>::operator=(VectorArray<Type> &b) { setDim(b.n); for (int i=0; i<this->n; i++) x[i] = b[i]; return *this; } template<typename Type> template<class Type2> VectorArray<Type> &VectorArray<Type>::operator=(Type2 &b) { setDim(b.n); for (int i=0; i<this->n; i++) x[i] = b[i]; return *this; } template<typename Type> void VectorArray<Type>::setDim(int d) { if (d != this->n) { this->free(); x = new Type [d]; this->n = d; } return; } template<typename Type> void VectorArray<Type>::free(void) { if (x != NULL && this->n != 0) delete [] x; x = NULL; this->n = 0; return; } template<typename Type> void VectorArray<Type>::expand(int d) { if (d <= this->n) return; Type *tmp = new Type [d]; int i = 0; while (i < this->n) tmp[i] = x[i++]; while (i < d) tmp[i++] = (Type) 0; delete [] x; x = tmp; this->n = d; return; } #endif
[ "denizsomer@gmail.com" ]
denizsomer@gmail.com
c473a24210ed841d4e87efb737d69bf79bb6788d
59d247ef1d7208d55e5086f044d793fa218b8416
/Wrapper.cpp
23c6b143e82d31d1c6aad790e6854e2e437b789e
[]
no_license
manolaqe/Proiect_POO1
3867ca3d78cfd09fb5b583115d55c8853443294e
c63ae0c4d69033ba2f3760e2c809f3d6a30f4da0
refs/heads/master
2023-02-18T22:38:51.707754
2021-01-19T14:21:07
2021-01-19T14:21:07
328,775,322
1
1
null
null
null
null
UTF-8
C++
false
false
2,782
cpp
#include "Wrapper.h" Wrapper::Wrapper(Produs produs, int cantitateProdus) { this->produs = produs; this->cantitateProdus = cantitateProdus; } Wrapper::Wrapper(int idProdus, const char* numeProdus, float pretProdus, int cantitateProdus) { this->produs.idProdus = idProdus; this->produs.nrElemNume = strlen(numeProdus); this->produs.numeProdus = new char[strlen(numeProdus) + 1]; strcpy_s(this->produs.numeProdus, strlen(numeProdus) + 1, numeProdus); this->produs.pretProdus = pretProdus; this->cantitateProdus = cantitateProdus; } Produs Wrapper::getProdus() { return produs; } int Wrapper::getCantitateProdus() { return this->cantitateProdus; } void Wrapper::setCantitateProdus(int cantitateProdus) { this->cantitateProdus = cantitateProdus; if (this->cantitateProdus <= 0) { this->produs = Produs(); cantitateProdus = -1; } } Wrapper::Wrapper() { Produs p(99, "ProdusNecunoscut", 2.3f); this->produs = p; this->cantitateProdus = 3; } Wrapper::Wrapper(const Wrapper& w) { cantitateProdus = w.cantitateProdus; produs = w.produs; } ostream& operator<<(ostream& iesire, Wrapper& w) { //iesire << "numeProdus.push_back(" << w.produs.getNumeProdus() << ");"; iesire << " \nPRODUS:" << w.produs.numeProdus << "\nID: " << w.produs.idProdus << "\nPRET: " << w.produs.pretProdus << "\nCANTITATE: " << w.cantitateProdus << endl; return iesire; } void Wrapper::serializare(ofstream& out, Wrapper w) { out.write((char*)&w.produs.idProdus, sizeof(int)); out.write((char*)&w.produs.nrElemNume, sizeof(int)); out.write(w.produs.numeProdus, w.produs.nrElemNume * sizeof(char)); out.write((char*)&w.produs.pretProdus, sizeof(float)); out.write((char*)&w.cantitateProdus, sizeof(int)); out.flush(); } Wrapper Wrapper::deserializare(ifstream& in) { Wrapper aux; in.read(reinterpret_cast<char*>(&aux), sizeof(Wrapper)); return aux; } ifstream& operator>>(ifstream& in, Wrapper& w) { delete[] w.produs.numeProdus; in.read((char*)&w.produs.nrElemNume, sizeof(int)); w.produs.numeProdus = new char[w.produs.nrElemNume + 1]; int size = (w.produs.nrElemNume + 1) * sizeof(char); in.read(w.produs.numeProdus, size); in.read((char*)&w.produs.idProdus, sizeof(int)); in.read((char*)&w.produs.pretProdus, sizeof(float)); in.read((char*)&w.cantitateProdus, sizeof(int)); return in; } ofstream& operator<<(ofstream& out, Wrapper w) { out.write((char*)&w.produs.nrElemNume, sizeof(int)); int size = (w.produs.nrElemNume + 1) * sizeof(char); out.write(w.produs.numeProdus, size); out.write((char*)&w.produs.idProdus, sizeof(int)); out.write((char*)&w.produs.pretProdus, sizeof(float)); out.write((char*)&w.cantitateProdus, sizeof(int)); return out; } void Wrapper::operator+=(int cantitateProdus) { this->cantitateProdus += cantitateProdus; }
[ "manolachemihaiandrei@protonmail.ch" ]
manolachemihaiandrei@protonmail.ch
4175230095b0c386a1e9652cb365d6ce3db006ff
aee3d6ddc9ff388ed7d67681ca2b3a946ce4aab6
/src/pauseanimation.h
38d5f4e86448437ac90c8d13bee6319824c1a963
[]
no_license
bzar/glhck-scene
c9fc3aab2d74ba97de3e80e32d2381a69b46acc3
d162ab23534c20812cf660b1a4c705ec41f80576
refs/heads/master
2020-06-04T12:11:09.568488
2013-03-11T17:25:18
2013-03-11T17:25:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
380
h
#ifndef PAUSEANIMATION_HH #define PAUSEANIMATION_HH #include "animatable.h" class PauseAnimation : public Animatable { public: PauseAnimation(); void animate(float const delta); bool isFinished() const; void reset(); void setDuration(float const value); void setLoops(int const value); private: float duration; float time; int loops; int loop; }; #endif
[ "teemu.erkkola@iki.fi" ]
teemu.erkkola@iki.fi
5f69df102f649218d99a6b36c577c0dfe996e787
10b4db1d4f894897b5ee435780bddfdedd91caf7
/thrift/compiler/test/fixtures/frozen-struct/gen-cpp2/include1_layouts.cpp
1595c67c567b10d17dd8558dda0b20679923c82b
[ "Apache-2.0" ]
permissive
SammyEnigma/fbthrift
04f4aca77a64c65f3d4537338f7fbf3b8214e06a
31d7b90e30de5f90891e4a845f6704e4c13748df
refs/heads/master
2021-11-11T16:59:04.628193
2021-10-12T11:19:22
2021-10-12T11:20:27
211,245,426
1
0
Apache-2.0
2021-07-15T21:12:07
2019-09-27T05:50:42
C++
UTF-8
C++
false
false
1,037
cpp
/** * Autogenerated by Thrift for src/include1.thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated @nocommit */ #include "thrift/compiler/test/fixtures/frozen-struct/gen-cpp2/include1_layouts.h" namespace apache { namespace thrift { namespace frozen { FROZEN_CTOR(::some::ns::IncludedA, FROZEN_CTOR_FIELD(i32Field, 1) FROZEN_CTOR_FIELD(strField, 2)) FROZEN_MAXIMIZE(::some::ns::IncludedA, FROZEN_MAXIMIZE_FIELD(i32Field) FROZEN_MAXIMIZE_FIELD(strField)) FROZEN_LAYOUT(::some::ns::IncludedA, FROZEN_LAYOUT_FIELD(i32Field) FROZEN_LAYOUT_FIELD(strField)) FROZEN_FREEZE(::some::ns::IncludedA, FROZEN_FREEZE_FIELD(i32Field) FROZEN_FREEZE_FIELD(strField)) FROZEN_THAW(::some::ns::IncludedA, FROZEN_THAW_FIELD(i32Field) FROZEN_THAW_FIELD(strField)) FROZEN_DEBUG(::some::ns::IncludedA, FROZEN_DEBUG_FIELD(i32Field) FROZEN_DEBUG_FIELD(strField)) FROZEN_CLEAR(::some::ns::IncludedA, FROZEN_CLEAR_FIELD(i32Field) FROZEN_CLEAR_FIELD(strField)) }}} // apache::thrift::frozen
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
38cb648cb05ae777031b906259be97ae20cf5a36
62968d5589d3eae8d3befebf7f7680b0840d4348
/Client/LoginDialog.hpp
33143fbc6b6af6dc3e5f0af2495243c0151071bb
[]
no_license
x3sphiorx/r3e
d400407594ad1bb649c952de9ba0b2d2669ab63e
addbca176ac2c32ebe4a347f47f8862a505fe11c
refs/heads/master
2021-01-17T20:21:53.838579
2013-02-03T19:29:39
2013-02-03T19:29:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
506
hpp
#ifndef LOGIN_DIALOG_HPP #define LOGIN_DIALOG_HPP #include "..\RGE\Dialog.hpp" class Button; class EditBox; class LoginDialog : public Dialog { public: LoginDialog(); ~LoginDialog(); static LoginDialog* Create(); virtual void OnCreated(); virtual int HandleEvent(MouseEvent* evt); virtual int HandleEvent(KeyboardEvent* evt); private: void EmitLoginEvent(); private: EditBox* mUsername; EditBox* mPassword; Button* mButtonOK; Button* mButtonExit; }; #endif
[ "james.benton2@gmail.com" ]
james.benton2@gmail.com
ec78e31d22d12325d86611727ccef6ae0e8f76fd
b6c708ea6c7bada354c1af315cad8bcd388fe179
/T_PROS.CPP contains/AKHITA.CPP
650d8a5f25e3649d8dcb29da683ddaefdfcfd897
[]
no_license
ShashwathKumar/Shashu_Pokemon_game_CPP
57038046e4a0887850fe12c19ae4a45310d2bf34
6158e86a9e60a594ff3f267cb38e97b7113b280c
refs/heads/master
2016-08-12T12:53:29.441182
2015-10-22T15:26:47
2015-10-22T15:26:47
44,723,375
1
0
null
null
null
null
UTF-8
C++
false
false
3,516
cpp
/*************************************************************************** ********************* ************************* ******* It displays the Akhil teasing animation using ******************** *********** the function `Akhita' ************************* ***************************************************************************/ void Akhilta(); void Bye(); void akhita() { char ch; int m; clrscr(); { gotoxy(35,20); textcolor(GREEN+BLINK); cprintf("WELCOME Akhil"); delay(3000); } clrscr(); P: Akhilta(); S: textcolor(LIGHTGREEN); gotoxy(50,32); cprintf("PRESS"); gotoxy(50,34); cprintf("1.To repeat the animation"); gotoxy(50,36); cprintf("2.To continue with the game"); cout<<"\t"; ch=getche(); m=ch-48; textcolor(RED); if((m==1)||(m==2)) { if (m==1) goto P; else { Bye(); } } else { clrscr(); cout<<"\n\n\n\n\n\n\n\n\n\n\t YOU FOOL !! Can't you see what's written ......... "; goto S; } } //-----------THE MAJOR FUNTION " AKHILTA " ------------------------------- void Akhilta() { int a,b,c,d,i,j; //------- The Major Code ------- Mater loop ------ //The outer - most for loop is just to control the number of revoluions ***** for(int y=1; y<=2 && !kbhit() ; ++y) { for(int k=1; k<=4 && !kbhit() ; ++k) //The loop to assign arguments for the following for loops { switch(k) { case 1:{ a=20 ; b=20 ; c=10 ; d=80 ; break; } case 2:{ a=41 ; b=10 ; c=0 ; d=20 ; break; } case 3:{ a=59 ; b=21 ; c=0 ; d=30 ; break; } case 4:{ a=39 ; b=30 ; c=20 ; d=80 ; break; } } //-- The for - loop ------------- for(i=a, j=b; (j>=c)&&(j<=d) && !kbhit() ; ) { textcolor(BROWN); clrscr(); { for(int x=39; x<=41; ++x) //code to print the core { for(int y=19; y<=21; ++y) { gotoxy(x,y); cprintf("*"); } } textcolor(LIGHTGRAY); gotoxy(40,18); cprintf("*"); gotoxy(42,20); cprintf("*"); gotoxy(40,22); cprintf("*"); gotoxy(38,20); cprintf("*"); } { gotoxy(i,j); textcolor(BLUE); cprintf("o"); } { textcolor(GREEN); gotoxy(i-1,j); cprintf("-"); gotoxy(i+1,j); cprintf("-"); } delay(50); // ------ The incriment -- decrement code ------------- switch(k) { case 1: { if(i%2==0) ++i; else { ++i; --j; } break; } case 2: { if(i%2==0) ++i; else { ++i; ++j; } break; } case 3: { if(i%2==0) { --i; ++j; } else --i; break; } case 4: { if(i%2==0) --i; else { --i; --j; } break; } } } } } textcolor(LIGHTCYAN); delay(200); gotoxy(3,20); cprintf("Satellite -->"); delay(500); gotoxy(50,27); cprintf("Howzzatt.."); delay(400); } //-------- The cuty " Bye " function ------------------- void Bye() { textcolor(MAGENTA); char B[]="Welcome--again"; for(int i=0; i<=13; ++i) { clrscr(); for(int j=13; j>=i; --j) { gotoxy(j+40,20); cout<<B[j]; } delay(500); } delay(500); }
[ "pkattep@ncsu.edu" ]
pkattep@ncsu.edu
6698225337445aad67f2c2f94107540ba0f396ea
e900bfb6dcd70761984a9d464054b8f3c6a2157d
/self made - Question missing/ACN1.CPP
dabe3f11a63f0e3127bf1dfa5492562108be9651
[]
no_license
mridul88/Programs
1b43308146580e33d7564e1b1077df0c959c1e59
18960b34b844390fc34411da37f656ed70974463
refs/heads/master
2021-01-19T14:05:03.857012
2014-01-29T17:18:55
2014-01-29T17:18:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
635
cpp
#include<cstdio> using namespace std; int hcf(int a, int b) { if(b==0) return a; else hcf(b,a%b); } int main() { int k=0,r,b,flag=1,i,j,n,re,max=0; int *a; scanf("%d",&n); a=new int [n]; for(i=0;i<n;i++) scanf("%d",&a[i]); for(r=0;r<30;r++) { for(i=0;i<n;i++) { flag=1; k=hcf((a[i]-r),(a[(1+i)]-r)); //printf("\n%d %d",k,i); for(j=i+2;j<n;j++) /*to check k is valid*/ { b=a[j]%k; if(b!=r) flag=0; } if(flag==1) { if(max>k) { max=k; re=r;} } } } printf("%d %d",max,re); while(getchar()!='\n'); getchar(); return 0; }
[ "malpanimridul@gmail.com" ]
malpanimridul@gmail.com
c1f27a375ffb3a354ffb05daae9b3bc4fa022cb7
562fd1846ebf205ed1d0da30e0deea12adc9c2a1
/DerydocaEngine/src/Utilities/TexturePacker.h
9ed660bb6b6c4ac225484057b706c9fc46231e0d
[ "BSD-3-Clause" ]
permissive
luigicampbell/derydocaengine
1e31bee63eba26ee2de089e91948b8439ec59e64
d915c92392d31f94f84671c311528795f5fa6c84
refs/heads/master
2020-04-24T23:54:57.320317
2019-02-20T23:10:28
2019-02-20T23:10:28
172,360,592
1
0
BSD-3-Clause
2019-02-24T16:22:00
2019-02-24T16:25:02
null
UTF-8
C++
false
false
1,491
h
#pragma once #include <vector> #include <map> #include "Rectangle.h" #include "Utilities\TexturePackerImage.h" #include "Utilities\TexturePackerTextureData.h" #include "IntRect.h" namespace DerydocaEngine::Rendering { class Texture; } namespace DerydocaEngine::Utilities { class TexturePacker { public: TexturePacker(int const& channels); ~TexturePacker(); void addImage( unsigned long const& id, float const& sizeX, float const& sizeY, float const& bearingX, float const& bearingY, float const& advanceX, float const& advanceY, unsigned char* const& imageBuffer, int const& width, int const& height, int const& channels); void packImages(); bool getIsDirty() const { return m_isDirty; } std::shared_ptr<Rendering::Texture> allocTexture() { return m_packedImageData.allocTexture(); }; unsigned char* allocImageBuffer() { return m_packedImageData.allocImageBuffer(); } void freeSubImageData(); std::vector<TexturePackerImage> getSubImageData() { return m_images; } int getWidth() const { return m_packedImageData.getWidth(); } int getHeight() const { return m_packedImageData.getHeight(); } int getChannels() const { return m_packedImageData.getChannels(); } private: std::vector<TexturePackerImage> m_images; std::map<unsigned long, unsigned char*> m_imageBuffers; bool m_isDirty; TexturePackerTextureData m_packedImageData; int getIntersectingImageXAdvance(std::vector<IntRect> imageBounds, IntRect rect); }; }
[ "derrick.canfield@gmail.com" ]
derrick.canfield@gmail.com
08e3cc2b7cb05907af52079cdbed6d52a9489b8e
c17cb8f229a6762cb88848a70e9b6505adbcbcdd
/c++/src/vs-2019/HelloWinUICppWinRT/HelloWinUICppWinRT/Generated Files/winrt/impl/Windows.System.RemoteSystems.2.h
ec9e344f7c13b4b0e0ac8ece833b6ed9cf5e7be4
[]
no_license
awrznc/scribble
b1a49df8c66ffb0c63a01d0266a50277e3f2000a
cee07c2d6dc7960023673e3c3a31f1738da7a8e5
refs/heads/master
2023-08-18T22:31:01.852432
2023-06-12T12:16:42
2023-06-12T12:16:42
202,322,395
4
0
null
2023-09-13T13:12:44
2019-08-14T09:49:39
C++
UTF-8
C++
false
false
20,627
h
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.200703.9 #ifndef WINRT_Windows_System_RemoteSystems_2_H #define WINRT_Windows_System_RemoteSystems_2_H #include "winrt/impl/Windows.ApplicationModel.AppService.1.h" #include "winrt/impl/Windows.Foundation.1.h" #include "winrt/impl/Windows.Foundation.Collections.1.h" #include "winrt/impl/Windows.Networking.1.h" #include "winrt/impl/Windows.Security.Credentials.1.h" #include "winrt/impl/Windows.System.1.h" #include "winrt/impl/Windows.System.RemoteSystems.1.h" WINRT_EXPORT namespace winrt::Windows::System::RemoteSystems { struct KnownRemoteSystemCapabilities { KnownRemoteSystemCapabilities() = delete; [[nodiscard]] static auto AppService(); [[nodiscard]] static auto LaunchUri(); [[nodiscard]] static auto RemoteSession(); [[nodiscard]] static auto SpatialEntity(); }; struct __declspec(empty_bases) RemoteSystem : Windows::System::RemoteSystems::IRemoteSystem, impl::require<RemoteSystem, Windows::System::RemoteSystems::IRemoteSystem2, Windows::System::RemoteSystems::IRemoteSystem3, Windows::System::RemoteSystems::IRemoteSystem4, Windows::System::RemoteSystems::IRemoteSystem5, Windows::System::RemoteSystems::IRemoteSystem6> { RemoteSystem(std::nullptr_t) noexcept {} RemoteSystem(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystem(ptr, take_ownership_from_abi) {} static auto FindByHostNameAsync(Windows::Networking::HostName const& hostName); static auto CreateWatcher(); static auto CreateWatcher(param::iterable<Windows::System::RemoteSystems::IRemoteSystemFilter> const& filters); static auto RequestAccessAsync(); static auto IsAuthorizationKindEnabled(Windows::System::RemoteSystems::RemoteSystemAuthorizationKind const& kind); static auto CreateWatcherForUser(Windows::System::User const& user); static auto CreateWatcherForUser(Windows::System::User const& user, param::iterable<Windows::System::RemoteSystems::IRemoteSystemFilter> const& filters); }; struct __declspec(empty_bases) RemoteSystemAddedEventArgs : Windows::System::RemoteSystems::IRemoteSystemAddedEventArgs { RemoteSystemAddedEventArgs(std::nullptr_t) noexcept {} RemoteSystemAddedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemAddedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemApp : Windows::System::RemoteSystems::IRemoteSystemApp, impl::require<RemoteSystemApp, Windows::System::RemoteSystems::IRemoteSystemApp2> { RemoteSystemApp(std::nullptr_t) noexcept {} RemoteSystemApp(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemApp(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemAppRegistration : Windows::System::RemoteSystems::IRemoteSystemAppRegistration { RemoteSystemAppRegistration(std::nullptr_t) noexcept {} RemoteSystemAppRegistration(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemAppRegistration(ptr, take_ownership_from_abi) {} static auto GetDefault(); static auto GetForUser(Windows::System::User const& user); }; struct __declspec(empty_bases) RemoteSystemAuthorizationKindFilter : Windows::System::RemoteSystems::IRemoteSystemAuthorizationKindFilter, impl::require<RemoteSystemAuthorizationKindFilter, Windows::System::RemoteSystems::IRemoteSystemFilter> { RemoteSystemAuthorizationKindFilter(std::nullptr_t) noexcept {} RemoteSystemAuthorizationKindFilter(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemAuthorizationKindFilter(ptr, take_ownership_from_abi) {} explicit RemoteSystemAuthorizationKindFilter(Windows::System::RemoteSystems::RemoteSystemAuthorizationKind const& remoteSystemAuthorizationKind); }; struct __declspec(empty_bases) RemoteSystemConnectionInfo : Windows::System::RemoteSystems::IRemoteSystemConnectionInfo { RemoteSystemConnectionInfo(std::nullptr_t) noexcept {} RemoteSystemConnectionInfo(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemConnectionInfo(ptr, take_ownership_from_abi) {} static auto TryCreateFromAppServiceConnection(Windows::ApplicationModel::AppService::AppServiceConnection const& connection); }; struct __declspec(empty_bases) RemoteSystemConnectionRequest : Windows::System::RemoteSystems::IRemoteSystemConnectionRequest, impl::require<RemoteSystemConnectionRequest, Windows::System::RemoteSystems::IRemoteSystemConnectionRequest2, Windows::System::RemoteSystems::IRemoteSystemConnectionRequest3> { RemoteSystemConnectionRequest(std::nullptr_t) noexcept {} RemoteSystemConnectionRequest(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemConnectionRequest(ptr, take_ownership_from_abi) {} explicit RemoteSystemConnectionRequest(Windows::System::RemoteSystems::RemoteSystem const& remoteSystem); static auto CreateForApp(Windows::System::RemoteSystems::RemoteSystemApp const& remoteSystemApp); static auto CreateFromConnectionToken(param::hstring const& connectionToken); static auto CreateFromConnectionTokenForUser(Windows::System::User const& user, param::hstring const& connectionToken); }; struct __declspec(empty_bases) RemoteSystemDiscoveryTypeFilter : Windows::System::RemoteSystems::IRemoteSystemDiscoveryTypeFilter, impl::require<RemoteSystemDiscoveryTypeFilter, Windows::System::RemoteSystems::IRemoteSystemFilter> { RemoteSystemDiscoveryTypeFilter(std::nullptr_t) noexcept {} RemoteSystemDiscoveryTypeFilter(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemDiscoveryTypeFilter(ptr, take_ownership_from_abi) {} explicit RemoteSystemDiscoveryTypeFilter(Windows::System::RemoteSystems::RemoteSystemDiscoveryType const& discoveryType); }; struct __declspec(empty_bases) RemoteSystemEnumerationCompletedEventArgs : Windows::System::RemoteSystems::IRemoteSystemEnumerationCompletedEventArgs { RemoteSystemEnumerationCompletedEventArgs(std::nullptr_t) noexcept {} RemoteSystemEnumerationCompletedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemEnumerationCompletedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemKindFilter : Windows::System::RemoteSystems::IRemoteSystemKindFilter, impl::require<RemoteSystemKindFilter, Windows::System::RemoteSystems::IRemoteSystemFilter> { RemoteSystemKindFilter(std::nullptr_t) noexcept {} RemoteSystemKindFilter(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemKindFilter(ptr, take_ownership_from_abi) {} explicit RemoteSystemKindFilter(param::iterable<hstring> const& remoteSystemKinds); }; struct RemoteSystemKinds { RemoteSystemKinds() = delete; [[nodiscard]] static auto Phone(); [[nodiscard]] static auto Hub(); [[nodiscard]] static auto Holographic(); [[nodiscard]] static auto Desktop(); [[nodiscard]] static auto Xbox(); [[nodiscard]] static auto Iot(); [[nodiscard]] static auto Tablet(); [[nodiscard]] static auto Laptop(); }; struct __declspec(empty_bases) RemoteSystemRemovedEventArgs : Windows::System::RemoteSystems::IRemoteSystemRemovedEventArgs { RemoteSystemRemovedEventArgs(std::nullptr_t) noexcept {} RemoteSystemRemovedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemRemovedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSession : Windows::System::RemoteSystems::IRemoteSystemSession, impl::require<RemoteSystemSession, Windows::Foundation::IClosable> { RemoteSystemSession(std::nullptr_t) noexcept {} RemoteSystemSession(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSession(ptr, take_ownership_from_abi) {} static auto CreateWatcher(); }; struct __declspec(empty_bases) RemoteSystemSessionAddedEventArgs : Windows::System::RemoteSystems::IRemoteSystemSessionAddedEventArgs { RemoteSystemSessionAddedEventArgs(std::nullptr_t) noexcept {} RemoteSystemSessionAddedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionAddedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionController : Windows::System::RemoteSystems::IRemoteSystemSessionController { RemoteSystemSessionController(std::nullptr_t) noexcept {} RemoteSystemSessionController(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionController(ptr, take_ownership_from_abi) {} explicit RemoteSystemSessionController(param::hstring const& displayName); RemoteSystemSessionController(param::hstring const& displayName, Windows::System::RemoteSystems::RemoteSystemSessionOptions const& options); }; struct __declspec(empty_bases) RemoteSystemSessionCreationResult : Windows::System::RemoteSystems::IRemoteSystemSessionCreationResult { RemoteSystemSessionCreationResult(std::nullptr_t) noexcept {} RemoteSystemSessionCreationResult(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionCreationResult(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionDisconnectedEventArgs : Windows::System::RemoteSystems::IRemoteSystemSessionDisconnectedEventArgs { RemoteSystemSessionDisconnectedEventArgs(std::nullptr_t) noexcept {} RemoteSystemSessionDisconnectedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionDisconnectedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionInfo : Windows::System::RemoteSystems::IRemoteSystemSessionInfo { RemoteSystemSessionInfo(std::nullptr_t) noexcept {} RemoteSystemSessionInfo(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionInfo(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionInvitation : Windows::System::RemoteSystems::IRemoteSystemSessionInvitation { RemoteSystemSessionInvitation(std::nullptr_t) noexcept {} RemoteSystemSessionInvitation(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionInvitation(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionInvitationListener : Windows::System::RemoteSystems::IRemoteSystemSessionInvitationListener { RemoteSystemSessionInvitationListener(std::nullptr_t) noexcept {} RemoteSystemSessionInvitationListener(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionInvitationListener(ptr, take_ownership_from_abi) {} RemoteSystemSessionInvitationListener(); }; struct __declspec(empty_bases) RemoteSystemSessionInvitationReceivedEventArgs : Windows::System::RemoteSystems::IRemoteSystemSessionInvitationReceivedEventArgs { RemoteSystemSessionInvitationReceivedEventArgs(std::nullptr_t) noexcept {} RemoteSystemSessionInvitationReceivedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionInvitationReceivedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionJoinRequest : Windows::System::RemoteSystems::IRemoteSystemSessionJoinRequest { RemoteSystemSessionJoinRequest(std::nullptr_t) noexcept {} RemoteSystemSessionJoinRequest(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionJoinRequest(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionJoinRequestedEventArgs : Windows::System::RemoteSystems::IRemoteSystemSessionJoinRequestedEventArgs { RemoteSystemSessionJoinRequestedEventArgs(std::nullptr_t) noexcept {} RemoteSystemSessionJoinRequestedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionJoinRequestedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionJoinResult : Windows::System::RemoteSystems::IRemoteSystemSessionJoinResult { RemoteSystemSessionJoinResult(std::nullptr_t) noexcept {} RemoteSystemSessionJoinResult(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionJoinResult(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionMessageChannel : Windows::System::RemoteSystems::IRemoteSystemSessionMessageChannel { RemoteSystemSessionMessageChannel(std::nullptr_t) noexcept {} RemoteSystemSessionMessageChannel(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionMessageChannel(ptr, take_ownership_from_abi) {} RemoteSystemSessionMessageChannel(Windows::System::RemoteSystems::RemoteSystemSession const& session, param::hstring const& channelName); RemoteSystemSessionMessageChannel(Windows::System::RemoteSystems::RemoteSystemSession const& session, param::hstring const& channelName, Windows::System::RemoteSystems::RemoteSystemSessionMessageChannelReliability const& reliability); }; struct __declspec(empty_bases) RemoteSystemSessionOptions : Windows::System::RemoteSystems::IRemoteSystemSessionOptions { RemoteSystemSessionOptions(std::nullptr_t) noexcept {} RemoteSystemSessionOptions(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionOptions(ptr, take_ownership_from_abi) {} RemoteSystemSessionOptions(); }; struct __declspec(empty_bases) RemoteSystemSessionParticipant : Windows::System::RemoteSystems::IRemoteSystemSessionParticipant { RemoteSystemSessionParticipant(std::nullptr_t) noexcept {} RemoteSystemSessionParticipant(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionParticipant(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionParticipantAddedEventArgs : Windows::System::RemoteSystems::IRemoteSystemSessionParticipantAddedEventArgs { RemoteSystemSessionParticipantAddedEventArgs(std::nullptr_t) noexcept {} RemoteSystemSessionParticipantAddedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionParticipantAddedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionParticipantRemovedEventArgs : Windows::System::RemoteSystems::IRemoteSystemSessionParticipantRemovedEventArgs { RemoteSystemSessionParticipantRemovedEventArgs(std::nullptr_t) noexcept {} RemoteSystemSessionParticipantRemovedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionParticipantRemovedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionParticipantWatcher : Windows::System::RemoteSystems::IRemoteSystemSessionParticipantWatcher { RemoteSystemSessionParticipantWatcher(std::nullptr_t) noexcept {} RemoteSystemSessionParticipantWatcher(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionParticipantWatcher(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionRemovedEventArgs : Windows::System::RemoteSystems::IRemoteSystemSessionRemovedEventArgs { RemoteSystemSessionRemovedEventArgs(std::nullptr_t) noexcept {} RemoteSystemSessionRemovedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionRemovedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionUpdatedEventArgs : Windows::System::RemoteSystems::IRemoteSystemSessionUpdatedEventArgs { RemoteSystemSessionUpdatedEventArgs(std::nullptr_t) noexcept {} RemoteSystemSessionUpdatedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionUpdatedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionValueSetReceivedEventArgs : Windows::System::RemoteSystems::IRemoteSystemSessionValueSetReceivedEventArgs { RemoteSystemSessionValueSetReceivedEventArgs(std::nullptr_t) noexcept {} RemoteSystemSessionValueSetReceivedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionValueSetReceivedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemSessionWatcher : Windows::System::RemoteSystems::IRemoteSystemSessionWatcher { RemoteSystemSessionWatcher(std::nullptr_t) noexcept {} RemoteSystemSessionWatcher(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemSessionWatcher(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemStatusTypeFilter : Windows::System::RemoteSystems::IRemoteSystemStatusTypeFilter, impl::require<RemoteSystemStatusTypeFilter, Windows::System::RemoteSystems::IRemoteSystemFilter> { RemoteSystemStatusTypeFilter(std::nullptr_t) noexcept {} RemoteSystemStatusTypeFilter(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemStatusTypeFilter(ptr, take_ownership_from_abi) {} explicit RemoteSystemStatusTypeFilter(Windows::System::RemoteSystems::RemoteSystemStatusType const& remoteSystemStatusType); }; struct __declspec(empty_bases) RemoteSystemUpdatedEventArgs : Windows::System::RemoteSystems::IRemoteSystemUpdatedEventArgs { RemoteSystemUpdatedEventArgs(std::nullptr_t) noexcept {} RemoteSystemUpdatedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemUpdatedEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemWatcher : Windows::System::RemoteSystems::IRemoteSystemWatcher, impl::require<RemoteSystemWatcher, Windows::System::RemoteSystems::IRemoteSystemWatcher2, Windows::System::RemoteSystems::IRemoteSystemWatcher3> { RemoteSystemWatcher(std::nullptr_t) noexcept {} RemoteSystemWatcher(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemWatcher(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemWatcherErrorOccurredEventArgs : Windows::System::RemoteSystems::IRemoteSystemWatcherErrorOccurredEventArgs { RemoteSystemWatcherErrorOccurredEventArgs(std::nullptr_t) noexcept {} RemoteSystemWatcherErrorOccurredEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemWatcherErrorOccurredEventArgs(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) RemoteSystemWebAccountFilter : Windows::System::RemoteSystems::IRemoteSystemWebAccountFilter, impl::require<RemoteSystemWebAccountFilter, Windows::System::RemoteSystems::IRemoteSystemFilter> { RemoteSystemWebAccountFilter(std::nullptr_t) noexcept {} RemoteSystemWebAccountFilter(void* ptr, take_ownership_from_abi_t) noexcept : Windows::System::RemoteSystems::IRemoteSystemWebAccountFilter(ptr, take_ownership_from_abi) {} explicit RemoteSystemWebAccountFilter(Windows::Security::Credentials::WebAccount const& account); }; } #endif
[ "49797644+awrznc@users.noreply.github.com" ]
49797644+awrznc@users.noreply.github.com
51ceacb263f610ea7cc8c5d2c1b35a206972f458
8c0ce81f046fcf0e8fd5bc8971458b6b5303ac8e
/src/Application/Tabs/7_ImportData/parseborsdata.h
8976855210275e25d2b7e098fc0543f6a3ed4618
[]
no_license
ralex1975/jackStock
87b71544b49e0cfe5631c8b1633655d6dfce0f8e
2feee13cb8fbdb28bf01105a3a74b4c9551605a7
refs/heads/master
2022-04-11T08:03:13.166782
2019-12-22T13:58:21
2019-12-22T13:58:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,461
h
#ifndef PARSEBORSDATA_H #define PARSEBORSDATA_H #include <QString> class ParseBorsData { enum MainStateET { MSTATE_YEAR, MSTATE_SOLIDITY, MSTATE_REVENUE_PER_SHARE, MSTATE_EQUITY_PER_SHARE, MSTATE_EARNINGS_PER_SHARE, MSTATE_DIVIDEND }; struct StockDataST { QString stockSymbol; QString stockName; QString htmlFilename; }; struct StockParseDataST { QString year; QString solidity; QString revenuePerShare; QString equityPerShare; QString earningPerShare; QString dividend; }; #define PARSE_DATA_ARR_SIZE 100 StockParseDataST m_parseDataArr[PARSE_DATA_ARR_SIZE]; int m_nofParseArrData; MainStateET m_mainState; public: ParseBorsData(); bool helpParser(QString &result, QRegExp rx, MainStateET mainState, QString dbgStr, StockParseDataST *parseDataArr, int &nofParseArrData); bool cleanupParsedProcentValue(QString &value, QString str); bool cleanupParsedRealValue(QString &value, QString str); bool addRevenuePerShare(StockParseDataST *parseDataArr, int nofParseArrData, QString stockSymbol, QString stockName); bool addDividendPerShare(StockParseDataST *parseDataArr, int nofParseArrData, QString stockSymbol, QString stockName); bool addEarningsPerShare(StockParseDataST *parseDataArr, int nofParseArrData, QString stockSymbol, QString stockName); bool addSolidityPerShare(StockParseDataST *parseDataArr, int nofParseArrData, QString stockSymbol, QString stockName); bool addEquityPerShare(StockParseDataST *parseDataArr, int nofParseArrData, QString stockSymbol, QString stockName); bool readStockSymbolsFile(QString filename); bool readParseHtmlFile(QString filename, StockParseDataST *parseDataArr, int &nofParseArrData); }; #endif // PARSEBORSDATA_H
[ "ajn@bredband.net" ]
ajn@bredband.net
5f8ef5d61a222a51fd010f6800304b2791c08f2d
5008922e0ac56b95adf31062a365366733ea7458
/TestLOBPCG.cpp
fe13fcaad5f100c836ef9fc26f63e4d640025079
[]
no_license
FedericaCutroneo/ModalAnalysis
df60d8cc87a8a40c95051dd5f206c57a2529a681
fca8331889242d36131d0fb831eaf4f37e7ffefd
refs/heads/master
2022-11-12T19:01:15.625936
2020-07-04T17:44:14
2020-07-04T17:44:14
277,155,871
0
0
null
null
null
null
UTF-8
C++
false
false
1,898
cpp
#include <iostream> #include <Spectra/contrib/LOBPCGSolver.h> typedef Eigen::Matrix<long double, Eigen::Dynamic, Eigen::Dynamic> Matrix; typedef Eigen::Matrix<long double, Eigen::Dynamic, 1> Vector; typedef std::complex<long double> Complex; typedef Eigen::Matrix<Complex, Eigen::Dynamic, Eigen::Dynamic> ComplexMatrix; typedef Eigen::Matrix<Complex, Eigen::Dynamic, 1> ComplexVector; typedef Eigen::SparseMatrix<long double> SparseMatrix; typedef Eigen::SparseMatrix<Complex> SparseComplexMatrix; int example() { // generate random sparse A Matrix a; a = (Matrix::Random(10, 10).array() > 0.6).cast<long double>() * Matrix::Random(10, 10).array() * 5; a = Matrix((a).triangularView<Eigen::Lower>()) + Matrix((a).triangularView<Eigen::Lower>()).transpose(); for (int i = 0; i < 10; i++) a(i, i) = i + 0.5; std::cout << a << "\n"; Eigen::SparseMatrix<long double> A(a.sparseView()); // random X Eigen::Matrix<long double, 10, 2> x; x = Matrix::Random(10, 2).array(); Eigen::SparseMatrix<long double> X(x.sparseView()); // solve Ax = lambda*x Spectra::LOBPCGSolver<long double> solver(A, X); solver.compute(10, 1e-4); // 10 iterations, L2_tolerance = 1e-4*N std::cout << "info\n" << solver.info() << std::endl; std::cout << "eigenvalues\n" << solver.eigenvalues() << std::endl; std::cout << "eigenvectors\n" << solver.eigenvectors() << std::endl; std::cout << "residuals\n" << solver.residuals() << std::endl; return 0; } int main() { SparseMatrix matK(3, 3); // default is column major matK.reserve(9); matK.insert(0, 0) = 7.14; // alternative: mat.coeffRef(i,j) += v_ij; matK.insert(0, 1) = -5.36; matK.insert(0, 2) = 1.79; matK.insert(1, 0) = -5.36; matK.insert(1, 1) = 5.58; matK.insert(1, 2) = -2.21; matK.insert(2, 0) = 1.79; matK.insert(2, 1) = -2.21; matK.insert(2, 2) = 0.96; matK.makeCompressed(); std::cout << matK; }
[ "federica.cutroneo@studenti.unipr.it" ]
federica.cutroneo@studenti.unipr.it
ed305cf60719317c2b92b2ef5cc6165b1303345f
d2871878756ce2b4dbcfc538bcc0ba7a5900c769
/OOP/class/09pointer2class.cpp
533048f837ce8f0370ceef5ef6edfb0d94c35e47
[]
no_license
Ziaeemehr/cpp_workshop
75934095eb057d0643d0b59db3712e83fba053d6
5752356aa7aa571c107f2fa042332ebb04ad37f1
refs/heads/master
2022-01-18T18:51:29.398280
2022-01-03T14:10:35
2022-01-03T14:10:35
170,557,736
5
0
null
null
null
null
UTF-8
C++
false
false
854
cpp
#include<iostream> using namespace std; class Box{ public: Box(double l = 2.0, double b=2.0, double h=2.0){ cout << "constructor called." << endl; length = l; breadth = b; height = h; } double Volume(){ return length*breadth*height; } private: double length; double breadth; double height; }; int main(void){ Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 Box *ptrBox; ptrBox = &Box1; // Now try to access a member using member access operator cout << "Volume of Box1: " << ptrBox->Volume() << endl; // Save the address of second object ptrBox = &Box2; // Now try to access a member using member access operator cout << "Volume of Box2: " << ptrBox->Volume() << endl; return 0; }
[ "a.ziaeemehr@gmail.com" ]
a.ziaeemehr@gmail.com
26f6d7295f455de6ec03caf62826bbeb62b3c363
61cb74457fc169ddac829fe7d94572747c503d13
/Practices/Geometric/LineIntersect.cpp
a45db7b53d4db95335fe698d4e1e09e5eeb99510
[]
no_license
zhenglu0/Programming_Practice
e7e3e0d8c65c824abb043b308f00a2b40aaddc06
359469bffa4978ffc72be1eff3d96788ca0f0a8c
refs/heads/master
2021-06-16T06:42:34.227254
2017-05-13T15:08:05
2017-05-13T15:08:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,762
cpp
// // LineIntersect.cpp // // Modified by 罗铮 on 03/13/14. // http://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/ // Or we can calculate the given point should be on the both side // of the given line by using the ax+by >=< 0 // // A C++ program to check if two given line segments intersect #include <iostream> using namespace std; struct Point { int x; int y; }; // Given three colinear points p, q, r, the function checks if // point q lies on line segment 'pr' bool onSegment(Point p, Point q, Point r) { if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) return true; return false; } // To find orientation of ordered triplet (p, q, r). // The function returns following values // 0 --> p, q and r are colinear // 1 --> Clockwise // 2 --> Counterclockwise int orientation(Point p, Point q, Point r) { // See 10th slides from following link for derivation of the formula // http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // colinear return (val > 0)? 1: 2; // clock or counterclock wise } // The main function that returns true if line segment 'p1q1' // and 'p2q2' intersect. bool doIntersect(Point p1, Point q1, Point p2, Point q2) { // Find the four orientations needed for general and // special cases int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases } // Driver program to test above functions int main() { struct Point p1 = {1, 1}, q1 = {10, 1}; struct Point p2 = {1, 2}, q2 = {10, 2}; doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n"; p1 = {10, 0}, q1 = {0, 10}; p2 = {0, 0}, q2 = {10, 10}; doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n"; p1 = {-5, -5}, q1 = {0, 0}; p2 = {1, 1}, q2 = {10, 10}; doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n"; return 0; }
[ "luozheng03@gmail.com" ]
luozheng03@gmail.com
82b97007ca7b344ec6b233204098fc08d22a1ee8
cfdb6838655b75e7cb7316bdd736408485bf6319
/trpg/Ennemis.h
4882db5432801ef4a50a71ef74d8357a5da8e06c
[]
no_license
kahn-aar/trpg
0fee9b8c25f95997f435736a7106e59e46d0b540
4d686e4430903952c169746d917bd4f51621beed
refs/heads/master
2020-04-13T17:00:12.382278
2013-09-29T20:06:15
2013-09-29T20:06:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
759
h
#ifndef ENNEMIS_H_INCLUDED #define ENNEMIS_H_INCLUDED #include "Personnage.h" namespace TRPG { class Ennemis : public Combattant { protected: int xp; int grade; public: Ennemis(const std::string& name, int lvl, int vie, int att, int def, int vit, int x, int grad) : Combattant(name, lvl, vie, att, def, vit), xp(x), grade(grad){} int getXp() const {return xp;} int getGrade() const {return grade;} void setXp(int x) {xp = x;} void setGrade(int g) {grade = g;} virtual std::string getClass() const=0; }; class Empereur : public Ennemis { private: public: Empereur(const std::string& name, int lvl=1); std::string getClass() const {return "Empereur";} void lvlUp(); void affiche() const; }; } #endif // ENNEMIS_H_INCLUDED
[ "nicolas.martinr@gmail.com" ]
nicolas.martinr@gmail.com
947e1a167b99753ec26a90d91ee70f17c40efef3
95d81d0143275d51577ff6493afd80db392475a3
/ch9/9.2.cpp
9863fd29a79fd9c74941ad53057054fc4cc50e87
[ "Apache-2.0" ]
permissive
CSLP/Cpp-Primer-5th-Exercises
aa5bb0bc0c8ff4326bf08f60d97dd0e407dc895a
29ea2e3f4bd32674eb518f431bb1b10aecfaa216
refs/heads/master
2020-04-29T04:26:54.668388
2020-01-16T07:19:27
2020-01-16T07:19:27
175,847,389
0
0
Apache-2.0
2019-03-15T15:37:29
2019-03-15T15:37:28
null
UTF-8
C++
false
false
96
cpp
#include <list> #include <deque> int main() { std::list<std::deque<int>> ldi; return 0; }
[ "jaege@163.com" ]
jaege@163.com
eeb96139a0cbfdcc06739fe0f0494e4d907a7bc8
5cfe1c0e2f16e585ec4dd5391fb7ba4da725a5a1
/UVa11426_GCDExtreme(II).cpp
3c908250511227ed3f1124c50b7d62d5ee8b5a12
[]
no_license
nhatnguyendrgs/UVa-OnlineJudge
dcec2d0941cacc8dfe81db871e2641ffff00cbc2
33d172a0296eed85a1b0011cdbda1c5942d75973
refs/heads/master
2020-04-11T23:50:24.963107
2015-08-29T08:50:48
2015-08-29T08:50:48
41,350,568
0
2
null
null
null
null
UTF-8
C++
false
false
1,287
cpp
/* UVa 11426 - GCD - Extreme (II) * https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=2421 */ //nhatnguyendrgs (c) 2015 #include "iostream" #include "stdio.h" #include "stdlib.h" #include "string" #include "string.h" #include "algorithm" #include "math.h" #include "vector" #include "map" #include "queue" #include "stack" #include "deque" #include "set" using namespace std; const int MaxN = 4000000; int Div[MaxN+4],p,Exp; long long result[MaxN+4],F[MaxN+4],aux,Pow; void solve(){ memset(Div,-1,sizeof(Div)); for(int i = 2;i<=4000000;++i){ if(Div[i]==-1){ Div[i] = i; if(i<=2000) for(int j = i*i;j<=4000000;j += i) Div[j] = i; } } memset(F,-1,sizeof(F)); result[1] = 0; F[1] = 1; for(int i = 2;i<=4000000;++i){ p = Div[i]; Exp = 0; aux = i; Pow = 1; while(aux%p==0){ Pow *= p; ++Exp; aux /= p; } F[i] = ((Exp+1)*Pow-Exp*(Pow/p))*F[aux]; result[i] = result[i-1]+F[i]-i; } } int N; int main(){ solve(); while(scanf("%d",&N)!=EOF){ if(N==0) break; else printf("%lld\n",result[N]); } return 0; }
[ "nhatnguyendrgs@gmail.com" ]
nhatnguyendrgs@gmail.com
5028c68d8c9c0ad70a37631955c89e13adfe5b93
46b1fa8fe679dec71c66ec4587d3048bcbdc23e3
/include/xflens/cxxblas/level2extensions/her.h
f4f1af2ffb74c898a7386dbc7cc9f89bda044bac
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
potpath/xtensor-blas
dccfcc10a184806778e21a538ec2f083bc76bfad
5d2cb7d4d2162a4e0c0c787ef88299663c9ef71a
refs/heads/master
2020-04-07T00:50:09.897253
2018-11-16T16:39:39
2018-11-16T16:39:39
157,920,622
1
0
BSD-3-Clause
2018-11-16T20:59:32
2018-11-16T20:59:32
null
UTF-8
C++
false
false
2,120
h
/* * Copyright (c) 2009, Michael Lehn * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3) Neither the name of the FLENS development group nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CXXBLAS_LEVEL2EXTENSIONS_HER_H #define CXXBLAS_LEVEL2EXTENSIONS_HER_H 1 #include "xflens/cxxblas/typedefs.h" namespace cxxblas { template <typename IndexType, typename ALPHA, typename VX, typename MA> void her(StorageOrder order, StorageUpLo upLo, Transpose conjugateA, IndexType n, const ALPHA &alpha, const VX *x, IndexType incX, MA *A, IndexType ldA); } // namespace cxxblas #endif // CXXBLAS_LEVEL2EXTENSIONS_HER_H
[ "w.vollprecht@gmail.com" ]
w.vollprecht@gmail.com
25f7c71c03745abebbc584ebce8ffd4514934217
3f0a83c7864b837894fbe38db81e786f5a1f1bbd
/src/containers/BitSet.hpp
2bfdf99224f1c4462e69b7279804610dd4e3819f
[]
no_license
abhishekudupa/aurum
7380a8bf3807163843ca51a6a6aa89412c2cbc54
f691dd9f86c726d551844880ecbdbf7839f2a8e6
refs/heads/master
2020-04-09T09:53:57.136516
2019-05-02T00:57:31
2019-05-02T00:57:31
50,958,465
0
0
null
null
null
null
UTF-8
C++
false
false
4,058
hpp
// BitSet.hpp --- // Filename: BitSet.hpp // Author: Abhishek Udupa // Created: Mon Feb 16 02:10:18 2015 (-0500) // // Copyright (c) 2013, Abhishek Udupa, University of Pennsylvania // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by The University of Pennsylvania // 4. Neither the name of the University of Pennsylvania nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''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 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. // // // Code: #if !defined AURUM_CONTAINERS_BIT_SET_HPP_ #define AURUM_CONTAINERS_BIT_SET_HPP_ #include "../basetypes/AurumTypes.hpp" #include "../basetypes/Stringifiable.hpp" namespace aurum { namespace containers { class BitSet final : public AurumObject<BitSet>, public Stringifiable<BitSet> { private: u64 m_num_bits; u08* m_bit_array; inline i32 compare(const BitSet& other) const; public: class BitRef { private: BitSet* m_bit_set; u64 m_bit_num; public: BitRef(BitSet* bit_set, u64 bit_num); BitRef(const BitRef& other); ~BitRef(); BitRef& operator = (const BitRef& other); BitRef& operator = (bool value); bool operator == (const BitRef& other) const; bool operator != (const BitRef& other) const; bool operator == (bool value) const; bool operator != (bool value) const; operator bool () const; bool operator ! () const; }; BitSet(); BitSet(u64 size); BitSet(u64 size, bool initial_value); BitSet(const BitSet& other); BitSet(BitSet&& other); ~BitSet(); BitSet& operator = (const BitSet& other); BitSet& operator = (BitSet&& other); bool operator == (const BitSet& other) const; bool operator < (const BitSet& other) const; bool operator > (const BitSet& other) const; bool operator <= (const BitSet& other) const; bool operator >= (const BitSet& other) const; bool operator != (const BitSet& other) const; void set(u64 bit_num); bool test(u64 bit_num) const; void clear(u64 bit_num); // returns the value of bit before flip bool flip(u64 bit_num); // Gang set, clear and flip void set(); void clear(); void flip(); // resets to a zero size bit set void reset(); bool operator [] (u64 bit_num) const; BitRef operator [] (u64 bit_num); u64 size() const; void resize_and_clear(u64 new_num_bits); std::string as_string(i64 verbosity) const; }; } /* end namespace containers */ } /* end namespace aurum */ #endif /* AURUM_CONTAINERS_BIT_SET_HPP_ */ // // BitSet.hpp ends here
[ "audupa@seas.upenn.edu" ]
audupa@seas.upenn.edu
5c8355716a95c0d117946946cebd9da8187abc50
7cce7d352e68ab56f1e9aa4b9bab1f21b05937bd
/src/Rules/RookMoveRequester.cc
2931ba8956aaa45a346c39885347fc34f1521d1a
[ "MIT" ]
permissive
rodrigowerberich/simple-terminal-chess
2db79f0a0fb7127570827f14c94298f302d63dfd
73c62251c4d130a896270c1e27b297da3ab0933f
refs/heads/master
2022-11-06T00:56:50.561470
2020-06-23T10:08:39
2020-06-23T10:08:39
259,643,057
0
0
null
null
null
null
UTF-8
C++
false
false
3,159
cc
#include "Rules/MoveRequester.hh" #include "Rules/RookMoveRequester.hh" #include "Rules/PieceMoverAux.hh" #include "Board/Definitions.hh" #include <iostream> namespace Chess{ namespace Rules{ namespace RookMoveRequester{ std::vector<Chess::Board::Position> rookPath(const Chess::Board::Position& initialPosition, const Chess::Board::Position& finalPosition){ std::vector<Chess::Board::Position> path; if(!initialPosition.isValid() || !finalPosition.isValid()){ return path; } // Normal rook movement is only in the same column if(initialPosition.column() == finalPosition.column()){ auto initialRow = initialPosition.row(); auto finalRow = finalPosition.row(); auto smallToBig = initialRow < finalRow; auto distance = std::abs(finalRow - initialRow); for(auto index = 0; index <= distance; index++ ){ auto row = initialRow + index*(smallToBig?1:-1); path.push_back({initialPosition.column(), row}); } }else if(initialPosition.row() == finalPosition.row()){ auto initialPositionNumber = PieceMoverAux::InternalPosition(initialPosition); auto finalPositionNumber = PieceMoverAux::InternalPosition(finalPosition); auto initialColumn = initialPositionNumber.column(); auto finalColumn = finalPositionNumber.column(); auto smallToBig = initialColumn < finalColumn; auto distance = std::abs(finalColumn - initialColumn); for(auto index = 0; index <= distance; index++ ){ auto column = initialColumn + index*(smallToBig?1:-1); path.push_back({PieceMoverAux::columnFromNumber(column), initialPosition.row()}); } } return path; } } template <> MoveProposalAnalysis MoveRequester::verifyMove<Chess::Board::PieceType::Rook>(const BoardType& originalBoard, const BoardType& newBoard, const PieceDescriptionType& pieceDescription, const MoveResultType& moveResult){ auto originalPosition = originalBoard.getPiecePosition(pieceDescription); auto finalPosition = newBoard.getPiecePosition(pieceDescription); if(moveResult.status() == Chess::Board::MoveResult::Status::Collision){ finalPosition = moveResult.info<Chess::Board::MoveResult::Info::Collision>().position; } // Rook path only returns horizontal or vertical paths. auto path = RookMoveRequester::rookPath(originalPosition, finalPosition); auto pathSize = static_cast<int>(path.size()); if(pathSize > 1){ for(int pathIndex = 1; pathIndex < pathSize-1; pathIndex++){ auto possibilityOfCollisionPosition = path[pathIndex]; auto possiblePieceDescription = originalBoard.getPieceAtPosition(possibilityOfCollisionPosition); if(possiblePieceDescription.isValid()){ return {originalBoard, Rules::MovementInterrupted{originalPosition, possibilityOfCollisionPosition, finalPosition, pieceDescription, possiblePieceDescription}}; } } return {newBoard, moveResult}; } return {originalBoard, Rules::InvalidPieceMovement{originalPosition, finalPosition, pieceDescription}}; } } }
[ "rodrigowerberich@hotmail.com" ]
rodrigowerberich@hotmail.com
44a33543c5e49f55367a035c024f4ec5024431b9
038cafb60fb6f157118724d5f3d13ecb26f9a64b
/SimpleRead4_openGL/geometry/vxobj.cpp
5bcb2074c4a0cbb68773fc7514ef55bfa120052b
[]
no_license
t-doi/OpenNI2-test
0996d28c870522f943459d43bad15dc88a67e2b6
13ab7ce8a3ce6bd892d3aa7618b83b093643ba91
refs/heads/master
2020-04-06T10:04:47.559650
2017-07-01T04:57:46
2017-07-01T04:57:46
37,178,342
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,432
cpp
//--------------------------------------------------------------------------- //vxobj.cpp,h //ボクセルによって物体の表面データの入出力,重心算出 //を行うクラスVXObj //voxelの派生クラス #include "vxobj.h" //--------------------------------------------------------------------------- void VXObj::clear(void) { int i; for(i=0;i<(mesh_x*mesh_y*mesh_z);i++) { flag[i]=0; } } //--------------------------------------------------------------------------- char VXObj::input(double x_in,double y_in,double z_in) { //データ入力 int i,j,k; i=xtoi(x_in); j=ytoj(y_in); k=ztok(z_in); if(!check(i,j,k))return 0; flag[index(i,j,k)]=1; return 1; } //--------------------------------------------------------------------------- char VXObj::calc_cog(double *x_out,double *y_out,double *z_out) { int i,j,k; double cog_x_sum=0;//データの総和 double cog_y_sum=0; double cog_z_sum=0; int data_num=0;//データの個数 for(k=0;k<mesh_z;k++) { for(j=0;j<mesh_y;j++) { for(i=0;i<mesh_x;i++) { if(flag[index(i,j,k)]!=0) { cog_x_sum+=itox(i); cog_y_sum+=jtoy(j); cog_z_sum+=ktoz(k); data_num++; } } } } if(data_num==0)return 0; *x_out=cog_x_sum/data_num; *y_out=cog_y_sum/data_num; *z_out=cog_z_sum/data_num; return 1; } //---------------------------------------------------------------------------
[ "doi@neptune.kanazawa-it.ac.jp" ]
doi@neptune.kanazawa-it.ac.jp
fb1c6e5f56c68e22586903660a35c4c3259726cf
e4f85676da4b6a7d8eaa56e7ae8910e24b28b509
/components/viz/service/gl/gpu_service_impl.cc
2f2da0a43f5000a7d6f91419a2a13fa0476f2896
[ "BSD-3-Clause" ]
permissive
RyoKodama/chromium
ba2b97b20d570b56d5db13fbbfb2003a6490af1f
c421c04308c0c642d3d1568b87e9b4cd38d3ca5d
refs/heads/ozone-wayland-dev
2023-01-16T10:47:58.071549
2017-09-27T07:41:58
2017-09-27T07:41:58
105,863,448
0
0
null
2017-10-05T07:55:32
2017-10-05T07:55:32
null
UTF-8
C++
false
false
21,899
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/viz/service/gl/gpu_service_impl.h" #include "base/bind.h" #include "base/command_line.h" #include "base/debug/crash_logging.h" #include "base/lazy_instance.h" #include "base/memory/shared_memory.h" #include "base/run_loop.h" #include "base/task_runner_util.h" #include "base/task_scheduler/post_task.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "components/viz/common/gpu/in_process_context_provider.h" #include "gpu/command_buffer/client/gpu_memory_buffer_manager.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "gpu/command_buffer/service/scheduler.h" #include "gpu/command_buffer/service/sync_point_manager.h" #include "gpu/config/dx_diag_node.h" #include "gpu/config/gpu_info_collector.h" #include "gpu/config/gpu_switches.h" #include "gpu/config/gpu_util.h" #include "gpu/ipc/common/gpu_memory_buffer_support.h" #include "gpu/ipc/common/memory_stats.h" #include "gpu/ipc/gpu_in_process_thread_service.h" #include "gpu/ipc/service/gpu_channel.h" #include "gpu/ipc/service/gpu_channel_manager.h" #include "gpu/ipc/service/gpu_memory_buffer_factory.h" #include "gpu/ipc/service/gpu_watchdog_thread.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_sync_channel.h" #include "ipc/ipc_sync_message_filter.h" #include "media/gpu/gpu_video_encode_accelerator_factory.h" #include "media/gpu/ipc/service/gpu_jpeg_decode_accelerator_factory_provider.h" #include "media/gpu/ipc/service/gpu_video_decode_accelerator.h" #include "media/gpu/ipc/service/gpu_video_encode_accelerator.h" #include "media/gpu/ipc/service/media_gpu_channel_manager.h" #include "media/mojo/services/mojo_video_encode_accelerator_provider.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/gl_switches.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/gl/init/gl_factory.h" #include "url/gurl.h" #if defined(OS_ANDROID) #include "base/android/throw_uncaught_exception.h" #include "media/gpu/android/content_video_view_overlay_allocator.h" #endif namespace viz { namespace { static base::LazyInstance<base::Callback< void(int severity, size_t message_start, const std::string& message)>>:: Leaky g_log_callback = LAZY_INSTANCE_INITIALIZER; bool GpuLogMessageHandler(int severity, const char* file, int line, size_t message_start, const std::string& message) { g_log_callback.Get().Run(severity, message_start, message); return false; } // Returns a callback which does a PostTask to run |callback| on the |runner| // task runner. template <typename Param> base::OnceCallback<void(const Param&)> WrapCallback( scoped_refptr<base::SingleThreadTaskRunner> runner, base::OnceCallback<void(const Param&)> callback) { return base::BindOnce( [](base::SingleThreadTaskRunner* runner, base::OnceCallback<void(const Param&)> callback, const Param& param) { runner->PostTask(FROM_HERE, base::BindOnce(std::move(callback), param)); }, base::RetainedRef(std::move(runner)), std::move(callback)); } void DestroyBinding(mojo::BindingSet<mojom::GpuService>* binding, base::WaitableEvent* wait) { binding->CloseAllBindings(); wait->Signal(); } } // namespace GpuServiceImpl::GpuServiceImpl( const gpu::GPUInfo& gpu_info, std::unique_ptr<gpu::GpuWatchdogThread> watchdog_thread, scoped_refptr<base::SingleThreadTaskRunner> io_runner, const gpu::GpuFeatureInfo& gpu_feature_info) : main_runner_(base::ThreadTaskRunnerHandle::Get()), io_runner_(std::move(io_runner)), watchdog_thread_(std::move(watchdog_thread)), gpu_memory_buffer_factory_( gpu::GpuMemoryBufferFactory::CreateNativeType()), gpu_info_(gpu_info), gpu_feature_info_(gpu_feature_info), bindings_(base::MakeUnique<mojo::BindingSet<mojom::GpuService>>()), weak_ptr_factory_(this) { DCHECK(!io_runner_->BelongsToCurrentThread()); weak_ptr_ = weak_ptr_factory_.GetWeakPtr(); } GpuServiceImpl::~GpuServiceImpl() { DCHECK(main_runner_->BelongsToCurrentThread()); bind_task_tracker_.TryCancelAll(); logging::SetLogMessageHandler(nullptr); g_log_callback.Get() = base::Callback<void(int, size_t, const std::string&)>(); base::WaitableEvent wait(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); if (io_runner_->PostTask( FROM_HERE, base::Bind(&DestroyBinding, bindings_.get(), &wait))) { wait.Wait(); } media_gpu_channel_manager_.reset(); gpu_channel_manager_.reset(); owned_sync_point_manager_.reset(); // Signal this event before destroying the child process. That way all // background threads can cleanup. For example, in the renderer the // RenderThread instances will be able to notice shutdown before the render // process begins waiting for them to exit. if (owned_shutdown_event_) owned_shutdown_event_->Signal(); } void GpuServiceImpl::UpdateGPUInfoFromPreferences( const gpu::GpuPreferences& preferences) { DCHECK(main_runner_->BelongsToCurrentThread()); DCHECK(!gpu_host_); gpu_preferences_ = preferences; gpu::GpuDriverBugWorkarounds gpu_workarounds( gpu_feature_info_.enabled_gpu_driver_bug_workarounds); gpu_info_.video_decode_accelerator_capabilities = media::GpuVideoDecodeAccelerator::GetCapabilities(gpu_preferences_, gpu_workarounds); gpu_info_.video_encode_accelerator_supported_profiles = media::GpuVideoEncodeAccelerator::GetSupportedProfiles(gpu_preferences_); gpu_info_.jpeg_decode_accelerator_supported = media::GpuJpegDecodeAcceleratorFactoryProvider:: IsAcceleratedJpegDecodeSupported(); // Record initialization only after collecting the GPU info because that can // take a significant amount of time. gpu_info_.initialization_time = base::Time::Now() - start_time_; } void GpuServiceImpl::InitializeWithHost( ui::mojom::GpuHostPtr gpu_host, gpu::GpuProcessActivityFlags activity_flags, gpu::SyncPointManager* sync_point_manager, base::WaitableEvent* shutdown_event) { DCHECK(main_runner_->BelongsToCurrentThread()); gpu_host->DidInitialize(gpu_info_, gpu_feature_info_); gpu_host_ = ui::mojom::ThreadSafeGpuHostPtr::Create(gpu_host.PassInterface(), io_runner_); if (!in_host_process_) { // The global callback is reset from the dtor. So Unretained() here is safe. // Note that the callback can be called from any thread. Consequently, the // callback cannot use a WeakPtr. g_log_callback.Get() = base::Bind(&GpuServiceImpl::RecordLogMessage, base::Unretained(this)); logging::SetLogMessageHandler(GpuLogMessageHandler); } sync_point_manager_ = sync_point_manager; if (!sync_point_manager_) { owned_sync_point_manager_ = base::MakeUnique<gpu::SyncPointManager>(); sync_point_manager_ = owned_sync_point_manager_.get(); } shutdown_event_ = shutdown_event; if (!shutdown_event_) { owned_shutdown_event_ = base::MakeUnique<base::WaitableEvent>( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); shutdown_event_ = owned_shutdown_event_.get(); } if (gpu_preferences_.enable_gpu_scheduler) { scheduler_ = base::MakeUnique<gpu::Scheduler>( base::ThreadTaskRunnerHandle::Get(), sync_point_manager_); } // Defer creation of the render thread. This is to prevent it from handling // IPC messages before the sandbox has been enabled and all other necessary // initialization has succeeded. gpu_channel_manager_.reset(new gpu::GpuChannelManager( gpu_preferences_, this, watchdog_thread_.get(), main_runner_, io_runner_, scheduler_.get(), sync_point_manager_, gpu_memory_buffer_factory_.get(), gpu_feature_info_, std::move(activity_flags))); media_gpu_channel_manager_.reset( new media::MediaGpuChannelManager(gpu_channel_manager_.get())); if (watchdog_thread()) watchdog_thread()->AddPowerObserver(); } void GpuServiceImpl::Bind(mojom::GpuServiceRequest request) { if (main_runner_->BelongsToCurrentThread()) { bind_task_tracker_.PostTask( io_runner_.get(), FROM_HERE, base::Bind(&GpuServiceImpl::Bind, base::Unretained(this), base::Passed(std::move(request)))); return; } bindings_->AddBinding(this, std::move(request)); } gpu::ImageFactory* GpuServiceImpl::gpu_image_factory() { return gpu_memory_buffer_factory_ ? gpu_memory_buffer_factory_->AsImageFactory() : nullptr; } void GpuServiceImpl::RecordLogMessage(int severity, size_t message_start, const std::string& str) { // This can be run from any thread. std::string header = str.substr(0, message_start); std::string message = str.substr(message_start); (*gpu_host_)->RecordLogMessage(severity, header, message); } void GpuServiceImpl::CreateJpegDecodeAccelerator( media::mojom::GpuJpegDecodeAcceleratorRequest jda_request) { DCHECK(io_runner_->BelongsToCurrentThread()); // TODO(c.padhi): Implement this, see https://crbug.com/699255. NOTIMPLEMENTED(); } void GpuServiceImpl::CreateVideoEncodeAcceleratorProvider( media::mojom::VideoEncodeAcceleratorProviderRequest vea_provider_request) { DCHECK(io_runner_->BelongsToCurrentThread()); media::MojoVideoEncodeAcceleratorProvider::Create( std::move(vea_provider_request), base::Bind(&media::GpuVideoEncodeAcceleratorFactory::CreateVEA), gpu_preferences_); } void GpuServiceImpl::CreateGpuMemoryBuffer( gfx::GpuMemoryBufferId id, const gfx::Size& size, gfx::BufferFormat format, gfx::BufferUsage usage, int client_id, gpu::SurfaceHandle surface_handle, CreateGpuMemoryBufferCallback callback) { DCHECK(io_runner_->BelongsToCurrentThread()); // This needs to happen in the IO thread. std::move(callback).Run(gpu_memory_buffer_factory_->CreateGpuMemoryBuffer( id, size, format, usage, client_id, surface_handle)); } void GpuServiceImpl::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id, int client_id, const gpu::SyncToken& sync_token) { if (io_runner_->BelongsToCurrentThread()) { main_runner_->PostTask(FROM_HERE, base::Bind(&GpuServiceImpl::DestroyGpuMemoryBuffer, weak_ptr_, id, client_id, sync_token)); return; } gpu_channel_manager_->DestroyGpuMemoryBuffer(id, client_id, sync_token); } void GpuServiceImpl::GetVideoMemoryUsageStats( GetVideoMemoryUsageStatsCallback callback) { if (io_runner_->BelongsToCurrentThread()) { auto wrap_callback = WrapCallback(io_runner_, std::move(callback)); main_runner_->PostTask( FROM_HERE, base::BindOnce(&GpuServiceImpl::GetVideoMemoryUsageStats, weak_ptr_, std::move(wrap_callback))); return; } gpu::VideoMemoryUsageStats video_memory_usage_stats; gpu_channel_manager_->gpu_memory_manager()->GetVideoMemoryUsageStats( &video_memory_usage_stats); std::move(callback).Run(video_memory_usage_stats); } void GpuServiceImpl::RequestCompleteGpuInfo( RequestCompleteGpuInfoCallback callback) { if (io_runner_->BelongsToCurrentThread()) { auto wrap_callback = WrapCallback(io_runner_, std::move(callback)); main_runner_->PostTask( FROM_HERE, base::BindOnce(&GpuServiceImpl::RequestCompleteGpuInfo, weak_ptr_, std::move(wrap_callback))); return; } DCHECK(main_runner_->BelongsToCurrentThread()); UpdateGpuInfoPlatform(base::BindOnce( IgnoreResult(&base::TaskRunner::PostTask), main_runner_, FROM_HERE, base::BindOnce( [](GpuServiceImpl* gpu_service, RequestCompleteGpuInfoCallback callback) { std::move(callback).Run(gpu_service->gpu_info_); #if defined(OS_WIN) if (!gpu_service->in_host_process_) { // The unsandboxed GPU process fulfilled its duty. Rest // in peace. base::RunLoop::QuitCurrentWhenIdleDeprecated(); } #endif }, this, std::move(callback)))); } #if defined(OS_MACOSX) void GpuServiceImpl::UpdateGpuInfoPlatform( base::OnceClosure on_gpu_info_updated) { DCHECK(main_runner_->BelongsToCurrentThread()); // gpu::CollectContextGraphicsInfo() is already called during gpu process // initialization (see GpuInit::InitializeAndStartSandbox()) on non-mac // platforms, and during in-browser gpu thread initialization on all platforms // (See InProcessGpuThread::Init()). if (in_host_process_) return; DCHECK_EQ(gpu::kCollectInfoNone, gpu_info_.context_info_state); gpu::CollectInfoResult result = gpu::CollectContextGraphicsInfo(&gpu_info_); switch (result) { case gpu::kCollectInfoFatalFailure: LOG(ERROR) << "gpu::CollectGraphicsInfo failed (fatal)."; // TODO(piman): can we signal overall failure? break; case gpu::kCollectInfoNonFatalFailure: DVLOG(1) << "gpu::CollectGraphicsInfo failed (non-fatal)."; break; case gpu::kCollectInfoNone: NOTREACHED(); break; case gpu::kCollectInfoSuccess: break; } gpu::SetKeysForCrashLogging(gpu_info_); std::move(on_gpu_info_updated).Run(); } #elif defined(OS_WIN) void GpuServiceImpl::UpdateGpuInfoPlatform( base::OnceClosure on_gpu_info_updated) { DCHECK(main_runner_->BelongsToCurrentThread()); // GPU full info collection should only happen on un-sandboxed GPU process // or single process/in-process gpu mode on Windows. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); DCHECK(command_line->HasSwitch("disable-gpu-sandbox") || in_host_process_); // We can continue on shutdown here because we're not writing any critical // state in this task. base::PostTaskAndReplyWithResult( base::CreateCOMSTATaskRunnerWithTraits( {base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}) .get(), FROM_HERE, base::BindOnce([]() { gpu::DxDiagNode dx_diag_node; gpu::GetDxDiagnostics(&dx_diag_node); return dx_diag_node; }), base::BindOnce( [](GpuServiceImpl* gpu_service, base::OnceClosure on_gpu_info_updated, const gpu::DxDiagNode& dx_diag_node) { gpu_service->gpu_info_.dx_diagnostics = dx_diag_node; gpu_service->gpu_info_.dx_diagnostics_info_state = gpu::kCollectInfoSuccess; std::move(on_gpu_info_updated).Run(); }, this, std::move(on_gpu_info_updated))); } #else void GpuServiceImpl::UpdateGpuInfoPlatform( base::OnceClosure on_gpu_info_updated) { std::move(on_gpu_info_updated).Run(); } #endif void GpuServiceImpl::DidCreateOffscreenContext(const GURL& active_url) { DCHECK(main_runner_->BelongsToCurrentThread()); (*gpu_host_)->DidCreateOffscreenContext(active_url); } void GpuServiceImpl::DidDestroyChannel(int client_id) { DCHECK(main_runner_->BelongsToCurrentThread()); media_gpu_channel_manager_->RemoveChannel(client_id); (*gpu_host_)->DidDestroyChannel(client_id); } void GpuServiceImpl::DidDestroyOffscreenContext(const GURL& active_url) { DCHECK(main_runner_->BelongsToCurrentThread()); (*gpu_host_)->DidDestroyOffscreenContext(active_url); } void GpuServiceImpl::DidLoseContext(bool offscreen, gpu::error::ContextLostReason reason, const GURL& active_url) { DCHECK(main_runner_->BelongsToCurrentThread()); (*gpu_host_)->DidLoseContext(offscreen, reason, active_url); } void GpuServiceImpl::StoreShaderToDisk(int client_id, const std::string& key, const std::string& shader) { DCHECK(main_runner_->BelongsToCurrentThread()); (*gpu_host_)->StoreShaderToDisk(client_id, key, shader); } #if defined(OS_WIN) void GpuServiceImpl::SendAcceleratedSurfaceCreatedChildWindow( gpu::SurfaceHandle parent_window, gpu::SurfaceHandle child_window) { DCHECK(main_runner_->BelongsToCurrentThread()); (*gpu_host_)->SetChildSurface(parent_window, child_window); } #endif void GpuServiceImpl::SetActiveURL(const GURL& url) { DCHECK(main_runner_->BelongsToCurrentThread()); constexpr char kActiveURL[] = "url-chunk"; base::debug::SetCrashKeyValue(kActiveURL, url.possibly_invalid_spec()); } void GpuServiceImpl::EstablishGpuChannel(int32_t client_id, uint64_t client_tracing_id, bool is_gpu_host, EstablishGpuChannelCallback callback) { if (io_runner_->BelongsToCurrentThread()) { EstablishGpuChannelCallback wrap_callback = base::BindOnce( [](scoped_refptr<base::SingleThreadTaskRunner> runner, EstablishGpuChannelCallback cb, mojo::ScopedMessagePipeHandle handle) { runner->PostTask(FROM_HERE, base::BindOnce(std::move(cb), std::move(handle))); }, io_runner_, std::move(callback)); main_runner_->PostTask( FROM_HERE, base::BindOnce(&GpuServiceImpl::EstablishGpuChannel, weak_ptr_, client_id, client_tracing_id, is_gpu_host, std::move(wrap_callback))); return; } gpu::GpuChannel* gpu_channel = gpu_channel_manager_->EstablishChannel( client_id, client_tracing_id, is_gpu_host); mojo::MessagePipe pipe; gpu_channel->Init(base::MakeUnique<gpu::SyncChannelFilteredSender>( pipe.handle0.release(), gpu_channel, io_runner_, shutdown_event_)); media_gpu_channel_manager_->AddChannel(client_id); std::move(callback).Run(std::move(pipe.handle1)); } void GpuServiceImpl::CloseChannel(int32_t client_id) { if (io_runner_->BelongsToCurrentThread()) { main_runner_->PostTask(FROM_HERE, base::Bind(&GpuServiceImpl::CloseChannel, weak_ptr_, client_id)); return; } gpu_channel_manager_->RemoveChannel(client_id); } void GpuServiceImpl::LoadedShader(const std::string& key, const std::string& data) { if (io_runner_->BelongsToCurrentThread()) { main_runner_->PostTask(FROM_HERE, base::Bind(&GpuServiceImpl::LoadedShader, weak_ptr_, key, data)); return; } gpu_channel_manager_->PopulateShaderCache(key, data); } void GpuServiceImpl::DestroyingVideoSurface( int32_t surface_id, DestroyingVideoSurfaceCallback callback) { DCHECK(io_runner_->BelongsToCurrentThread()); #if defined(OS_ANDROID) main_runner_->PostTaskAndReply( FROM_HERE, base::BindOnce( [](int32_t surface_id) { media::ContentVideoViewOverlayAllocator::GetInstance() ->OnSurfaceDestroyed(surface_id); }, surface_id), std::move(callback)); #else NOTREACHED() << "DestroyingVideoSurface() not supported on this platform."; #endif } void GpuServiceImpl::WakeUpGpu() { if (io_runner_->BelongsToCurrentThread()) { main_runner_->PostTask(FROM_HERE, base::Bind(&GpuServiceImpl::WakeUpGpu, weak_ptr_)); return; } #if defined(OS_ANDROID) gpu_channel_manager_->WakeUpGpu(); #else NOTREACHED() << "WakeUpGpu() not supported on this platform."; #endif } void GpuServiceImpl::GpuSwitched() { DVLOG(1) << "GPU: GPU has switched"; if (!in_host_process_) ui::GpuSwitchingManager::GetInstance()->NotifyGpuSwitched(); } void GpuServiceImpl::DestroyAllChannels() { if (io_runner_->BelongsToCurrentThread()) { main_runner_->PostTask( FROM_HERE, base::Bind(&GpuServiceImpl::DestroyAllChannels, weak_ptr_)); return; } DVLOG(1) << "GPU: Removing all contexts"; gpu_channel_manager_->DestroyAllChannels(); } void GpuServiceImpl::Crash() { DCHECK(io_runner_->BelongsToCurrentThread()); DVLOG(1) << "GPU: Simulating GPU crash"; // Good bye, cruel world. volatile int* it_s_the_end_of_the_world_as_we_know_it = NULL; *it_s_the_end_of_the_world_as_we_know_it = 0xdead; } void GpuServiceImpl::Hang() { DCHECK(io_runner_->BelongsToCurrentThread()); main_runner_->PostTask(FROM_HERE, base::Bind([] { DVLOG(1) << "GPU: Simulating GPU hang"; for (;;) { // Do not sleep here. The GPU watchdog timer tracks // the amount of user time this thread is using and // it doesn't use much while calling Sleep. } })); } void GpuServiceImpl::ThrowJavaException() { DCHECK(io_runner_->BelongsToCurrentThread()); #if defined(OS_ANDROID) main_runner_->PostTask( FROM_HERE, base::Bind([] { base::android::ThrowUncaughtException(); })); #else NOTREACHED() << "Java exception not supported on this platform."; #endif } void GpuServiceImpl::Stop(StopCallback callback) { DCHECK(io_runner_->BelongsToCurrentThread()); main_runner_->PostTaskAndReply( FROM_HERE, base::BindOnce([] { base::RunLoop::QuitCurrentWhenIdleDeprecated(); }), std::move(callback)); } } // namespace viz
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
6e3eabd943595099c7a747108bede25ac7fb3db3
612f23e6503bbaf257a730257ee8945d3a196d0c
/Chapter13/friend_function/fractions.cpp
55b9abe3701be25fbc41ad8a4f90a9018c689a29
[ "MIT" ]
permissive
Rayyan06/CPP
a81d8c2a6161bc74bdd5d6d9662b56a9cc7e2462
daeededda19a0d9766115a700dd949d92dfa4963
refs/heads/main
2023-05-04T08:42:51.588098
2021-05-16T12:10:01
2021-05-16T12:10:01
356,848,090
1
0
null
null
null
null
UTF-8
C++
false
false
2,118
cpp
#include <iostream> #include <cassert> #include <limits> class Fraction { private: int m_numerator{ 0 }; int m_denominator{ 1 }; public: Fraction(int numerator=0, int denominator=1) { assert((denominator != 0) && "Zero division error. "); m_numerator = numerator; m_denominator = denominator; reduce(); } void print() const { std::cout << m_numerator << "/" << m_denominator << '\n'; } static int gcd(int a, int b) { return (b == 0) ? (a > 0 ? a: -a) : gcd(b, a % b); } public: void reduce() { if(m_numerator != 0) { int gcd{ Fraction::gcd(m_numerator, m_denominator) }; m_numerator /= gcd; m_denominator /= gcd; } } friend Fraction operator*(const Fraction& f1, const Fraction& f2); friend Fraction operator*(const Fraction& f, int value); friend Fraction operator*(int value, const Fraction& f); friend std::ostream& operator<< (std::ostream& out, const Fraction& f); friend std::istream& operator>> (std::istream& in, Fraction& f); }; Fraction operator*(const Fraction& f1, const Fraction& f2) { return { f1.m_numerator * f2.m_numerator, f1.m_denominator * f2.m_denominator}; } Fraction operator*(const Fraction& f, int value) { return { f.m_numerator * value, f.m_denominator }; } Fraction operator*(int value, const Fraction& f) { return {f.m_numerator * value, f.m_denominator}; // Overloaded :) } std::ostream& operator<< (std::ostream& out, const Fraction& f) { out << f.m_numerator << '/' << f.m_denominator; return out; } std::istream& operator>> (std::istream& in, Fraction& f) { // Overwrite the values of f in >> f.m_numerator; // Ignore the '/' separator in.ignore(std::numeric_limits<std::streamsize>::max(), '/'); in >> f.m_denominator; // Since we overwrite the existing f1, we need to reduce again f.reduce(); return in; } int main() { Fraction f1{}; std::cout << "Enter fraction 1: "; std::cin >> f1; Fraction f2{}; std::cout << "Enter fraction 2: "; std::cin >> f2; std::cout << f1 << " * " << f2 << " is " << f1 * f2 << '\n'; // note: The result of f1 * f2 is an r-value return 0; }
[ "anonymous" ]
anonymous
276bdafc6f3edceb8d976441484548ac66adb98d
841c0df958129bef4ec456630203992a143c7dc7
/src/15/15596.cpp
5e6bed0511923c82bdac81f55f7ff984beb19c89
[ "MIT" ]
permissive
xCrypt0r/Baekjoon
da404d3e2385c3278a1acd33ae175c2c1eb82e5e
7d858d557dbbde6603fe4e8af2891c2b0e1940c0
refs/heads/master
2022-12-25T18:36:35.344896
2021-11-22T20:01:41
2021-11-22T20:01:41
287,291,199
16
25
MIT
2022-12-13T05:03:49
2020-08-13T13:42:32
C++
UTF-8
C++
false
false
343
cpp
/** * 15596. 정수 N개의 합 * * 작성자: xCrypt0r * 언어: C++14 * 사용 메모리: 13,704 KB * 소요 시간: 8 ms * 해결 날짜: 2020년 8월 17일 */ #include <vector> long long sum(std::vector<int> &a) { long long ret = 0; for (int i = 0; i < a.size(); ++i) { ret += a[i]; } return ret; }
[ "fireintheholl@naver.com" ]
fireintheholl@naver.com
0a8dd7c0cbf3dedd04035d4443ef31b099854933
5666c4d3dc294fe53ac2eba6216dd21fff1e96e3
/The_Library/src/Book.hpp
7142061afbf3e90bfc1989cd8dcb210e9dc9001a
[]
no_license
oherterich/EdLab-Collective-Wisdom
8b9612c192a9cee7d822c07eb62356becdb05585
62a6ff7f6bd28e78603548879e77ed755eaaf843
refs/heads/master
2020-07-03T22:14:40.010254
2016-11-19T18:12:59
2016-11-19T18:12:59
74,226,105
0
0
null
2016-11-19T18:09:37
2016-11-19T18:09:37
null
UTF-8
C++
false
false
1,288
hpp
// // Book.hpp // The_Library // // Created by Adiel Fernandez on 11/15/16. // // #ifndef Book_hpp #define Book_hpp #include <stdio.h> #endif /* Book_hpp */ #include "ofMain.h" #include "ofxAssimpModelLoader.h" class Book{ public: Book(); void setup(); void update(); void draw(); ofxAssimpModelLoader model; ofFbo liveTexture; ofMaterial material; vector<ofTexture> textures; /* //When model scale = 1.0, The real world pixel dimensions are below Scale to multiply mesh verts: 32.4672 realMin X: -1.2483 realMax X: -432.41 realMin Y: -1.95889 realMax Y: -59.3313 realMin Z: -339.395 realMax Z: 300.192 */ //these are the actual min/max //dimensions of the closed book float maxX; float minX; float maxY; float minY; float maxZ; float minZ; //Scaling of model through //AssImp methods float modelScale; //Actual amount needed to scale //the vertices to get real world size (in px) const float vertScale = 32.4672; float realMaxX; float realMinX; float realMaxY; float realMinY; float realMaxZ; float realMinZ; };
[ "ferna058@newschool.edu" ]
ferna058@newschool.edu
610f27b578ac01b79590806855f6bf333dbc13cc
d85b1f3ce9a3c24ba158ca4a51ea902d152ef7b9
/testcases/CWE78_OS_Command_Injection/s02/CWE78_OS_Command_Injection__char_environment_execlp_83_bad.cpp
e04b81e7ec39c541f34d863911bddb055e3fc45d
[]
no_license
arichardson/juliet-test-suite-c
cb71a729716c6aa8f4b987752272b66b1916fdaa
e2e8cf80cd7d52f824e9a938bbb3aa658d23d6c9
refs/heads/master
2022-12-10T12:05:51.179384
2022-11-17T15:41:30
2022-12-01T15:25:16
179,281,349
34
34
null
2022-12-01T15:25:18
2019-04-03T12:03:21
null
UTF-8
C++
false
false
2,047
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__char_environment_execlp_83_bad.cpp Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-83_bad.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: environment Read input from an environment variable * GoodSource: Fixed string * Sinks: execlp * BadSink : execute command with execlp * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE78_OS_Command_Injection__char_environment_execlp_83.h" #define ENV_VARIABLE "ADD" #ifdef _WIN32 #define GETENV getenv #else #define GETENV getenv #endif #ifdef _WIN32 #include <process.h> #define EXECLP _execlp #else /* NOT _WIN32 */ #define EXECLP execlp #endif namespace CWE78_OS_Command_Injection__char_environment_execlp_83 { CWE78_OS_Command_Injection__char_environment_execlp_83_bad::CWE78_OS_Command_Injection__char_environment_execlp_83_bad(char * dataCopy) { data = dataCopy; { /* Append input from an environment variable to data */ size_t dataLen = strlen(data); char * environment = GETENV(ENV_VARIABLE); /* If there is data in the environment variable */ if (environment != NULL) { /* POTENTIAL FLAW: Read data from an environment variable */ strncat(data+dataLen, environment, 100-dataLen-1); } } } CWE78_OS_Command_Injection__char_environment_execlp_83_bad::~CWE78_OS_Command_Injection__char_environment_execlp_83_bad() { /* execlp - searches for the location of the command among * the directories specified by the PATH environment variable */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ EXECLP(COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG3, NULL); } } #endif /* OMITBAD */
[ "Alexander.Richardson@cl.cam.ac.uk" ]
Alexander.Richardson@cl.cam.ac.uk
2bd7db0b510b8c229a30d6298b90b77607920c7f
fa092a67943b236a860f472d15c27ea46f78cfb9
/kaprekar.c++
6c5b0f8a85b18c0a3bd55ce38164f219f04e95fe
[]
no_license
Sanjana00/Cpp-Codes
42f8ca52d27b733c08ecd4b9e2c7bca3a9ee4937
f72e807ae689ac7c250d40907b99dc150bbfca83
refs/heads/master
2022-11-12T03:14:29.012765
2020-07-07T04:29:29
2020-07-07T04:29:29
277,715,731
0
0
null
null
null
null
UTF-8
C++
false
false
947
#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<int> sort_digits(int n) { vector<int> digits; for (; n > 0; n /= 10) digits.push_back(n % 10); sort(digits.begin(), digits.end()); return digits; } int to_num(vector<int> digits) { int result = 0; for (const int digit : digits) result = result * 10 + digit; return result; } int next(int n) { vector<int> digits = sort_digits(n); int smaller = to_num(digits); reverse(digits.begin(), digits.end()); int larger = to_num(digits); return larger - smaller; } vector<int> kaprekar(int n) { vector<int> seq; do { seq.push_back(n); n = next(n); }while(n != seq.back()); return seq; } int main(int argc, char* argv[]) { int START = stoi(argv[1]); vector<int> kap = kaprekar(START); for (const int k : kap) cout << k << endl; return 0; }
[ "sanjana.chakravarty@gmail.com" ]
sanjana.chakravarty@gmail.com
2e170c93fa97a7d3d68b0332aaf9f6155dc2f650
04251e142abab46720229970dab4f7060456d361
/lib/rosetta/source/src/protocols/denovo_design/architects/BlueprintArchitectCreator.hh
7b62841d72283f648a29b58d2c2d11d8ebbc46ee
[]
no_license
sailfish009/binding_affinity_calculator
216257449a627d196709f9743ca58d8764043f12
7af9ce221519e373aa823dadc2005de7a377670d
refs/heads/master
2022-12-29T11:15:45.164881
2020-10-22T09:35:32
2020-10-22T09:35:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,750
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu. /// @file protocols/denovo_design/architects/BlueprintArchitectCreator.hh /// @brief Class for instantiating a particular DeNovoArchitect /// @author Tom Linsky ( tlinsky at uw dot edu ) #ifndef INCLUDED_protocols_denovo_design_architects_BlueprintArchitectCreator_HH #define INCLUDED_protocols_denovo_design_architects_BlueprintArchitectCreator_HH // Package headers #include <protocols/denovo_design/architects/DeNovoArchitectCreator.hh> #include <protocols/denovo_design/architects/DeNovoArchitect.fwd.hh> // Utility headers #include <utility/VirtualBase.hh> // C++ headers #include <string> namespace protocols { namespace denovo_design { namespace architects { class BlueprintArchitectCreator : public DeNovoArchitectCreator { public: /// @brief Instantiate a particular DeNovoArchitect DeNovoArchitectOP create_architect( std::string const & architect_id ) const override; /// @brief Return a string that will be used to instantiate the particular DeNovoArchitect std::string keyname() const override; void provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd ) const override; }; } //namespace architects } //namespace denovo_design } //namespace protocols #endif
[ "lzhangbk@connect.ust.hk" ]
lzhangbk@connect.ust.hk
5de9b1233f446df6c706624509366f980d160169
204c5937cdea475f5c3dafde6d770a74ae9b8919
/bzoj/2705(欧拉函数).cpp
14356563646b8f25d925de7f9cf12f2eaa9cf822
[]
no_license
mlz000/Algorithms
ad2c35e4441bcbdad61203489888b83627024b7e
495eb701d4ec6b317816786ad5b38681fbea1001
refs/heads/master
2023-01-04T03:50:02.673937
2023-01-02T22:46:20
2023-01-02T22:46:20
101,135,823
7
1
null
null
null
null
UTF-8
C++
false
false
566
cpp
#include<iostream> #include<cstring> #include<cmath> #include<cstdio> #include<algorithm> using namespace std; long long phi(long long x){ if(x==1) return 1ll; long long tmp=1ll; for(long long i=2;i*i<=x;++i){ if(x%i==0){ int cnt=0; while(x%i==0) cnt++,x/=i; tmp*=i-1; for(int j=1;j<cnt;++j) tmp*=i; } } if(x>1) tmp*=x-1; return tmp; } int main(){ long long n; scanf("%lld",&n); long long ans=0ll; for(long long i=1ll;i*i<=n;++i){ if(n%i==0){ ans+=i*phi(n/i); if(i*i<n) ans+=(n/i)*phi(i); } } printf("%lld\n",ans); return 0; }
[ "njumlz@gmail.com" ]
njumlz@gmail.com
71f1d0425b880b2bf647216a661e7324248a178d
4ac7569cd87c6b8f3384d4c496e14f97d1c3b95c
/Classes/fmStatic/FSAssetsManager.h
30cfcbd82939082c72c197fd1609fba7cc45d3a0
[]
no_license
spzktshow/isoMap
c81e3fa9ab33b66dec57ead049ad202148a1ed97
744b5fc3bdb5a7483ab6bc8427ae4a82b37d9c1e
refs/heads/master
2021-01-23T02:59:30.194253
2013-12-18T14:03:45
2013-12-18T14:03:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
642
h
#ifndef __AssetsManager_FSAssetsManager__ #define __AssetsManager_FSAssetsManager__ #include "fmStatic.h" #include <cocos2d.h> #include "MSGroup.h" NS_FS_BEGIN class FSAssets : public moonSugar::MSGroupItem { public: FSAssets(char* datasValue, char* nameValue); ~FSAssets(); protected: char* datas; }; class FSAssetsCache : public moonSugar::MSGroup { public: FSAssetsCache(); ~FSAssetsCache(); static FSAssetsCache* getInstance(); }; class FSAssetsManager : public moonSugar::MSGroup { public: FSAssetsManager(); ~FSAssetsManager(); static FSAssetsManager* getInstance(); }; NS_FS_END; #endif
[ "gdspzkt@gmail.com" ]
gdspzkt@gmail.com
4eb08a1be61af58d11591decf4625021a242ae00
304be39df2e2b803f5cecec86c9367f423a1ae88
/Intermediate/arrays.cpp
effc986e28859189edcb82c3cafa9033eb468682
[]
no_license
amit1github/.CPPbyCodeWithHarry
3433dffb6807c9a26bfc3d8a92705a1bca081133
1b799bd8996fe2552bac300edb092af3995f51b7
refs/heads/master
2023-07-07T18:04:39.440070
2021-08-25T15:55:55
2021-08-25T15:55:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
751
cpp
#include<iostream> using namespace std; int main(){ // int arr[] = {1, 3, 6}; // //Array Index 0, 1, 2 // cout << arr[0]; //One - Dimensional array. // int marks[6]; // for (int i = 0; i < 6; i++) // { // cout<<"Marks of "<< i <<"th student is "<<marks[i]<<endl; // cin >> marks[i]; // } // for (int i = 0; i < 6; i++) // { // cout<<"Marks of "<< i <<"th student is "<<marks[i]<<endl; // } // Two Dimensional array int arr[4] [3] = {{ 1, 3, 6 } , { 2, 4, 8 }}; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << "The value at "<< i <<","<< j << " is " <<arr[i][j] << endl; } }; return 0; };
[ "amityadavinvalid@gmail.com" ]
amityadavinvalid@gmail.com
bb757c9933a0fedc590b8cdec10fca20f9352e9c
79795d6fe58bf3713f5461b26f9f78f735d4c73c
/src/Camera.cpp
70fc2c91e741bb58c6aac346f8eeb789011dd6db
[]
no_license
IntelOrca/popss
b5f74b340962dfa9e41b86c4a8e5bdc38eb01164
15f359a9ac9114b95f8b0b1336b39b03e11b81a3
refs/heads/master
2020-12-26T02:01:16.573584
2015-01-18T02:57:13
2015-01-18T02:57:13
28,665,965
1
1
null
null
null
null
UTF-8
C++
false
false
5,410
cpp
#include "Camera.h" #include "LandscapeRenderer.h" #include "Util/MathExtensions.hpp" #include "World.h" #include <glm/gtc/matrix_transform.hpp> using namespace IntelOrca::PopSS; const float Camera::MoveSpeed = 1.0f * World::TileSize; const float Camera::RotationSpeed = 360.0f / (60.0f * 3.0f); Camera::Camera() { this->fov = 60.0f; // this->target = glm::vec3(0, 512 + 128, 0); this->target = glm::vec3(128 * World::TileSize, 512 + 128, 128 * World::TileSize); this->zoom = 1024.0 + 256; this->targetZoom = this->zoom; SetRotation(0.0f); this->viewHasChanged = true; } Camera::~Camera() { } glm::mat4 Camera::Get3dProjectionMatrix() const { return glm::perspective( this->fov * (float)(M_PI / 180), 1920.0f / 1080.0f, 1.0f, 256.0f * 256.0f ); } glm::mat4 Camera::Get3dViewMatrix() const { return glm::lookAt( this->eye, this->target, glm::vec3(0.0f, 1.0f, 0.0f) ); } glm::vec3 Camera::GetViewportRayDirection(int x, int y) const { glm::vec3 rayNDS = glm::vec3( (gCursor.x * 2.0f) / 1920 - 1.0f, 1.0f - (gCursor.y * 2.0f) / 1080, 1.0f ); glm::vec4 rayClip = glm::vec4(rayNDS.x, rayNDS.y, -1.0, 1.0); glm::vec4 rayEye = glm::inverse(this->Get3dProjectionMatrix()) * rayClip; rayEye.z = -1.0f; rayEye.w = 0.0f; return glm::normalize(glm::vec3(glm::inverse(this->Get3dViewMatrix()) * rayEye)); } glm::vec3 Camera::SphereDistort(const glm::vec3 &position, float ratio) const { glm::vec3 relative = position - this->target; return glm::vec3( position.x, position.y - (ratio * (relative.x * relative.x + relative.z * relative.z)), position.z ); } bool Camera::GetWorldPositionFromViewport(int x, int y, glm::ivec3 *outPosition) const { float t, bestT; glm::vec3 eye = this->eye; glm::vec3 eyeDirection = this->GetViewportRayDirection(x, y); bool foundLandIntersection = false; float dist, sdist; glm::vec3 v[4]; glm::vec3 sintersection; int landOriginX = (int)(this->target.x / World::TileSize); int landOriginZ = (int)(this->target.z / World::TileSize); for (int z = -32; z <= 32; z++) { for (int x = -32; x <= 32; x++) { int landX = landOriginX + x; int landZ = landOriginZ + z; int lx = landX * World::TileSize; int lz = landZ * World::TileSize; v[0] = glm::vec3(lx, this->world->GetTile(landX, landZ)->height, lz); v[1] = glm::vec3(lx, this->world->GetTile(landX, landZ + 1)->height, lz + World::TileSize); v[2] = glm::vec3(lx + World::TileSize, this->world->GetTile(landX + 1, landZ + 1)->height, lz + World::TileSize); v[3] = glm::vec3(lx + World::TileSize, this->world->GetTile(landX + 1, landZ)->height, lz); for (int i = 0; i < 4; i++) v[i] = this->SphereDistort(v[i], LandscapeRenderer::SphereRatio); if (TriangleIntersect(eye, eyeDirection, v[0], v[1], v[2], &t) || TriangleIntersect(eye, eyeDirection, v[2], v[3], v[0], &t)) { float dist = abs(((v[0].x + v[1].x + v[2].x + v[3].x) / 4.0f - eye.x) + ((v[0].z + v[1].z + v[2].z + v[3].z) / 4.0f - eye.z)); if (!foundLandIntersection || dist < sdist) { foundLandIntersection = true; sdist = dist; bestT = t; } } } } if (foundLandIntersection) { *outPosition = eye + eyeDirection * t; return true; } if (!PlaneIntersect(eye, eyeDirection, glm::vec3(0), glm::vec3(0, 1, 0), &t)) return false; *outPosition = eye + eyeDirection * t; return true; } void Camera::Update() { this->UpdateZoom(); } void Camera::RotateLeft() { SetRotation(wraprange(0.0f, this->rotation + RotationSpeed, 360.0f)); } void Camera::RotateRight() { SetRotation(wraprange(0.0f, this->rotation - RotationSpeed, 360.0f)); } void Camera::MoveForwards() { this->target.x -= sin(toradians(this->rotation)) * MoveSpeed; this->target.z -= cos(toradians(this->rotation)) * MoveSpeed; this->target.x = this->world->Wrap(this->target.x); this->target.z = this->world->Wrap(this->target.z); UpdateEye(); } void Camera::MoveBackwards() { this->target.x += sin(toradians(this->rotation)) * MoveSpeed; this->target.z += cos(toradians(this->rotation)) * MoveSpeed; this->target.x = this->world->Wrap(this->target.x); this->target.z = this->world->Wrap(this->target.z); UpdateEye(); } void Camera::UpdateEye() { float zoom = this->zoom; float rotationRadians = toradians(this->rotation); this->eye = glm::vec3( sin(rotationRadians) * zoom + this->target.x, zoom, cos(rotationRadians) * zoom + this->target.z );; this->viewHasChanged = true; } void Camera::SetRotation(float value) { this->rotation = value; UpdateEye(); } void Camera::SetZoom(float value) { this->zoom = value; UpdateEye(); } void Camera::UpdateZoom() { if (this->zoom == this->targetZoom) { this->zoomSpeed = 0; return; } const float minZoomSpeed = 8.0f; this->zoomSpeed = max(minZoomSpeed, this->zoomSpeed - max(1.0f, this->zoomSpeed / 64)); if (this->zoom < this->targetZoom) SetZoom(min(this->zoom + this->zoomSpeed, this->targetZoom)); else if (this->zoom > this->targetZoom) SetZoom(max(this->zoom - this->zoomSpeed, this->targetZoom)); } void Camera::ZoomIn() { if (this->targetZoom > 768.0f) { this->targetZoom = max(768.0f, this->targetZoom - 512.0f); this->zoomSpeed = min(96.0f, this->zoomSpeed + 42.0f); } } void Camera::ZoomOut() { if (this->targetZoom < 2560.0f) { this->targetZoom = min(2560.0f, this->targetZoom + 512.0f); this->zoomSpeed = min(96.0f, this->zoomSpeed + 42.0f); } }
[ "ted@brambles.org" ]
ted@brambles.org
f0a694999dd4a53b0453e9757cee15194ff5bbd8
575731c1155e321e7b22d8373ad5876b292b0b2f
/examples/native/ios/Pods/boost-for-react-native/boost/fusion/algorithm/iteration/iter_fold.hpp
dfb27e4cf6ee4a1796360d34d69cfeddae552daf
[ "BSL-1.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Nozbe/zacs
802a84ffd47413a1687a573edda519156ca317c7
c3d455426bc7dfb83e09fdf20781c2632a205c04
refs/heads/master
2023-06-12T20:53:31.482746
2023-06-07T07:06:49
2023-06-07T07:06:49
201,777,469
432
10
MIT
2023-01-24T13:29:34
2019-08-11T14:47:50
JavaScript
UTF-8
C++
false
false
2,376
hpp
/*============================================================================= Copyright (c) 2010 Christopher Schmidt Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2015 Kohei Takahashi 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 BOOST_FUSION_ALGORITHM_ITERATION_ITER_FOLD_HPP #define BOOST_FUSION_ALGORITHM_ITERATION_ITER_FOLD_HPP #include <boost/fusion/support/config.hpp> #include <boost/fusion/algorithm/iteration/iter_fold_fwd.hpp> #include <boost/config.hpp> #include <boost/fusion/sequence/intrinsic/begin.hpp> #include <boost/fusion/sequence/intrinsic/size.hpp> #include <boost/fusion/support/is_segmented.hpp> #include <boost/fusion/support/is_sequence.hpp> #include <boost/fusion/iterator/deref.hpp> #include <boost/fusion/iterator/value_of.hpp> #include <boost/fusion/iterator/next.hpp> #include <boost/utility/result_of.hpp> #include <boost/core/enable_if.hpp> #include <boost/type_traits/add_reference.hpp> #define BOOST_FUSION_ITER_FOLD #if !defined(BOOST_FUSION_DONT_USE_PREPROCESSED_FILES) #include <boost/fusion/algorithm/iteration/detail/preprocessed/iter_fold.hpp> #else #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 2, line: 0, output: "detail/preprocessed/iter_fold.hpp") #endif /*============================================================================= Copyright (c) 2010 Christopher Schmidt Copyright (c) 2001-2011 Joel de Guzman 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) This is an auto-generated file. Do not edit! ==============================================================================*/ #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 1) #endif #include <boost/fusion/algorithm/iteration/detail/fold.hpp> #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(output: null) #endif #endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES #undef BOOST_FUSION_ITER_FOLD #endif
[ "radexpl@gmail.com" ]
radexpl@gmail.com
ad180855a682ec4c651a1dcb0fd68aca3498c1be
bf8fcdbf6101caef2674fb74c9920cc67f3d8e9b
/AudioStreamingLib/Demos/WalkieTalkie/mainwindow.h
7dcd3e3a8363ef9ab9558af837c5b76fb9ee3cfe
[ "MIT" ]
permissive
xGreat/AudioStreaming
14f6738cbeba4e1c5de2333c522dd9de5092f138
10f5e81cf9eb3d5dbb6958fd0c9a48f5c4ab5630
refs/heads/master
2023-03-23T13:38:29.759279
2019-07-05T04:37:12
2019-07-05T04:37:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,686
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QtCore> #include <QtGui> #include <QtWidgets> #include <AudioStreamingLibCore> #include "common.h" #include "settings.h" #include "levelwidget.h" #include "audiorecorder.h" #include "mp3recorder.h" class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); signals: void stoprequest(); private slots: void initWidgets(); void currentChanged(int index); void startDiscover(); void stopDiscover(); void peerFound(const QHostAddress &address, const QString &id); void selectPeer(QListWidgetItem *item); void webClient(const QString &username, const QString &password, bool unavailable = false, bool new_user = false, const QString &code = QString()); void client(); void server(); void sliderVolumeValueChanged(int value); void webClientStarted(bool enable); void clientStarted(bool enable); void serverStarted(bool enable); void warning(const QString &warning); void error(const QString &error); void adjustSettings(); void setRecordPath(); void startPauseRecord(); void stopRecord(); void resetRecordPage(); void writeLocalToBuffer(const QByteArray &data); void writePeerToBuffer(const QByteArray &data); void mixLocalPeer(); void connectedToServer(const QByteArray &hash); void connectToPeer(); void webClientConnected(const QHostAddress &address, const QString &id); void clientConnected(const QHostAddress &address, const QString &id); void serverConnected(const QHostAddress &address, const QString &id); void webClientDisconnected(); void clientDisconnected(); void serverDisconnected(); void pending(const QHostAddress &address, const QString &id); void webClientLoggedIn(); void webClientWarning(const QString &message); void writeText(); void receiveText(const QByteArray &data); void finished(); void currentInputIndexChanged(int index); void currentOutputIndexChanged(int index); void getDevInfo(); private: QString m_peer; bool m_connecting_connected_to_peer; QPointer<AudioStreamingLibCore> m_audio_lib; QPointer<AudioStreamingLibCore> m_discover_instance; Settings *websettings; QListWidget *listwidgetpeers; LevelWidget *levelinput; LevelWidget *leveloutput; QTabWidget *tabwidget; QComboBox *comboboxaudioinput; QComboBox *comboboxaudiooutput; QPushButton *buttonconnecttopeer; QLabel *labelservertweb; QLineEdit *lineserverweb; QLabel *labelportweb; QLineEdit *lineportweb; QLabel *labelsamplerateweb; QLineEdit *linesamplerateweb; QLabel *labelchannelsweb; QLineEdit *linechannelsweb; QLabel *labelbuffertimeweb; QLineEdit *linebuffertimeweb; QLabel *labelhost; QLineEdit *linehost; QLabel *labelport; QLineEdit *lineport; QPlainTextEdit *texteditsettings; QCheckBox *boxinputmuted; QLabel *labelvolume; QSlider *slidervolume; QLabel *labelportserver; QLineEdit *lineportserver; QLabel *labelsamplerate; QLineEdit *linesamplerate; QLabel *labelchannels; QLineEdit *linechannels; QLabel *labelbuffertime; QLineEdit *linebuffertime; QPlainTextEdit *texteditchat; QLineEdit *linechat; QPushButton *buttonsendchat; QLabel *labelwebid; QLabel *labelclientid; QLabel *labelserverid; QLabel *labelwebcode; QLabel *labelwebpassword; QLabel *labelclientpassword; QLabel *labelserverpassword; QLineEdit *linewebid; QLineEdit *lineclientid; QLineEdit *lineserverid; QLineEdit *linewebpassword; QLineEdit *lineclientpassword; QLineEdit *lineserverpassword; QLineEdit *linewebcode; QPushButton *buttonsigninweb; QPushButton *buttonsignupweb; QPushButton *buttonconnect; QPushButton *buttonstartserver; QWidget *widget1; QWidget *widget2; QWidget *widget3; QScrollArea *scrollclientserver; QWidget *widgetchat; QLineEdit *linerecordpath; QPushButton *buttonsearch; QPushButton *buttonrecord; QPushButton *buttonrecordstop; QLCDNumber *lcdtime; QCheckBox *boxautostart; QPlainTextEdit *texteditlog; QCheckBox *boxlogtowidget; QPushButton *buttonclearlog; QPointer<AudioRecorder> m_audio_recorder; QPointer<MP3Recorder> m_audio_recorder_mp3; QAudioFormat m_format; qint64 m_total_size; bool m_paused; QByteArray m_local_audio; QByteArray m_peer_audio; bool m_msgbox_visible; QByteArray m_web_login_xml; }; #endif // MAINWINDOW_H
[ "antonyproductions@gmail.com" ]
antonyproductions@gmail.com
6ff7ddfa59b9a34d065f6064a7f54090d3044e9e
ef7d308ff157eb43d9056dae91ea24effd2f32b2
/RevealTriangle.cpp
0bc49c3a3904f9813082d2a554515aef66d5083f
[]
no_license
abhiranjankumar00/TopCoder-SRM-submissions
cd37f2f2638c2e40daa571d08e2b068382921f23
d0d3ee3bde2be630f6126d53f4bb0ea008a03150
refs/heads/master
2021-01-18T01:42:20.313261
2018-04-09T19:04:42
2018-04-09T19:04:42
5,789,738
2
4
null
null
null
null
UTF-8
C++
false
false
6,119
cpp
#include <bits/stdc++.h> using namespace std; class RevealTriangle { public: vector <string> calcTriangle(vector <string> questionMarkTriangle); }; void solve(char &a, char &b, char &s) { if(s == '?') return; if(a=='?' && b =='?') return; int l = a== '?' ? b : a; l-='0'; for(int r = 0; r < (int)11; ++r) { if((l+r)%10 == s-'0') { (a=='?' ? a : b) = r + '0'; return; } } } vector <string> RevealTriangle::calcTriangle (vector <string> questionMarkTriangle) { vector <string> ret = questionMarkTriangle; for(int i = (int)ret.size()-1; i >= (int)1; --i) { for(int k = 0; k < (int)50; ++k) { for(int j = 0; j < (int)ret[i].size(); ++j) { solve(ret[i-1][j], ret[i-1][j+1], ret[i][j]); } } } return ret; } // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.8 (beta) modified by pivanof #include <iostream> #include <string> #include <vector> using namespace std; bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, vector <string> p1) { cout << "Test " << testNum << ": [" << "{"; for (int i = 0; int(p0.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << "\"" << p0[i] << "\""; } cout << "}"; cout << "]" << endl; RevealTriangle *obj; vector <string> answer; obj = new RevealTriangle(); clock_t startTime = clock(); answer = obj->calcTriangle(p0); clock_t endTime = clock(); delete obj; bool res; res = true; cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl; if (hasAnswer) { cout << "Desired answer:" << endl; cout << "\t" << "{"; for (int i = 0; int(p1.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << "\"" << p1[i] << "\""; } cout << "}" << endl; } cout << "Your answer:" << endl; cout << "\t" << "{"; for (int i = 0; int(answer.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << "\"" << answer[i] << "\""; } cout << "}" << endl; if (hasAnswer) { if (answer.size() != p1.size()) { res = false; } else { for (int i = 0; int(answer.size()) > i; ++i) { if (answer[i] != p1[i]) { res = false; } } } } if (!res) { cout << "DOESN'T MATCH!!!!" << endl; } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) { cout << "FAIL the timeout" << endl; res = false; } else if (hasAnswer) { cout << "Match :-)" << endl; } else { cout << "OK, but is it right?" << endl; } cout << "" << endl; return res; } int main() { bool all_right; all_right = true; vector <string> p0; vector <string> p1; { // ----- test 0 ----- string t0[] = {"4?" "?","?2","1"}; p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); string t1[] = {"457","92","1"}; p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0])); all_right = KawigiEdit_RunTest(0, p0, true, p1) && all_right; // ------------------ } { // ----- test 1 ----- string t0[] = {"1"}; p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); string t1[] = {"1"}; p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0])); all_right = KawigiEdit_RunTest(1, p0, true, p1) && all_right; // ------------------ } { // ----- test 2 ----- string t0[] = {"?" "?" "?2","?" "?2","?2","2"}; p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); string t1[] = {"0002","002","02","2"}; p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0])); all_right = KawigiEdit_RunTest(2, p0, true, p1) && all_right; // ------------------ } { // ----- test 3 ----- string t0[] = {"?" "?5?","?" "?9","?4","6"}; p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); string t1[] = {"7054","759","24","6"}; p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0])); all_right = KawigiEdit_RunTest(3, p0, true, p1) && all_right; // ------------------ } if (all_right) { cout << "You're a stud (at least on the example cases)!" << endl; } else { cout << "Some of the test cases had errors." << endl; } return 0; } // PROBLEM STATEMENT // // Suppose there is a triangle of digits like the following: // // 74932 // 1325 // 457 // 92 // 1 // // Each digit, with the exception of those in the top row, is equal to the last digit of the sum of // its upper and upper-right neighboring digits. // // // You will be given a vector <string> questionMarkTriangle containing a triangle where // only one digit in each row is known and all others are represented by '?'s // (see example 0 for clarification). // Each element of questionMarkTriangle represents a row of the triangle, and the rows are given // from top to bottom. Each element contains exactly one digit ('0'-'9') and // the remaining characters are all '?'s. Restore the triangle and return it as a // vector <string> without '?'s. // // // // DEFINITION // Class:RevealTriangle // Method:calcTriangle // Parameters:vector <string> // Returns:vector <string> // Method signature:vector <string> calcTriangle(vector <string> questionMarkTriangle) // // // CONSTRAINTS // -questionMarkTriangle will contain between 1 and 50 elements, inclusive. // -Element i (0 indexed) of questionMarkTriangle will contain exactly n-i characters, where n is the number of elements in questionMarkTriangle. // -Each element of questionMarkTriangle will contain exactly one digit ('0'-'9') and all others characters will be '?'s. // // // EXAMPLES // // 0) // {"4??", // "?2", // "1"} // // Returns: {"457", "92", "1" } // // Let's substitute '?'s with unknown variables: // // 4ab // c2 // 1 // // // Having done that, we start solving for the variables from the bottom to the top. First, we know that the last digit of (c + 2) is 1. Therefore, c must be 9: // // // 4ab // 92 // 1 // // Now we know that the last digit of (4 + a) is 9, which means a is 5: // // 45b // 92 // 1 // // // And, finally, the last digit of (5 + b) is 2, so b is 7. // // 1) // {"1"} // // Returns: {"1" } // // 2) // {"???2", "??2", "?2", "2"} // // Returns: {"0002", "002", "02", "2" } // // 3) // {"??5?", "??9", "?4", "6"} // // Returns: {"7054", "759", "24", "6" } // // END KAWIGIEDIT TESTING //Powered by KawigiEdit 2.1.8 (beta) modified by pivanof!
[ "abhiranjan.kumar00@gmail.com" ]
abhiranjan.kumar00@gmail.com
53326e1a768a9d9e4ee6c44d2eead112cc100720
d06a58d6641477569f016f675cd82100fb53e2d3
/AsyncUDPClient_RelayUnit/AsyncUDPClient_RelayUnit.ino
d02000d2654b044ed3b53f98872be2ca8e5b3a93
[]
no_license
pestunov/domesticStick
edf8175c68cafb00649b781d14a796e2fd0c6046
53dca1397e9b6e169e3acb29caf5d7d115668742
refs/heads/master
2021-06-16T03:17:06.299476
2021-04-21T14:48:35
2021-04-21T14:48:35
192,478,793
1
0
null
null
null
null
UTF-8
C++
false
false
5,501
ino
/* * Base: ESP32 * module intend for transport data * in: UDP module --> out: I/O ports * * received data format * "unit#001.12.1" * * uses: * WiFi ver 1.2.7 by Arduino * */ #include <WiFi.h> #include <WiFiUdp.h> #include "/home/pi/secure.h" //#include "D:/1_Projects/secure.h" #define CYCLE_MAX 200 #define UNIT_NAME "UNIT001" String unitName, tempStr; const char* ssid = SECURE_SSID; //secure.h #define SECURE_SSID = "my_ssid12345" const char* password = SECURE_PASSWORD; //secure.h const char* udpAddress = "192.168.001.255"; // a network broadcast address const int udpPort = 3334; enum { JUST_CONNECTED, CONNECTED, DISCONNECTED, DISCON_TRIED } wifiState; char packetBuffer[1000]; // buffer to hold incoming packet boolean tag; int parseCounter; int cycle_counter = 0; char my_status, my_tasks, parsePort, parseState; WiFiUDP udp; // udp library class int relayPins[] = {0, 4, 17, 2000}; // an array of port to which relay are attached int statePins[] = {0, 0, 0}; // init state of pins int pinCount = 3; void setup(){ unitName = String(UNIT_NAME); setPins(); // initialize digital pins Serial.begin(115200); // serial port for status monitoring wifiState = DISCONNECTED; //Connect to the WiFi network connectToWiFi(ssid, password); } // setup void loop() { for(int cycle_counter = 0; cycle_counter < CYCLE_MAX; cycle_counter++){ delay(10); if ((cycle_counter == 10) && (wifiState == JUST_CONNECTED)){ //only send data when connected wifiState = CONNECTED; tempStr = unitName + " started!"; udp.beginPacket(udp.remoteIP(), udp.remotePort()); udp.print(tempStr); udp.endPacket(); } if ((cycle_counter == 12) && (wifiState == CONNECTED)){ //only send data when connected udp.beginPacket(udpAddress,udpPort); udp.print(unitName); udp.printf(" still here %lu", millis()/1000); udp.endPacket(); } if ((cycle_counter == 20) && (wifiState == DISCON_TRIED)){ // try to reconnect wifiState = DISCONNECTED; connectToWiFi(ssid, password); } if ((cycle_counter == 30) && (wifiState == DISCONNECTED)){ // still alife Serial.print('.'); } if (cycle_counter == 100){ continue; } unsigned int packetSize = udp.parsePacket(); if (packetSize) { unsigned int len = udp.read(packetBuffer, 255); if (len > 0) { packetBuffer[len] = 0; } String tStr = String(packetBuffer); tStr.trim(); tStr.toUpperCase(); Serial.println(tStr); int nnn = parseCommand(tStr); if (nnn == 0){ // packet acknowleged // send a reply, to the IP address and port that sent us the packet we received tempStr = unitName + " done!"; udp.beginPacket(udp.remoteIP(), udp.remotePort()); udp.print(tempStr); udp.endPacket(); } } setPins(); } // for } // loop void connectToWiFi(const char * ssid, const char * pwd){ Serial.println("Connecting to WiFi network: " + String(ssid)); WiFi.disconnect(true); // delete old config wifiState = DISCONNECTED; WiFi.onEvent(WiFiEvent); //register event handler WiFi.begin(ssid, pwd); //Initiate connection Serial.println("Waiting for WIFI connection..."); } //wifi event handler void WiFiEvent(WiFiEvent_t event){ switch(event) { case SYSTEM_EVENT_STA_GOT_IP: //When connected set Serial.print("WiFi connected! IP address: "); Serial.println(WiFi.localIP()); //initializes the UDP state //This initializes the transfer buffer udp.begin(WiFi.localIP(),udpPort); wifiState = JUST_CONNECTED; break; case SYSTEM_EVENT_STA_DISCONNECTED: Serial.println("WiFi lost connection"); wifiState = DISCON_TRIED; break; default: break; } } int parseCommand(String strr){ unsigned int len = strr.length(); unsigned int minLen = unitName.length()+2; if (len < minLen){ return 1; } if (not strr.startsWith(unitName)){ return 2; } // todo: add service command [sendStatus, setData, getData, setKey, getKey] int firstDot = strr.indexOf(".",unitName.length()); int secondDot = strr.indexOf(".", firstDot+1); String sstr1 = strr.substring(firstDot+1,secondDot); String sstr2= strr.substring(secondDot+1); unsigned int addr = sstr1.toInt(); int value = sstr2.toInt(); Serial.print("Address: "); Serial.print(addr); Serial.print(", Value: "); Serial.println(value); if (addr > pinCount){ return 3; } statePins[addr] = value; return 0; } void sendUDP(String strr, const char * udpAddress, int udpPort){ udp.beginPacket(udpAddress, udpPort); udp.print(strr); udp.endPacket(); } /*void sendParsingStatus(int n, String tStr){ Serial.print("N = "); Serial.print(n); Serial.print("; String = "); Serial.println(tStr); } */ /* Serial.print("Received packet of size "); Serial.println(packetSize); IPAddress remoteIp = udp.remoteIP(); Serial.print("From "); Serial.print(remoteIp); Serial.print(", port "); Serial.println(udp.remotePort()); read the packet into packetBufffer */ void setPins(){ for (int pin = 1; pin < pinCount; pin++) { if (relayPins[pin] >= 1000){ break; } digitalWrite(relayPins[pin], (statePins[pin]==1)? HIGH : LOW); // turn the port off pinMode(relayPins[pin], OUTPUT); // pin as output } }
[ "pestuno@gmail.com" ]
pestuno@gmail.com
ae56fcfd4e3ad2ef02e3144e597686d8f4d63213
da1aa824deb8d7d7416151601e662629765780f0
/Seg3D/src/Packages/CardioWaveInterface/Core/XML/SynapseXML.h
6475e41f871d8bd715f7739c8d63b3518cd9b472
[ "MIT" ]
permissive
viscenter/educe
69b5402782a4455af6d4009cb69f0d9a47042095
2dca76e7def3e0620896f155af64f6ba84163d77
refs/heads/master
2021-01-02T22:44:36.560170
2009-06-12T15:16:15
2009-06-12T15:16:15
5,413,435
1
0
null
null
null
null
UTF-8
C++
false
false
1,966
h
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2004 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef PACAKGES_CARDIOWAVE_CORE_XML_SYNAPSE_H #define PACAKGES_CARDIOWAVE_CORE_XML_SYNAPSE_H 1 #include <string> #include <list> namespace CardioWaveInterface { class SynapseItem { public: std::string synapsename; std::string nodetype; std::string sourcefile; std::string parameters; std::string description; }; typedef std::vector<SynapseItem> SynapseList; class SynapseXML { public: SynapseXML(); std::string get_default_name(); std::vector<std::string> get_names(); SynapseItem get_synapse(std::string name); private: bool parse_xml_files(); bool add_file(std::string filename); std::string default_name_; SynapseList list_; }; } #endif
[ "ryan.baumann@gmail.com" ]
ryan.baumann@gmail.com
10bbf3e4bcc0c8492d384c5d1b41fa14adb41f17
1f63dde39fcc5f8be29f2acb947c41f1b6f1683e
/Boss2D/addon/_old/tesseract-3.04.01_for_boss/classify/trainingsample.cpp
1fd1222a6b544292f21a878d5164201fce44493b
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
koobonil/Boss2D
09ca948823e0df5a5a53b64a10033c4f3665483a
e5eb355b57228a701495f2660f137bd05628c202
refs/heads/master
2022-10-20T09:02:51.341143
2019-07-18T02:13:44
2019-07-18T02:13:44
105,999,368
7
2
MIT
2022-10-04T23:31:12
2017-10-06T11:57:07
C++
UTF-8
C++
false
false
14,166
cpp
// Copyright 2010 Google Inc. All Rights Reserved. // Author: rays@google.com (Ray Smith) // // 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 automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #include BOSS_TESSERACT_U_trainingsample_h //original-code:"trainingsample.h" #include <math.h> #include BOSS_OPENALPR_U_allheaders_h //original-code:"allheaders.h" #include BOSS_TESSERACT_U_helpers_h //original-code:"helpers.h" #include "intfeaturemap.h" #include "normfeat.h" #include BOSS_TESSERACT_U_shapetable_h //original-code:"shapetable.h" namespace tesseract { ELISTIZE(TrainingSample) // Center of randomizing operations. const int kRandomizingCenter = 128; // Randomizing factors. const int TrainingSample::kYShiftValues[kSampleYShiftSize] = { 6, 3, -3, -6, 0 }; const double TrainingSample::kScaleValues[kSampleScaleSize] = { 1.0625, 0.9375, 1.0 }; TrainingSample::~TrainingSample() { delete [] features_; delete [] micro_features_; } // WARNING! Serialize/DeSerialize do not save/restore the "cache" data // members, which is mostly the mapped features, and the weight. // It is assumed these can all be reconstructed from what is saved. // Writes to the given file. Returns false in case of error. bool TrainingSample::Serialize(FILE* fp) const { if (fwrite(&class_id_, sizeof(class_id_), 1, fp) != 1) return false; if (fwrite(&font_id_, sizeof(font_id_), 1, fp) != 1) return false; if (fwrite(&page_num_, sizeof(page_num_), 1, fp) != 1) return false; if (!bounding_box_.Serialize(fp)) return false; if (fwrite(&num_features_, sizeof(num_features_), 1, fp) != 1) return false; if (fwrite(&num_micro_features_, sizeof(num_micro_features_), 1, fp) != 1) return false; if (fwrite(&outline_length_, sizeof(outline_length_), 1, fp) != 1) return false; if (static_cast<int>(fwrite(features_, sizeof(*features_), num_features_, fp)) != num_features_) return false; if (static_cast<int>(fwrite(micro_features_, sizeof(*micro_features_), num_micro_features_, fp)) != num_micro_features_) return false; if (fwrite(cn_feature_, sizeof(*cn_feature_), kNumCNParams, fp) != kNumCNParams) return false; if (fwrite(geo_feature_, sizeof(*geo_feature_), GeoCount, fp) != GeoCount) return false; return true; } // Creates from the given file. Returns NULL in case of error. // If swap is true, assumes a big/little-endian swap is needed. TrainingSample* TrainingSample::DeSerializeCreate(bool swap, FILE* fp) { TrainingSample* sample = new TrainingSample; if (sample->DeSerialize(swap, fp)) return sample; delete sample; return NULL; } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool TrainingSample::DeSerialize(bool swap, FILE* fp) { if (fread(&class_id_, sizeof(class_id_), 1, fp) != 1) return false; if (fread(&font_id_, sizeof(font_id_), 1, fp) != 1) return false; if (fread(&page_num_, sizeof(page_num_), 1, fp) != 1) return false; if (!bounding_box_.DeSerialize(swap, fp)) return false; if (fread(&num_features_, sizeof(num_features_), 1, fp) != 1) return false; if (fread(&num_micro_features_, sizeof(num_micro_features_), 1, fp) != 1) return false; if (fread(&outline_length_, sizeof(outline_length_), 1, fp) != 1) return false; if (swap) { ReverseN(&class_id_, sizeof(class_id_)); ReverseN(&num_features_, sizeof(num_features_)); ReverseN(&num_micro_features_, sizeof(num_micro_features_)); ReverseN(&outline_length_, sizeof(outline_length_)); } delete [] features_; features_ = new INT_FEATURE_STRUCT[num_features_]; if (static_cast<int>(fread(features_, sizeof(*features_), num_features_, fp)) != num_features_) return false; delete [] micro_features_; micro_features_ = new MicroFeature[num_micro_features_]; if (static_cast<int>(fread(micro_features_, sizeof(*micro_features_), num_micro_features_, fp)) != num_micro_features_) return false; if (fread(cn_feature_, sizeof(*cn_feature_), kNumCNParams, fp) != kNumCNParams) return false; if (fread(geo_feature_, sizeof(*geo_feature_), GeoCount, fp) != GeoCount) return false; return true; } // Saves the given features into a TrainingSample. TrainingSample* TrainingSample::CopyFromFeatures( const INT_FX_RESULT_STRUCT& fx_info, const TBOX& bounding_box, const INT_FEATURE_STRUCT* features, int num_features) { TrainingSample* sample = new TrainingSample; sample->num_features_ = num_features; sample->features_ = new INT_FEATURE_STRUCT[num_features]; sample->outline_length_ = fx_info.Length; memcpy(sample->features_, features, num_features * sizeof(features[0])); sample->geo_feature_[GeoBottom] = bounding_box.bottom(); sample->geo_feature_[GeoTop] = bounding_box.top(); sample->geo_feature_[GeoWidth] = bounding_box.width(); // Generate the cn_feature_ from the fx_info. sample->cn_feature_[CharNormY] = MF_SCALE_FACTOR * (fx_info.Ymean - kBlnBaselineOffset); sample->cn_feature_[CharNormLength] = MF_SCALE_FACTOR * fx_info.Length / LENGTH_COMPRESSION; sample->cn_feature_[CharNormRx] = MF_SCALE_FACTOR * fx_info.Rx; sample->cn_feature_[CharNormRy] = MF_SCALE_FACTOR * fx_info.Ry; sample->features_are_indexed_ = false; sample->features_are_mapped_ = false; return sample; } // Returns the cn_feature as a FEATURE_STRUCT* needed by cntraining. FEATURE_STRUCT* TrainingSample::GetCNFeature() const { FEATURE feature = NewFeature(&CharNormDesc); for (int i = 0; i < kNumCNParams; ++i) feature->Params[i] = cn_feature_[i]; return feature; } // Constructs and returns a copy randomized by the method given by // the randomizer index. If index is out of [0, kSampleRandomSize) then // an exact copy is returned. TrainingSample* TrainingSample::RandomizedCopy(int index) const { TrainingSample* sample = Copy(); if (index >= 0 && index < kSampleRandomSize) { ++index; // Remove the first combination. int yshift = kYShiftValues[index / kSampleScaleSize]; double scaling = kScaleValues[index % kSampleScaleSize]; for (int i = 0; i < num_features_; ++i) { double result = (features_[i].X - kRandomizingCenter) * scaling; result += kRandomizingCenter; sample->features_[i].X = ClipToRange(static_cast<int>(result + 0.5), 0, MAX_UINT8); result = (features_[i].Y - kRandomizingCenter) * scaling; result += kRandomizingCenter + yshift; sample->features_[i].Y = ClipToRange(static_cast<int>(result + 0.5), 0, MAX_UINT8); } } return sample; } // Constructs and returns an exact copy. TrainingSample* TrainingSample::Copy() const { TrainingSample* sample = new TrainingSample; sample->class_id_ = class_id_; sample->font_id_ = font_id_; sample->weight_ = weight_; sample->sample_index_ = sample_index_; sample->num_features_ = num_features_; if (num_features_ > 0) { sample->features_ = new INT_FEATURE_STRUCT[num_features_]; memcpy(sample->features_, features_, num_features_ * sizeof(features_[0])); } sample->num_micro_features_ = num_micro_features_; if (num_micro_features_ > 0) { sample->micro_features_ = new MicroFeature[num_micro_features_]; memcpy(sample->micro_features_, micro_features_, num_micro_features_ * sizeof(micro_features_[0])); } memcpy(sample->cn_feature_, cn_feature_, sizeof(*cn_feature_) * kNumCNParams); memcpy(sample->geo_feature_, geo_feature_, sizeof(*geo_feature_) * GeoCount); return sample; } // Extracts the needed information from the CHAR_DESC_STRUCT. void TrainingSample::ExtractCharDesc(int int_feature_type, int micro_type, int cn_type, int geo_type, CHAR_DESC_STRUCT* char_desc) { // Extract the INT features. if (features_ != NULL) delete [] features_; FEATURE_SET_STRUCT* char_features = char_desc->FeatureSets[int_feature_type]; if (char_features == NULL) { tprintf("Error: no features to train on of type %s\n", kIntFeatureType); num_features_ = 0; features_ = NULL; } else { num_features_ = char_features->NumFeatures; features_ = new INT_FEATURE_STRUCT[num_features_]; for (int f = 0; f < num_features_; ++f) { features_[f].X = static_cast<uinT8>(char_features->Features[f]->Params[IntX]); features_[f].Y = static_cast<uinT8>(char_features->Features[f]->Params[IntY]); features_[f].Theta = static_cast<uinT8>(char_features->Features[f]->Params[IntDir]); features_[f].CP_misses = 0; } } // Extract the Micro features. if (micro_features_ != NULL) delete [] micro_features_; char_features = char_desc->FeatureSets[micro_type]; if (char_features == NULL) { tprintf("Error: no features to train on of type %s\n", kMicroFeatureType); num_micro_features_ = 0; micro_features_ = NULL; } else { num_micro_features_ = char_features->NumFeatures; micro_features_ = new MicroFeature[num_micro_features_]; for (int f = 0; f < num_micro_features_; ++f) { for (int d = 0; d < MFCount; ++d) { micro_features_[f][d] = char_features->Features[f]->Params[d]; } } } // Extract the CN feature. char_features = char_desc->FeatureSets[cn_type]; if (char_features == NULL) { tprintf("Error: no CN feature to train on.\n"); } else { ASSERT_HOST(char_features->NumFeatures == 1); cn_feature_[CharNormY] = char_features->Features[0]->Params[CharNormY]; cn_feature_[CharNormLength] = char_features->Features[0]->Params[CharNormLength]; cn_feature_[CharNormRx] = char_features->Features[0]->Params[CharNormRx]; cn_feature_[CharNormRy] = char_features->Features[0]->Params[CharNormRy]; } // Extract the Geo feature. char_features = char_desc->FeatureSets[geo_type]; if (char_features == NULL) { tprintf("Error: no Geo feature to train on.\n"); } else { ASSERT_HOST(char_features->NumFeatures == 1); geo_feature_[GeoBottom] = char_features->Features[0]->Params[GeoBottom]; geo_feature_[GeoTop] = char_features->Features[0]->Params[GeoTop]; geo_feature_[GeoWidth] = char_features->Features[0]->Params[GeoWidth]; } features_are_indexed_ = false; features_are_mapped_ = false; } // Sets the mapped_features_ from the features_ using the provided // feature_space to the indexed versions of the features. void TrainingSample::IndexFeatures(const IntFeatureSpace& feature_space) { GenericVector<int> indexed_features; feature_space.IndexAndSortFeatures(features_, num_features_, &mapped_features_); features_are_indexed_ = true; features_are_mapped_ = false; } // Sets the mapped_features_ from the features using the provided // feature_map. void TrainingSample::MapFeatures(const IntFeatureMap& feature_map) { GenericVector<int> indexed_features; feature_map.feature_space().IndexAndSortFeatures(features_, num_features_, &indexed_features); feature_map.MapIndexedFeatures(indexed_features, &mapped_features_); features_are_indexed_ = false; features_are_mapped_ = true; } // Returns a pix representing the sample. (Int features only.) Pix* TrainingSample::RenderToPix(const UNICHARSET* unicharset) const { Pix* pix = pixCreate(kIntFeatureExtent, kIntFeatureExtent, 1); for (int f = 0; f < num_features_; ++f) { int start_x = features_[f].X; int start_y = kIntFeatureExtent - features_[f].Y; double dx = cos((features_[f].Theta / 256.0) * 2.0 * PI - PI); double dy = -sin((features_[f].Theta / 256.0) * 2.0 * PI - PI); for (int i = 0; i <= 5; ++i) { int x = static_cast<int>(start_x + dx * i); int y = static_cast<int>(start_y + dy * i); if (x >= 0 && x < 256 && y >= 0 && y < 256) pixSetPixel(pix, x, y, 1); } } if (unicharset != NULL) pixSetText(pix, unicharset->id_to_unichar(class_id_)); return pix; } // Displays the features in the given window with the given color. void TrainingSample::DisplayFeatures(ScrollView::Color color, ScrollView* window) const { #ifndef GRAPHICS_DISABLED for (int f = 0; f < num_features_; ++f) { RenderIntFeature(window, &features_[f], color); } #endif // GRAPHICS_DISABLED } // Returns a pix of the original sample image. The pix is padded all round // by padding wherever possible. // The returned Pix must be pixDestroyed after use. // If the input page_pix is NULL, NULL is returned. Pix* TrainingSample::GetSamplePix(int padding, Pix* page_pix) const { if (page_pix == NULL) return NULL; int page_width = pixGetWidth(page_pix); int page_height = pixGetHeight(page_pix); TBOX padded_box = bounding_box(); padded_box.pad(padding, padding); // Clip the padded_box to the limits of the page TBOX page_box(0, 0, page_width, page_height); padded_box &= page_box; Box* box = boxCreate(page_box.left(), page_height - page_box.top(), page_box.width(), page_box.height()); Pix* sample_pix = pixClipRectangle(page_pix, box, NULL); boxDestroy(&box); return sample_pix; } } // namespace tesseract
[ "slacealic@gmail.com" ]
slacealic@gmail.com
fd2f9b8862ecfa693a6a6f426f672bd93231eeaa
5c66dee85161f46ebb3a1d300189e54b15919fba
/colorsensor/colorsensor.ino
7d22399390071142190a0415251be2007cd7af0c
[]
no_license
rajneeshkatkam/Colour-Detection-For-Visually-Impaired
58fb27cb12db0878588c69172ccc231bd225d8cc
f20a196110411c4a5eb82b0fb181cb7c23b1996c
refs/heads/main
2023-06-03T09:21:49.156887
2021-06-09T22:35:25
2021-06-09T22:35:25
375,505,425
0
0
null
null
null
null
UTF-8
C++
false
false
2,086
ino
#include <ESP8266WiFi.h> const char* ssid = "Bqil-cmFqbmVlc2g"; const char* password = "rajneesh97"; int ledPin = D5; WiFiServer server(80); void setup() { Serial.begin(115200); delay(10); pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW); // Connect to WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); // Start the server server.begin(); Serial.println("Server started"); // Print the IP address Serial.print("Use this URL : "); Serial.print("http://"); Serial.print(WiFi.localIP()); Serial.println("/"); } void loop() { // Check if a client has connected WiFiClient client = server.available(); if (!client) { return; } // Wait until the client sends some data Serial.println("new client"); while(!client.available()){ delay(1); } // Read the first line of the request String request = client.readStringUntil('\r'); Serial.println(request); client.flush(); // Match the request int value = LOW; if (request.indexOf("/LED=ON") != -1) { digitalWrite(ledPin, HIGH); value = HIGH; } if (request.indexOf("/LED=OFF") != -1){ digitalWrite(ledPin, LOW); value = LOW; } // Return the response client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(""); // do not forget this one client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.print("Led pin is now: "); if(value == HIGH) { client.print("On"); } else { client.print("Off"); } client.println("<br><br>"); client.println("Click <a href=\"/LED=ON\">here</a> turn the LED on pin 5 ON<br>"); client.println("Click <a href=\"/LED=OFF\">here</a> turn the LED on pin 5 OFF<br>"); client.println("</html>"); delay(1); Serial.println("Client disconnected"); Serial.println(""); }
[ "rajneesh.katkam@gmail.com" ]
rajneesh.katkam@gmail.com
44b2acb57b9b3b8ed91c234a3f2119b8c436ed01
a900cd6218dec5205a9ef013d966f21535ea981c
/zoj/dp/pack_2156.cpp
4120d4e2670811e79bd8aab382d67ced0a9ba72d
[]
no_license
bradelement/coding_exercise
686d56518d42b9de53d97c05d4727876a64592cf
1d162674e29ca1344a21d4d5d79f487945f288de
refs/heads/master
2020-12-25T17:35:38.456061
2017-03-01T08:18:58
2017-03-01T08:18:58
17,633,022
0
0
null
null
null
null
UTF-8
C++
false
false
1,918
cpp
#include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int inf = 0x12345678; const int MAX_VALUE = 10001; int V; int coins[5]; int values[5] = {0, 1, 5, 10, 25}; int dp[MAX_VALUE]; int rec[5][MAX_VALUE]; void ZeroOnePack(int ind, int F, int C, int W) { F = min(F, V); for (int v=F; v>=C; v--) { if (dp[v-C] != -inf && dp[v-C]+W > dp[v]) { dp[v] = dp[v-C]+W; rec[ind][v] += rec[ind][v-C]+W; } } } void CompletePack(int ind, int F, int C, int W) { F = min(F, V); for (int v=C; v<=F; v++) { if (dp[v-C] != -inf && dp[v-C]+W > dp[v]) { dp[v] = dp[v-C]+W; rec[ind][v] = rec[ind][v-C] + W; } } } void MultiPack(int ind, int F, int C, int W, int M) { if (C*M >= F) { CompletePack(ind, F, C, W); return; } int k = 1; while (k < M) { ZeroOnePack(ind, F, k*C, k*W); M -= k; k *= 2; } ZeroOnePack(ind, F, M*C, M*W); } void gao() { memset(dp, 0, sizeof(dp)); memset(rec, 0, sizeof(rec)); for (int j=1; j<=V; j++) { dp[j] = -inf; } for (int i=1; i<=4; i++) { MultiPack(i, V, values[i], 1, coins[i]); } if (dp[V] <= 0) { printf("Charlie cannot buy coffee.\n"); return; } //printf("dp[%d] is %d\n", V, dp[V]); int ans[5]; int v = V; for (int i=4; i>=1; i--) { ans[i] = rec[i][v]; //printf("rec[%d][%d] is %d\n", i, v, rec[i][v]); v -= ans[i] * values[i]; } printf("Throw in %d cents, %d nickels, %d dimes, and %d quarters.\n", ans[1], ans[2], ans[3], ans[4]); } int main(int argc, char const *argv[]) { while (~scanf("%d", &V)) { for (int i=1; i<=4; i++) { scanf("%d", &coins[i]); } if (V+coins[1]+coins[2]+coins[3]+coins[4] == 0) break; gao(); } return 0; }
[ "bradelementzju@gmail.com" ]
bradelementzju@gmail.com
4d56ffaf1bdca790a1b9b150bb2408e776fafa59
e1b7454c1aa244fd508354c988a11f790ab1b4b6
/project/src/Mod/ReverseEngineering/App/ApproxSurface.h
c9be27eafa4edd5661e5e3aa90b95f4d9ab5a3d8
[]
no_license
tralondong/FreeCad-McCad
3268aa8f78e86f8dd14051406cebc447a75a722d
b9756ccfb27bd1f33da2b42a09cbcda33000460e
refs/heads/master
2020-04-16T23:00:40.538516
2018-09-21T17:57:23
2018-09-21T17:57:23
165,994,482
1
0
null
null
null
null
UTF-8
C++
false
false
17,776
h
/*************************************************************************** * Copyright (c) 2008 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library 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; either * * version 2 of the License, or (at your option) any later version. * * * * This library 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 Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #ifndef REEN_APPROXSURFACE_H #define REEN_APPROXSURFACE_H #include <TColStd_Array1OfReal.hxx> #include <TColStd_Array1OfInteger.hxx> #include <TColgp_Array1OfPnt.hxx> #include <TColgp_Array2OfPnt.hxx> #include <TColgp_Array1OfPnt2d.hxx> #include <Handle_Geom_BSplineSurface.hxx> #include <math_Matrix.hxx> #include <Base/Vector3D.h> namespace Base { class SequencerLauncher; } // TODO: Replace OCC stuff with ublas & co namespace Reen { class ReenExport SplineBasisfunction { public: enum ValueT { Zero = 0, Full, Other }; /** * Konstruktor * @param iSize Length of Knots vector */ SplineBasisfunction(int iSize); /** * Konstruktor * @param vKnots Knotenvektor * @param iOrder Ordnung (Grad+1) des Basis-Polynoms */ SplineBasisfunction(TColStd_Array1OfReal& vKnots, int iOrder=1); /** * Konstruktor * @param vKnots Knotenvektor der Form (Wert) * @param vMults Knotenvektor der Form (Vielfachheit) * @param iSize Laenge des Knotenvektors * Die Arrays @a vKnots und @a vMults muessen die gleiche besitzen und die Summe der Werte in @a vMults * muss identisch mit @a iSize sein. * @param iOrder Ordnung (Grad+1) des Basis-Polynoms */ SplineBasisfunction(TColStd_Array1OfReal& vKnots, TColStd_Array1OfInteger& vMults, int iSize, int iOrder=1); virtual ~SplineBasisfunction(); /** * Gibt an, ob der Funktionswert Nik(t) an der Stelle fParam * 0, 1 oder ein Wert dazwischen ergibt. * Dies dient dazu, um die Berechnung zu u.U. zu beschleunigen. * * @param iIndex Index * @param fParam Parameterwert * @return ValueT */ virtual ValueT LocalSupport(int iIndex, double fParam)=0; /** * Berechnet den Funktionswert Nik(t) an der Stelle fParam * (aus: Piegl/Tiller 96 The NURBS-Book) * * @param iIndex Index * @param fParam Parameterwert * @return Funktionswert Nik(t) */ virtual double BasisFunction(int iIndex, double fParam)=0; /** * Berechnet die Funktionswerte der ersten iMaxDer Ableitungen an der * Stelle fParam (aus: Piegl/Tiller 96 The NURBS-Book) * * @param iIndex Index * @param iMaxDer max. Ableitung * @param fParam Parameterwert. * @return Derivat Liste der Funktionswerte * * Die Liste muss fuer iMaxDer+1 Elemente ausreichen. */ virtual void DerivativesOfBasisFunction(int iIndex, int iMaxDer, double fParam, TColStd_Array1OfReal& Derivat)=0; /** * Berechnet die k-te Ableitung an der Stelle fParam */ virtual double DerivativeOfBasisFunction(int iIndex, int k, double fParam)=0; /** * Setzt den Knotenvektor und die Ordnung fest. Die Groesse des Knotenvektors muss exakt so gross sein, * wie im Konstruktor festgelegt. */ virtual void SetKnots(TColStd_Array1OfReal& vKnots, int iOrder=1); /** * Setzt den Knotenvektor und die Ordnung fest. uebergeben wird der Knotenvektor der Form * (Wert, Vielfachheit). Intern wird dieser in einen Knotenvektor der Form (Wert,1) * umgerechnet. Die Groesse dieses neuen Vektors muss exakt so gross sein, wie im Konstruktor * festgelegt. */ virtual void SetKnots(TColStd_Array1OfReal& vKnots, TColStd_Array1OfInteger& vMults, int iOrder=1); protected: //Member // Knotenvektor TColStd_Array1OfReal _vKnotVector; // Ordnung (=Grad+1) int _iOrder; }; class ReenExport BSplineBasis : public SplineBasisfunction { public: /** * Konstruktor * @param iSize Laenge des Knotenvektors */ BSplineBasis(int iSize); /** * Konstruktor * @param vKnots Knotenvektor * @param iOrder Ordnung (Grad+1) des Basis-Polynoms */ BSplineBasis(TColStd_Array1OfReal& vKnots, int iOrder=1); /** * Konstruktor * @param vKnots Knotenvektor der Form (Wert) * @param vMults Knotenvektor der Form (Vielfachheit) * @param iSize Laenge des Knotenvektors * Die Arrays @a vKnots und @a vMults muessen die gleiche besitzen und die Summe der Werte in @a vMults * muss identisch mit @a iSize sein. * @param iOrder Ordnung (Grad+1) des Basis-Polynoms */ BSplineBasis(TColStd_Array1OfReal& vKnots, TColStd_Array1OfInteger& vMults, int iSize, int iOrder=1); /** * Bestimmt den Knotenindex zum Parameterwert (aus: Piegl/Tiller 96 The NURBS-Book) * @param fParam Parameterwert * @return Knotenindex */ virtual int FindSpan(double fParam); /** * Berechnet die Funktionswerte der an der Stelle fParam * nicht verschwindenden Basisfunktionen. Es muss darauf geachtet werden, dass * die Liste fuer d(=Grad des B-Splines) Elemente (0,...,d-1) ausreicht. * (aus: Piegl/Tiller 96 The NURBS-Book) * @param fParam Parameter * @param vFuncVals Liste der Funktionswerte * Index, Parameterwert */ virtual void AllBasisFunctions(double fParam, TColStd_Array1OfReal& vFuncVals); /** * Gibt an, ob der Funktionswert Nik(t) an der Stelle fParam * 0, 1 oder ein Wert dazwischen ergibt. * Dies dient dazu, um die Berechnung zu u.U. zu beschleunigen. * * @param iIndex Index * @param fParam Parameterwert * @return ValueT */ virtual ValueT LocalSupport(int iIndex, double fParam); /** * Berechnet den Funktionswert Nik(t) an der Stelle fParam * (aus: Piegl/Tiller 96 The NURBS-Book) * @param iIndex Index * @param fParam Parameterwert * @return Funktionswert Nik(t) */ virtual double BasisFunction(int iIndex, double fParam); /** * Berechnet die Funktionswerte der ersten iMaxDer Ableitungen an der Stelle fParam * (aus: Piegl/Tiller 96 The NURBS-Book) * @param iIndex Index * @param iMaxDer max. Ableitung * @param fParam Parameterwert. * @param Derivat * Die Liste muss fuer iMaxDer+1 Elemente ausreichen. * @return Liste der Funktionswerte */ virtual void DerivativesOfBasisFunction(int iIndex, int iMaxDer, double fParam, TColStd_Array1OfReal& Derivat); /** * Berechnet die k-te Ableitung an der Stelle fParam */ virtual double DerivativeOfBasisFunction(int iIndex, int k, double fParam); /** * Berechnet das Integral des Produkts zweier B-Splines bzw. deren Ableitungen. * Der Integrationsbereich erstreckt sich ueber den ganzen Definitionsbereich. * Berechnet wird das Integral mittels der Gauss'schen Quadraturformeln. */ virtual double GetIntegralOfProductOfBSplines(int i, int j, int r, int s); /** * Destruktor */ virtual~ BSplineBasis(); protected: /** * Berechnet die Nullstellen der Legendre-Polynome und die * zugehoerigen Gewichte */ virtual void GenerateRootsAndWeights(TColStd_Array1OfReal& vAbscissas, TColStd_Array1OfReal& vWeights); /** * Berechnet die Integrationsgrenzen (Indexe der Knoten) */ virtual void FindIntegrationArea(int iIdx1, int iIdx2, int& iBegin, int& iEnd); /** * Berechnet in Abhaengigkeit vom Grad die Anzahl der zu verwendenden Nullstellen/Gewichte * der Legendre-Polynome */ int CalcSize(int r, int s); }; class ReenExport ParameterCorrection { public: // Konstruktor ParameterCorrection(unsigned usUOrder=4, //Ordnung in u-Richtung (Ordnung=Grad+1) unsigned usVOrder=4, //Ordnung in v-Richtung unsigned usUCtrlpoints=6, //Anz. der Kontrollpunkte in u-Richtung unsigned usVCtrlpoints=6); //Anz. der Kontrollpunkte in v-Richtung virtual ~ParameterCorrection() { delete _pvcPoints; delete _pvcUVParam; } protected: /** * Berechnet die Eigenvektoren der Kovarianzmatrix */ virtual void CalcEigenvectors(); /** * Projiziert die Kontrollpunkte auf die Fit-Ebene */ void ProjectControlPointsOnPlane(); /** * Berechnet eine initiale Flaeche zu Beginn des Algorithmus. Dazu wird die Ausgleichsebene zu der * Punktwolke berechnet. * Die Punkte werden bzgl. der Basis bestehend aus den Eigenvektoren der Kovarianzmatrix berechnet und * auf die Ausgleichsebene projiziert. Von diesen Punkten wird die Boundingbox berechnet, dann werden * die u/v-Parameter fuer die Punkte berechnet. */ virtual bool DoInitialParameterCorrection(double fSizeFactor=0.0f); /** * Berechnet die u.v-Werte der Punkte */ virtual bool GetUVParameters(double fSizeFactor); /** * Fuehrt eine Parameterkorrektur durch. */ virtual void DoParameterCorrection(int iIter)=0; /** * Loest Gleichungssystem */ virtual bool SolveWithoutSmoothing()=0; /** * Loest ein regulaeres Gleichungssystem */ virtual bool SolveWithSmoothing(double fWeight)=0; public: /** * Berechnet eine B-Spline-Flaeche.aus den geg. Punkten */ virtual Handle_Geom_BSplineSurface CreateSurface(const TColgp_Array1OfPnt& points, int iIter, bool bParaCor, double fSizeFactor=0.0f); /** * Setzen der u/v-Richtungen * Dritter Parameter gibt an, ob die Richtungen tatsaechlich verwendet werden sollen. */ virtual void SetUV(const Base::Vector3d& clU, const Base::Vector3d& clV, bool bUseDir=true); /** * Gibt die u/v/w-Richtungen zurueck */ virtual void GetUVW(Base::Vector3d& clU, Base::Vector3d& clV, Base::Vector3d& clW) const; /** * */ virtual Base::Vector3d GetGravityPoint() const; /** * Verwende Glaettungsterme */ virtual void EnableSmoothing(bool bSmooth=true, double fSmoothInfl=1.0f); protected: bool _bGetUVDir; //! Stellt fest, ob u/v-Richtung vorgegeben wird bool _bSmoothing; //! Glaettung verwenden double _fSmoothInfluence; //! Einfluss der Glaettung unsigned _usUOrder; //! Ordnung in u-Richtung unsigned _usVOrder; //! Ordnung in v-Richtung unsigned _usUCtrlpoints; //! Anzahl der Kontrollpunkte in u-Richtung unsigned _usVCtrlpoints; //! Anzahl der Kontrollpunkte in v-Richtung Base::Vector3d _clU; //! u-Richtung Base::Vector3d _clV; //! v-Richtung Base::Vector3d _clW; //! w-Richtung (senkrecht zu u-und v-Richtung) TColgp_Array1OfPnt* _pvcPoints; //! Punktliste der Rohdaten TColgp_Array1OfPnt2d* _pvcUVParam; //! Parameterwerte zu den Punkten aus der Liste TColgp_Array2OfPnt _vCtrlPntsOfSurf; //! Array von Kontrollpunkten TColStd_Array1OfReal _vUKnots; //! Knotenvektor der B-Spline-Flaeche in u-Richtung TColStd_Array1OfReal _vVKnots; //! Knotenvektor der B-Spline-Flaeche in v-Richtung TColStd_Array1OfInteger _vUMults; //! Vielfachheit der Knoten im Knotenvektor TColStd_Array1OfInteger _vVMults; //! Vielfachheit der Knoten im Knotenvektor }; /////////////////////////////////////////////////////////////////////////////////////////////// /** * Diese Klasse berechnet auf einer beliebigen Punktwolke (auch scattered data) eine * B-Spline-Flaeche. Die Flaeche wird iterativ mit Hilfe einer Parameterkorrektur erzeugt. * Siehe dazu Hoschek/Lasser 2. Auflage (1992). * Erweitert wird die Approximation um Glaettungsterme, so dass glatte Flaechen erzeugt werden * koennen. */ class ReenExport BSplineParameterCorrection : public ParameterCorrection { public: // Konstruktor BSplineParameterCorrection(unsigned usUOrder=4, //Ordnung in u-Richtung (Ordnung=Grad+1) unsigned usVOrder=4, //Ordnung in v-Richtung unsigned usUCtrlpoints=6, //Anz. der Kontrollpunkte in u-Richtung unsigned usVCtrlpoints=6); //Anz. der Kontrollpunkte in v-Richtung virtual ~BSplineParameterCorrection(){}; protected: /** * Initialisierung */ virtual void Init(); /** * Fuehrt eine Parameterkorrektur durch. */ virtual void DoParameterCorrection(int iIter); /** * Loest ein ueberbestimmtes LGS mit Hilfe der Householder-Transformation */ virtual bool SolveWithoutSmoothing(); /** * Loest ein regulaeres Gleichungssystem durch LU-Zerlegung. Es fliessen je nach Gewichtung * Glaettungsterme mit ein */ virtual bool SolveWithSmoothing(double fWeight); public: /** * Setzen des Knotenvektors */ void SetUKnots(const std::vector<double>& afKnots); /** * Setzen des Knotenvektors */ void SetVKnots(const std::vector<double>& afKnots); /** * Gibt die erste Matrix der Glaettungsterme zurueck, falls berechnet */ virtual const math_Matrix& GetFirstSmoothMatrix() const; /** * Gibt die zweite Matrix der Glaettungsterme zurueck, falls berechnet */ virtual const math_Matrix& GetSecondSmoothMatrix() const; /** * Gibt die dritte Matrix der Glaettungsterme zurueck, falls berechnet */ virtual const math_Matrix& GetThirdSmoothMatrix() const; /** * Setzt die erste Matrix der Glaettungsterme */ virtual void SetFirstSmoothMatrix(const math_Matrix& rclMat); /** * Setzt die zweite Matrix der Glaettungsterme */ virtual void SetSecondSmoothMatrix(const math_Matrix& rclMat); /** * Setzt die dritte Matrix der Glaettungsterme */ virtual void SetThirdSmoothMatrix(const math_Matrix& rclMat); /** * Verwende Glaettungsterme */ virtual void EnableSmoothing(bool bSmooth=true, double fSmoothInfl=1.0f); /** * Verwende Glaettungsterme */ virtual void EnableSmoothing(bool bSmooth, double fSmoothInfl, double fFirst, double fSec, double fThird); protected: /** * Berechnet die Matrix zu den Glaettungstermen * (siehe Dissertation U.Dietz) */ virtual void CalcSmoothingTerms(bool bRecalc, double fFirst, double fSecond, double fThird); /** * Berechnet die Matrix zum ersten Glaettungsterm * (siehe Diss. U.Dietz) */ virtual void CalcFirstSmoothMatrix(Base::SequencerLauncher&); /** * Berechnet die Matrix zum zweiten Glaettunsterm * (siehe Diss. U.Dietz) */ virtual void CalcSecondSmoothMatrix(Base::SequencerLauncher&); /** * Berechnet die Matrix zum dritten Glaettungsterm */ virtual void CalcThirdSmoothMatrix(Base::SequencerLauncher&); protected: BSplineBasis _clUSpline; //! B-Spline-Basisfunktion in u-Richtung BSplineBasis _clVSpline; //! B-Spline-Basisfunktion in v-Richtung math_Matrix _clSmoothMatrix; //! Matrix der Glaettungsfunktionale math_Matrix _clFirstMatrix; //! Matrix der 1. Glaettungsfunktionale math_Matrix _clSecondMatrix; //! Matrix der 2. Glaettungsfunktionale math_Matrix _clThirdMatrix; //! Matrix der 3. Glaettungsfunktionale }; } // namespace Reen #endif // REEN_APPROXSURFACE_H
[ "mccad@inr149083.inr.kit.edu" ]
mccad@inr149083.inr.kit.edu
440efd2d522fdd0a5db160321a6a5c59f2267507
4dec7dfd539fabbd7de0b29f504d63195bd8a693
/src/DatabaseComponent.hpp
99944b76e2cc4ccbe8a27973475774f8d0763fb5
[ "Apache-2.0" ]
permissive
acidtonic/example-crud
0d06e566c980be6bf32e69dc54cdbd0a750237d5
fadaaf19fa66bfe61b01c9ec714b8c68d5840eeb
refs/heads/master
2023-01-31T05:32:11.438551
2020-12-11T15:27:32
2020-12-11T15:27:32
320,610,650
0
0
Apache-2.0
2020-12-11T15:27:33
2020-12-11T15:24:34
null
UTF-8
C++
false
false
1,008
hpp
#ifndef CRUD_DATABASECOMPONENT_HPP #define CRUD_DATABASECOMPONENT_HPP #include "db/UserDb.hpp" class DatabaseComponent { public: /** * Create database client */ OATPP_CREATE_COMPONENT(std::shared_ptr<UserDb>, userDb)([] { /* Create database-specific ConnectionProvider */ auto connectionProvider = std::make_shared<oatpp::sqlite::ConnectionProvider>(DATABASE_FILE); /* Create database-specific ConnectionPool */ auto connectionPool = oatpp::sqlite::ConnectionPool::createShared(connectionProvider, 10 /* max-connections */, std::chrono::seconds(5) /* connection TTL */); /* Create database-specific Executor */ auto executor = std::make_shared<oatpp::sqlite::Executor>(connectionPool); /* Create MyClient database client */ return std::make_shared<UserDb>(executor); }()); }; #endif //CRUD_DATABASECOMPONENT_HPP
[ "lganzzzo@gmail.com" ]
lganzzzo@gmail.com
647c2e11375b9991a99d933f9447db8d63f372cb
18b325a6b8b66672f0a83c4e6ffeafa7b9ad8246
/lab2/PrimeNumbers/PrimeNumbers/PrimeNumbersGenerator.h
25ee5a1055173fc2206064a6d134ca4c39b40ac6
[]
no_license
RomanovAleksandr/oop
dd55416752dc9f28a4c127400374979169fd14f5
d218de126f4ceb99956261f55a7944e3674b76c8
refs/heads/master
2021-02-28T04:19:20.732542
2020-07-02T13:14:30
2020-07-02T13:14:30
245,661,507
0
0
null
null
null
null
UTF-8
C++
false
false
107
h
#pragma once #include <set> #include <vector> std::set<int> GeneratePrimeNumbersSet(const int upperBound);
[ "61905953+RomanovAleksandr@users.noreply.github.com" ]
61905953+RomanovAleksandr@users.noreply.github.com
321ad889eec45ccc7e0d5046243010a79f04b834
f5996bf5720a51ecf7193fd4b342cb0386f53948
/src/VTime.hpp
9d288bf056fc897f4d3042f2913946fd1aa88bd5
[ "MIT" ]
permissive
CastMi/warped2
048ea64d2a1ff721b00b8c264557a660c44ab565
86c2fa5ddf777530b637dba800641b30ccee7aa7
refs/heads/master
2021-01-16T19:18:09.316795
2016-04-13T17:22:46
2016-04-13T17:22:46
35,889,867
0
0
null
null
null
null
UTF-8
C++
false
false
1,995
hpp
#ifndef VTIME_H #define VTIME_H #include <stdlib.h> #include <iostream> // for ostream #include <sstream> #include <climits> #include <string> // for operator<<, string enum RegionState { Preponed, Active, Inactive, NBA, Observed, Reactive, Re_Inactive, Re_NBA, Postponed }; class VTime { public: VTime(unsigned int timestamp, unsigned int delta_cycle, unsigned int regions, RegionState region_state = Preponed) : timestamp_(timestamp), delta_cycle_(delta_cycle), regions_(regions), region_state_(region_state) {}; virtual ~VTime(); virtual bool operator< (const VTime& right) const; virtual bool operator> (const VTime& right) const; virtual bool operator== (const VTime& right) const; virtual bool operator!= (const VTime& right) const; virtual bool operator<= (const VTime& right) const; virtual bool operator>= (const VTime& right) const; virtual const VTime operator+ (const VTime& right) const; virtual const VTime operator+ (unsigned int right) const; virtual VTime& operator+= (const VTime& right); virtual VTime& operator+= (unsigned int right); virtual const VTime operator++ () const; static const VTime& getPositiveInfinity() { static const VTime infinite = VTime(UINT_MAX, UINT_MAX, UINT_MAX, RegionState::Postponed); return infinite; }; static VTime& getZero() { static VTime Zero = VTime(0, 0, 0, RegionState::Preponed); return Zero; }; virtual const std::string toString() const { return std::to_string(timestamp_); }; static const VTime& getMaxSimTime() { return getPositiveInfinity(); }; unsigned int getApproximateIntTime() const { return timestamp_; } unsigned int timestamp_, delta_cycle_, regions_; RegionState region_state_; }; inline std::ostream& operator<< (std::ostream& os, const VTime& time) { os << time.toString(); return os; } #endif
[ "michele.castellana@outlook.com" ]
michele.castellana@outlook.com
c72c4b40ae7e985b6265c893e80984607f3f0d71
859785282e385c49c7a6ad11a233e7f5a9d0c9e7
/c++/Knight-Walk.cpp
ebae563f42225c67204e0feedb749c3b21dc1dbe
[]
no_license
tejeswinegi/DSA-Solved-Problems
eaacfd939ef08208f73854c2bae2b4e739d6c4c5
9c4947fecea1f8b66ee2405c2d537961465ea479
refs/heads/master
2023-08-30T19:49:06.935389
2021-10-06T02:07:47
2021-10-06T02:07:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,316
cpp
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define F first #define S second typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<vi> vvi; int minSteps(pii &src, pii &dest, int &n, int &m, vvi &mat) { queue<pii> q; q.push(src); mat[src.F][src.S] = 0; // Mark Visited int row[] = {-2, -1, 1, 2, 2, 1, -1, -2}; int col[] = {1, 2, 2, 1, -1, -2, -2, -1}; int dist = 0; while(!q.empty()) { int count = q.size(); while(count--) { int dx = q.front().F, dy = q.front().S; q.pop(); if(dx == dest.F && dy == dest.S) return dist; for(int k=0; k<8; k++) { int x = dx + row[k]; int y = dy + col[k]; if(x>=0 && x<n && y>=0 && y<m && mat[x][y]) { q.push({x, y}); mat[x][y] = 0; } } } dist++; } return -1; } int main() { IOS; int t, n, m, a, b, c, d; cin >> t; while(t--) { cin >> n >> m; vvi mat(n, vi(m, 1)); cin >> a >> b >> c >> d; pii src = {a-1, b-1}; pii dest = {c-1, d-1}; cout << minSteps(src, dest, n, m, mat) << endl; } }
[ "nkits9@gmail.com" ]
nkits9@gmail.com
2ccf4363bbcc22f8e39dc4efd3991c2d0ab8120a
b5d20ba5c51cbbabb8e8f67e64fec5f22abbf5b5
/webrtc/rtc_base/fake_ssl_identity.h
f2fe99c38397578294efe05a7e14595757fc6bbd
[]
no_license
zeiger589/video-chat
1f979e7f1e7ab543d4e36bef09175548c7528ec6
7c233388298057663cfbb65631b0d0d8b80530d4
refs/heads/master
2020-05-17T07:07:53.894612
2019-04-17T16:10:18
2019-04-17T16:10:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,735
h
/* * Copyright 2012 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef RTC_BASE_FAKE_SSL_IDENTITY_H_ #define RTC_BASE_FAKE_SSL_IDENTITY_H_ #include <memory> #include <vector> #include "rtc_base/ssl_certificate.h" #include "rtc_base/ssl_identity.h" namespace rtc { class FakeSSLCertificate : public SSLCertificate { public: // SHA-1 is the default digest algorithm because it is available in all build // configurations used for unit testing. explicit FakeSSLCertificate(const std::string& pem_string); FakeSSLCertificate(const FakeSSLCertificate&); ~FakeSSLCertificate() override; // SSLCertificate implementation. std::unique_ptr<SSLCertificate> Clone() const override; std::string ToPEMString() const override; void ToDER(Buffer* der_buffer) const override; int64_t CertificateExpirationTime() const override; bool GetSignatureDigestAlgorithm(std::string* algorithm) const override; bool ComputeDigest(const std::string& algorithm, unsigned char* digest, size_t size, size_t* length) const override; void SetCertificateExpirationTime(int64_t expiration_time); void set_digest_algorithm(const std::string& algorithm); private: std::string pem_string_; std::string digest_algorithm_; // Expiration time in seconds relative to epoch, 1970-01-01T00:00:00Z (UTC). int64_t expiration_time_; }; class FakeSSLIdentity : public SSLIdentity { public: explicit FakeSSLIdentity(const std::string& pem_string); // For a certificate chain. explicit FakeSSLIdentity(const std::vector<std::string>& pem_strings); explicit FakeSSLIdentity(const FakeSSLCertificate& cert); explicit FakeSSLIdentity(const FakeSSLIdentity& o); ~FakeSSLIdentity() override; // SSLIdentity implementation. FakeSSLIdentity* GetReference() const override; const SSLCertificate& certificate() const override; const SSLCertChain& cert_chain() const override; // Not implemented. std::string PrivateKeyToPEMString() const override; // Not implemented. std::string PublicKeyToPEMString() const override; // Not implemented. virtual bool operator==(const SSLIdentity& other) const; private: std::unique_ptr<SSLCertChain> cert_chain_; }; } // namespace rtc #endif // RTC_BASE_FAKE_SSL_IDENTITY_H_
[ "tuanit96@gmail.com" ]
tuanit96@gmail.com
153a3aabbf0117c9d0eb3e514cbb0c9746166da0
c6fae54cb4aec39e228254a99a50dd8bc0546af4
/cpp/dynamic_programing_DP/303_range_sum_query_immutable.cpp
9ba1def190e70536c4cc4ca89c2cebb7b8cd6c89
[]
no_license
songanz/Learn_coding
77c08d61c9a4f2917f147624c2e8013148588311
e2185b4c936b226f106e4f7f449b2b50a463f9e9
refs/heads/master
2020-04-18T05:36:21.586154
2020-04-13T18:30:23
2020-04-13T18:30:23
167,284,886
0
0
null
null
null
null
UTF-8
C++
false
false
561
cpp
#include "../header.h" using namespace std; class NumArray { public: NumArray(vector<int>& nums) { int n = nums.size(); sum_ = vector<int>(n+1); sum_[n] = 0; for (int i=0; i<n; ++i) { sum_[n-1-i] = sum_[n-i] + nums[n-1-i]; } } int sumRange(int i, int j) { return sum_[i] - sum_[j+1]; } private: vector<int> sum_; }; int main() { vector<int> nums = {1,2,3,4,5}; NumArray* arr = new NumArray(nums); int ans = arr->sumRange(0,4); cout << ans << '\n'; }
[ "songanz@umich.edu" ]
songanz@umich.edu
a262e9ed120ed23ab793644516ca1d9cfd563778
83e79662120dcd66a05b197888c521dbfbb907c5
/toyC/include/JVM/JVMlabel.h
c95a9d78377c41df4a1ef0690b33687669452da8
[]
no_license
jeremyprice97/EGRE591
70ca336e77de375aa8ae552a9eb78f646d2a40fb
50662746f49c5b8625adf53b07b02aa4b2cbe886
refs/heads/master
2020-07-27T03:15:10.214673
2019-12-05T15:58:19
2019-12-05T15:58:19
208,848,767
0
0
null
null
null
null
UTF-8
C++
false
false
177
h
#ifndef JVMLABEL_H #define JVMLABEL_H namespace toycalc { class JVMlabel{ public: virtual std::string toString() = 0; virtual std::string getLabel() = 0; }; } #endif
[ "jeremy.price97@gmail.com" ]
jeremy.price97@gmail.com
d12b8bb88c3f6757945bfdf8594fcc5ce17edf51
86683a8d36c44321c92e9c9a8ea6f0602c4f8452
/build/DevkitPSP/main.cpp
5e4e22b1b17fa721c8bac5d3e9747f4341c4c877
[]
no_license
cnyaw/good
157ca8b8c6560f7cd1f56141b93331fb973e95c7
c7a6564c2421e0685790550734cea5194eed619c
refs/heads/master
2023-09-04T11:06:03.035298
2023-08-31T07:57:37
2023-08-31T07:57:37
107,022,657
10
1
null
null
null
null
UTF-8
C++
false
false
4,072
cpp
/* main.cpp good game player DevkitPSP. Copyright (c) 2010 waync cheng All Rights Reserved. 2010/08/05 waync created */ #include <pspkernel.h> #include <pspdisplay.h> #include <pspdebug.h> #include <pspiofilemgr.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <sys/types.h> #include <sys/unistd.h> #include <sstream> #include <iterator> #include <pspgu.h> #include <pspgum.h> #include <pspctrl.h> #include <algorithm> #include <map> #include <sstream> #include <stdexcept> #include <vector> PSP_MODULE_INFO("Good devkitPSP", 0, 1, 1); PSP_MAIN_THREAD_ATTR(THREAD_ATTR_USER); static unsigned int __attribute__((aligned(16))) list[262144]; int exitCallback(int arg1, int arg2, void *common) { sceKernelExitGame(); return 0; } int callbackThread(SceSize args, void *argp) { int cbid; cbid = sceKernelCreateCallback("Exit Callback", exitCallback, NULL); sceKernelRegisterExitCallback(cbid); sceKernelSleepThreadCB(); return 0; } int setupCallbacks(void) { int thid = 0; thid = sceKernelCreateThread("update_thread", callbackThread, 0x11, 0xFA0, 0, 0); if(thid >= 0) { sceKernelStartThread(thid, 0, 0); } return thid; } #define GOOD_SUPPORT_STGE #define GOOD_SUPPORT_STB_IMG #define STB_IMAGE_IMPLEMENTATION #define GOOD_SUPPORT_NO_LOGO #include "rt/rt.h" #include "DevkitPSP_app.h" #define printf pspDebugScreenPrintf bool getPrjName(std::string& prjname) { // // Find all project files in this folder.(.txt, .good, .zip). // char cwd[MAXPATHLEN]; strcpy(cwd, "ms0:/PSP/GAME/good/"); int dfd = sceIoDopen(cwd); if (0 > dfd) { return false; } std::vector<std::string> names; std::string name; SceIoDirent dir; memset(&dir, 0, sizeof(dir)); while (0 < sceIoDread(dfd, &dir)) { if (0 == (dir.d_stat.st_attr & FIO_SO_IFDIR)) { // A file. name = dir.d_name; std::transform(name.begin(), name.end(), name.begin(), tolower); if (name.npos != name.find(".txt") || name.npos != name.find(".good") || name.npos != name.find(".zip")) names.push_back(dir.d_name); } } sceIoDclose(dfd); if (names.empty()) { return false; } std::sort(names.begin(), names.end()); // // List project files. // static int sel = 0; pspDebugScreenInit(); pspDebugScreenClear(); printf("cwd: %s\n", cwd); for (size_t i = 0; i < names.size(); i++) { printf(" %s\n", names[i].c_str()); } pspDebugScreenSetXY(0, 1 + sel); printf(">"); // // Handle input. // SceCtrlData oldPad = {0}; while (true) { SceCtrlData pad = {0}; sceCtrlReadBufferPositive(&pad, 1); if (oldPad.Buttons != pad.Buttons) { if (pad.Buttons & PSP_CTRL_CIRCLE) { prjname = names[sel]; return true; } else if (pad.Buttons & PSP_CTRL_LTRIGGER) { return false; } else if (pad.Buttons & PSP_CTRL_UP) { pspDebugScreenSetXY(0, 1 + sel); printf(" "); if (0 == sel) { sel = (int)names.size() - 1; } else { sel -= 1; } pspDebugScreenSetXY(0, 1 + sel); printf(">"); } else if (pad.Buttons & PSP_CTRL_DOWN) { pspDebugScreenSetXY(0, 1 + sel); printf(" "); if ((int)names.size() - 1 == sel) { sel = 0; } else { sel += 1; } pspDebugScreenSetXY(0, 1 + sel); printf(">"); } oldPad = pad; } sceDisplayWaitVblankStart(); } return false; } int main(int argc, char* argv[]) { setupCallbacks(); sceCtrlSetSamplingCycle(0); sceCtrlSetSamplingMode(PSP_CTRL_MODE_DIGITAL); good::rt::DevkitPspApplication& g = good::rt::DevkitPspApplication::getInst(); g.gx.init(); std::string prj; while (getPrjName(prj)) { g.loopGame(prj); } g.gx.uninit(); sceKernelExitGame(); return 0; } // // Workaround for fixing link error. // extern "C" { int _isatty(int file) { (void)file; // Avoid warning. return 1; } }
[ "wayncc@gmail.com" ]
wayncc@gmail.com
9803fd4f9b4117d215d3800e415ff44553470281
8f0418ee61396d07af6d3b7f925d65e55f9a97aa
/Options.cpp
190ce5dedacf7107e06fccbfde6302a8f244bf2d
[]
no_license
abartlett139/Camp
a5324094a76edc6901df32bf48ecf4139cd86f87
40c91b390259f684ac4fd94fe3d2a78e4e053dbe
refs/heads/master
2020-07-23T06:37:52.200529
2017-06-14T16:49:48
2017-06-14T16:49:48
94,353,692
1
0
null
null
null
null
UTF-8
C++
false
false
4,586
cpp
#include "MYCLIENT.h" #include "Options.h" Options::Options() { } Options::~Options() { D3D::Release(background); D3D::Release(title); for (int i = 0; i < 6; i++) { D3D::Release(button[i]); D3D::Release(buttonOver[i]); } D3D::Release<ID3DXSprite*>(sprite); } bool Options::Init() { // create sprite D3DXCreateSprite(Device, &sprite); // set center of textures buttonCenter = D3DXVECTOR3(440, 60, 0); titleCenter = D3DXVECTOR3(800, 100, 0); // set current button currentButton = 0; // set the timer timer = 0; canSwitch = false; // load textures background = D3D::LoadTexture("sprites/background.png"); title = D3D::LoadTexture("sprites/titles/options.png"); button[0] = D3D::LoadTexture("sprites/buttons/fxvolume.png"); button[1] = D3D::LoadTexture("sprites/buttons/musicvolume.png"); button[2] = D3D::LoadTexture("sprites/buttons/sethostipaddress.png"); button[3] = D3D::LoadTexture("sprites/buttons/mainmenu.png"); buttonOver[0] = D3D::LoadTexture("sprites/buttons/over/fxvolume.png"); buttonOver[1] = D3D::LoadTexture("sprites/buttons/over/musicvolume.png"); buttonOver[2] = D3D::LoadTexture("sprites/buttons/over/sethostipaddress.png"); buttonOver[3] = D3D::LoadTexture("sprites/buttons/over/mainmenu.png"); // create dialog box for ip address dlgHwnd = CreateDialog(NULL, MAKEINTRESOURCE(IDD_DIALOG1), NULL, DlgProc); return true; } void Options::Enter() { if (!isInit) isInit = Init(); // start playing sounds for level if (previousState == 0 || previousState == onePlayer || previousState == twoPlayer) SoundEngine->PlayMusic(Sound::MENUBACKGROUND); } bool Options::Render(float deltaTime) { Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, 0xFF000000, 1.0f, 0); Device->BeginScene(); sprite->Begin(D3DXSPRITE_ALPHABLEND); sprite->Draw(background, NULL, NULL, NULL, D3D::WHITE); sprite->Draw(title, NULL, &titleCenter, &D3DXVECTOR3(800, 100, 0), D3D::WHITE); for (int i = 0; i < 4; i++) { if (i != currentButton) { sprite->Draw(button[i], NULL, &buttonCenter, &D3DXVECTOR3(800, (float)300 + (100 * i), 0), D3D::WHITE); } else { sprite->Draw(buttonOver[i], NULL, &buttonCenter, &D3DXVECTOR3(800, (float)300 + (100 * i), 0), D3D::WHITE); } } sprite->End(); Device->EndScene(); Device->Present(0, 0, 0, 0); return true; } void Options::Update(float deltaTime) { // timer control for button switching if (timer >= .5f) { timer = 0; canSwitch = true; } else { timer += deltaTime; } //------------------- // Change States //------------------- if (((GetAsyncKeyState(VK_RETURN) && 0x8000) || controller->isPressed(XINPUT_GAMEPAD_A)) && canSwitch) { SoundEngine->PlayFX(Sound::ENEMYSHOT); canSwitch = false; timer = 0; switch (currentButton) { case 0: // adjust fx volume SoundEngine->fxVolume += .2; if (SoundEngine->fxVolume >= 2.5f) SoundEngine->fxVolume = 0; SoundEngine->PlayFX(Sound::FIRE); break; case 1: // adjust music volume SoundEngine->musicVolume += .2; if (SoundEngine->musicVolume >= 2.5f) SoundEngine->musicVolume = 0; SoundEngine->ChangeMusicVolume(); break; case 2: // display and enable dialog window for setting the IP address if(!IsWindowVisible(dlgHwnd)) ShowWindow(dlgHwnd, SW_SHOW); if (!IsWindowEnabled(dlgHwnd)) EnableWindow(dlgHwnd, TRUE); break; case 3: Exit(menu); break; default: break; } } //------------------- // Keyboard Input //------------------- if (GetAsyncKeyState(VK_DOWN) && 0x8000 && canSwitch) { SoundEngine->PlayFX(Sound::RELOAD); currentButton += 1; canSwitch = false; timer = 0; } if (GetAsyncKeyState(VK_UP) && 0x8000 && canSwitch) { SoundEngine->PlayFX(Sound::RELOAD); currentButton -= 1; canSwitch = false; timer = 0; } //------------------- // Controller Input //------------------- if (controller->isConnected) { if (controller->leftY && canSwitch) { SoundEngine->PlayFX(Sound::RELOAD); currentButton -= controller->leftY / abs(controller->leftY); canSwitch = false; timer = 0; } } // keep current button in range if (currentButton >= 4) currentButton = 0; if (currentButton <= -1) currentButton = 3; } void Options::Exit(GameState *nextState) { // stop playing sounds for level if(nextState == onePlayer || nextState == twoPlayer) SoundEngine->StopMusic(); // reset variables currentButton = 0; timer = 0; EndDialog(dlgHwnd, FALSE); // go to the next state previousState = currentState; currentState = nextState; currentState->Enter(); }
[ "abartlett139@gmail.com" ]
abartlett139@gmail.com
62eeed91333ac2369810b6d60986398e37861278
e48a40b19ebe1ca64d877885f9f19e9a78b192c3
/Examples/Cxx/WidgetsTour/Widgets/vtkKWMenu.cxx
15b9497cc292386ffe683048331246171fab3d07
[]
no_license
SIVICLab/KWWidgets
dbe2034caf065c30eafed92d73e9df9ff60a6565
f5a3e16063db773eaf79736ec31314d392fa934d
refs/heads/master
2021-01-18T20:08:02.372034
2017-04-01T20:57:19
2017-04-01T20:57:19
86,941,196
1
0
null
2017-04-01T20:34:24
2017-04-01T20:34:23
null
UTF-8
C++
false
false
6,686
cxx
#include "vtkKWMenu.h" #include "vtkKWMessage.h" #include "vtkKWApplication.h" #include "vtkKWWindow.h" #include "vtkKWWidgetsTourExample.h" #include <vtksys/stl/string> class vtkKWMenuItem : public KWWidgetsTourItem { public: virtual int GetType(); virtual void Create(vtkKWWidget *parent, vtkKWWindow *); }; void vtkKWMenuItem::Create(vtkKWWidget *parent, vtkKWWindow *win) { vtkKWApplication *app = parent->GetApplication(); int index; size_t i; const char* days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}; const char* colors[] = {"Re&d", "Gree&n", "&Blue"}; // ----------------------------------------------------------------------- // Let's create a label to explain what's going on vtkKWMessage *message1 = vtkKWMessage::New(); message1->SetParent(parent); message1->Create(); message1->SetText("This example creates a new menu entry called 'Test Menu' in the window menu bar and populate it with various menu entries. Check the source code below for more details."); app->Script( "pack %s -side top -anchor nw -expand n -padx 2 -pady 2", message1->GetWidgetName()); // ----------------------------------------------------------------------- // Let's create a new entry in the main menu bar of our window // (vtkKWWindow is a subclass of vtkKWTopLevel, which has a pointer // to the menu bar) vtkKWMenu *menu1 = vtkKWMenu::New(); menu1->SetParent(win->GetMenu()); menu1->Create(); win->GetMenu()->AddCascade("Test Menu", menu1); // ----------------------------------------------------------------------- // Let's add a few commands in the menu index = menu1->AddCommand( "&Left Justification", message1, "SetJustificationToLeft"); menu1->SetItemAccelerator(index, "F8"); menu1->SetBindingForItemAccelerator(index, menu1->GetParentTopLevel()); menu1->SetItemHelpString(index, "Set the message justification to left."); index = menu1->AddCommand( "&Right Justification", message1, "SetJustificationToRight"); index = menu1->AddCommand( "&Center Justification", message1, "SetJustificationToCenter"); // disable entry for demonstration purposes menu1->SetItemState(index, 0); // ----------------------------------------------------------------------- // Let's add a cascade menu menu1->AddSeparator(); vtkKWMenu *submenu1 = vtkKWMenu::New(); submenu1->SetParent(menu1); submenu1->Create(); menu1->AddCascade("Days", submenu1); // Populate this menu with radiobuttons. // This is as simple as it gets since by default all radiobuttons // share the same group. for (i = 0; i < sizeof(days) / sizeof(days[0]); i++) { submenu1->AddRadioButton(days[i]); } submenu1->SelectItem("Monday"); // ----------------------------------------------------------------------- // Let's add a more complex cascade menu menu1->AddSeparator(); vtkKWMenu *submenu2 = vtkKWMenu::New(); submenu2->SetParent(menu1); submenu2->Create(); menu1->AddCascade("Colors and Widths", submenu2); // Populate this menu with radiobuttons // This time, we need to assign each items the proper group. // There are several ways to do so, you can for example pick // an arbitrary group name... // No command here, just a simple radiobutton. You can use // SetItemCommand later on... for (i = 0; i < sizeof(colors) / sizeof(colors[0]); i++) { index = submenu2->AddRadioButton(colors[i]); submenu2->SetItemGroupName(index, "Colors"); } submenu2->SelectItem("Red"); submenu2->AddSeparator(); // ... or you can use the group name that is assigned to any radiobutton // when it is created and make sure all other share the same. This can be // done with PutItemInGroup too. We also show that an arbitrary value can // be assigned to each entry: a string, or here, an integer. By default, // this value is the label itself. int index_g = submenu2->AddRadioButton( "&Tiny Width", message1, "SetWidth 50"); submenu2->SetItemSelectedValueAsInt(index_g, 50); vtksys_stl::string group_name = submenu2->GetItemGroupName(index_g); index = submenu2->AddRadioButton( "&Small Width", message1, "SetWidth 100"); submenu2->SetItemSelectedValueAsInt(index, 100); submenu2->SetItemGroupName(index, group_name.c_str()); index = submenu2->AddRadioButton( "&Medium Width", message1, "SetWidth 150"); submenu2->SetItemSelectedValueAsInt(index, 150); submenu2->PutItemInGroup(index, index_g); // Now instead of selecting by label, or even index, we use the selected // value we assigned for each entry in that group. The goal here is // to provide an easy way to map an internal variable (say, 'width') // to a choice in the menu. int width = 150; message1->SetWidth(width); submenu2->SelectItemInGroupWithSelectedValueAsInt(group_name.c_str(), width); // The callbacks above hardcodes the width in each method to keep this // example short, but it could/should have been a unique 'SetWidthFromMenu' // callback that would have retrieved the width that was associated to each // entry like this: int selected_width = submenu2->GetItemSelectedValueAsInt( submenu2->GetIndexOfSelectedItemInGroup(group_name.c_str())); message1->SetWidth(selected_width); // ----------------------------------------------------------------------- // Let's add a some checkbuttons menu1->AddSeparator(); index = menu1->AddCheckButton("Italic"); // Better use markers in label, but hey menu1->SetItemUnderline(index, 1); // A callback command can be associated to the checkbutton, inside which // the selected state can be queried int is_selected = menu1->GetItemSelectedState("Italic"); // If it is easier to remember, you can use a group name too for // that single checkbutton (don't put any other item in it). You don't even // have to make one up, it is assigned one by default that can be // retrieved using the entry's index (or label, but hey, if you remember // the label at this point, you probably do not need a group :) // The selected value of a checkbutton is 1 by default. index = menu1->AddCheckButton("I want some bold"); menu1->SetItemGroupName(index, "Bold"); menu1->SelectItemInGroupWithSelectedValueAsInt("Bold", 1); is_selected = menu1->GetItemSelectedState( menu1->GetIndexOfSelectedItemInGroup("Bold")); (void)is_selected; message1->Delete(); submenu1->Delete(); submenu2->Delete(); menu1->Delete(); } int vtkKWMenuItem::GetType() { return KWWidgetsTourItem::TypeCore; } KWWidgetsTourItem* vtkKWMenuEntryPoint() { return new vtkKWMenuItem(); }
[ "barre" ]
barre
680ab72aae93f2aa5f059d7cd4871c5feb913512
45aa6c77337e06f8ca8cd570a90d4542b3d63521
/ThirdParty/cpgf/test/metagen/metadata/src/register_meta_test.cpp
53d5a0fbcde98a603523b197409d1e67df9c119c
[ "Apache-2.0" ]
permissive
iteratif/uifaces
b6fcf4a023f41ee92c6cba0f06090cd967742031
2db85273282a52af09ced7f8ca50baff600dc31c
refs/heads/master
2021-07-01T05:15:11.858215
2017-09-13T23:32:17
2017-09-13T23:32:17
103,461,748
0
0
null
null
null
null
UTF-8
C++
false
false
1,034
cpp
/* cpgf Library Copyright (C) 2011 - 2013 Wang Qi http://www.cpgf.org/ All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 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. */ // Auto generated file, don't modify. #include "../include/register_meta_test.h" #include "cpgf/gmetadefine.h" #include "cpgf/goutmain.h" using namespace cpgf; namespace meta_test { namespace { G_AUTO_RUN_BEFORE_MAIN() { GDefineMetaNamespace _d = GDefineMetaNamespace::define("metatest"); registerMain_metatest(_d); } } // unnamed namespace } // namespace meta_test
[ "olivier.bgualotto@iteratif.fr" ]
olivier.bgualotto@iteratif.fr
6659d0572873f5ed9db13e01c5c99936e2543ae9
37d08c745caee39da991debb54635065df1a8e2a
/src/zgetrf.cpp
76d0d3e7b5a0e9eb6e3ca2045ff088d0218f6ee8
[]
no_license
kjbartel/magma
c936cd4838523779f31df418303c6bebb063aecd
3f0dd347d2e230c8474d1e22e05b550fa233c7a3
refs/heads/master
2020-06-06T18:12:56.286615
2015-06-04T17:20:40
2015-06-04T17:20:40
36,885,326
23
4
null
null
null
null
UTF-8
C++
false
false
11,419
cpp
/* -- MAGMA (version 1.6.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date January 2015 @author Stan Tomov @precisions normal z -> s d c */ #include "common_magma.h" /** Purpose ------- ZGETRF computes an LU factorization of a general M-by-N matrix A using partial pivoting with row interchanges. This version does not require work space on the GPU passed as input. GPU memory is allocated in the routine. The factorization has the form A = P * L * U where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m > n), and U is upper triangular (upper trapezoidal if m < n). This is the right-looking Level 3 BLAS version of the algorithm. If the current stream is NULL, this version replaces it with a new stream to overlap computation with communication. Arguments --------- @param[in] m INTEGER The number of rows of the matrix A. M >= 0. @param[in] n INTEGER The number of columns of the matrix A. N >= 0. @param[in,out] A COMPLEX_16 array, dimension (LDA,N) On entry, the M-by-N matrix to be factored. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. \n Higher performance is achieved if A is in pinned memory, e.g. allocated using magma_malloc_pinned. @param[in] lda INTEGER The leading dimension of the array A. LDA >= max(1,M). @param[out] ipiv INTEGER array, dimension (min(M,N)) The pivot indices; for 1 <= i <= min(M,N), row i of the matrix was interchanged with row IPIV(i). @param[out] info INTEGER - = 0: successful exit - < 0: if INFO = -i, the i-th argument had an illegal value or another error occured, such as memory allocation failed. - > 0: if INFO = i, U(i,i) is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations. @ingroup magma_zgesv_comp ********************************************************************/ extern "C" magma_int_t magma_zgetrf( magma_int_t m, magma_int_t n, magmaDoubleComplex *A, magma_int_t lda, magma_int_t *ipiv, magma_int_t *info) { #define dAT(i_, j_) (dAT + (i_)*nb*ldda + (j_)*nb) magmaDoubleComplex *dAT, *dA, *da, *work; magmaDoubleComplex c_one = MAGMA_Z_ONE; magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE; magma_int_t iinfo, nb; /* Check arguments */ *info = 0; if (m < 0) *info = -1; else if (n < 0) *info = -2; else if (lda < max(1,m)) *info = -4; if (*info != 0) { magma_xerbla( __func__, -(*info) ); return *info; } /* Quick return if possible */ if (m == 0 || n == 0) return *info; /* Function Body */ nb = magma_get_zgetrf_nb(m); if ( (nb <= 1) || (nb >= min(m,n)) ) { /* Use CPU code. */ lapackf77_zgetrf(&m, &n, A, &lda, ipiv, info); } else { /* Use hybrid blocked code. */ magma_int_t maxm, maxn, ldda, maxdim; magma_int_t i, j, rows, cols, s = min(m, n)/nb; maxm = ((m + 31)/32)*32; maxn = ((n + 31)/32)*32; maxdim = max(maxm, maxn); /* set number of GPUs */ magma_int_t ngpu = magma_num_gpus(); if ( ngpu > 1 ) { /* call multi-GPU non-GPU-resident interface */ magma_zgetrf_m(ngpu, m, n, A, lda, ipiv, info); return *info; } /* explicitly checking the memory requirement */ size_t freeMem, totalMem; cudaMemGetInfo( &freeMem, &totalMem ); freeMem /= sizeof(magmaDoubleComplex); int h = 1+(2+ngpu), ngpu2 = ngpu; int NB = (magma_int_t)(0.8*freeMem/maxm-h*nb); const char* ngr_nb_char = getenv("MAGMA_NGR_NB"); if ( ngr_nb_char != NULL ) NB = max( nb, min( NB, atoi(ngr_nb_char) ) ); if ( ngpu > ceil((double)NB/nb) ) { ngpu2 = (int)ceil((double)NB/nb); h = 1+(2+ngpu2); NB = (magma_int_t)(0.8*freeMem/maxm-h*nb); } if ( ngpu2*NB < n ) { /* require too much memory, so call non-GPU-resident version */ magma_zgetrf_m(ngpu, m, n, A, lda, ipiv, info); return *info; } ldda = maxn; work = A; if (maxdim*maxdim < 2*maxm*maxn) { // if close to square, allocate square matrix and transpose in-place if (MAGMA_SUCCESS != magma_zmalloc( &dA, nb*maxm + maxdim*maxdim )) { /* alloc failed so call non-GPU-resident version */ magma_zgetrf_m(ngpu, m, n, A, lda, ipiv, info); return *info; } da = dA + nb*maxm; ldda = maxdim; magma_zsetmatrix( m, n, A, lda, da, ldda ); dAT = da; magmablas_ztranspose_inplace( ldda, dAT, ldda ); } else { // if very rectangular, allocate dA and dAT and transpose out-of-place if (MAGMA_SUCCESS != magma_zmalloc( &dA, (nb + maxn)*maxm )) { /* alloc failed so call non-GPU-resident version */ magma_zgetrf_m(ngpu, m, n, A, lda, ipiv, info); return *info; } da = dA + nb*maxm; magma_zsetmatrix( m, n, A, lda, da, maxm ); if (MAGMA_SUCCESS != magma_zmalloc( &dAT, maxm*maxn )) { /* alloc failed so call non-GPU-resident version */ magma_free( dA ); magma_zgetrf_m(ngpu, m, n, A, lda, ipiv, info); return *info; } magmablas_ztranspose( m, n, da, maxm, dAT, ldda ); } lapackf77_zgetrf( &m, &nb, work, &lda, ipiv, &iinfo); /* Define user stream if current stream is NULL */ magma_queue_t stream[2]; magma_queue_t orig_stream; magmablasGetKernelStream( &orig_stream ); magma_queue_create( &stream[0] ); if (orig_stream == NULL) { magma_queue_create( &stream[1] ); magmablasSetKernelStream(stream[1]); } else { stream[1] = orig_stream; } for( j = 0; j < s; j++ ) { // download j-th panel cols = maxm - j*nb; if (j > 0) { magmablas_ztranspose( nb, cols, dAT(j,j), ldda, dA, cols ); // make sure that gpu queue is empty magma_device_sync(); magma_zgetmatrix_async( m-j*nb, nb, dA, cols, work, lda, stream[0]); magma_ztrsm( MagmaRight, MagmaUpper, MagmaNoTrans, MagmaUnit, n - (j+1)*nb, nb, c_one, dAT(j-1,j-1), ldda, dAT(j-1,j+1), ldda ); magma_zgemm( MagmaNoTrans, MagmaNoTrans, n-(j+1)*nb, m-j*nb, nb, c_neg_one, dAT(j-1,j+1), ldda, dAT(j, j-1), ldda, c_one, dAT(j, j+1), ldda ); // do the cpu part rows = m - j*nb; magma_queue_sync( stream[0] ); lapackf77_zgetrf( &rows, &nb, work, &lda, ipiv+j*nb, &iinfo); } if (*info == 0 && iinfo > 0) *info = iinfo + j*nb; // upload j-th panel magma_zsetmatrix_async( m-j*nb, nb, work, lda, dA, cols, stream[0]); for( i=j*nb; i < j*nb + nb; ++i ) { ipiv[i] += j*nb; } magmablas_zlaswp( n, dAT, ldda, j*nb + 1, j*nb + nb, ipiv, 1 ); magma_queue_sync( stream[0] ); magmablas_ztranspose( cols, nb, dA, cols, dAT(j,j), ldda ); // do the small non-parallel computations (next panel update) if (s > (j+1)) { magma_ztrsm( MagmaRight, MagmaUpper, MagmaNoTrans, MagmaUnit, nb, nb, c_one, dAT(j, j ), ldda, dAT(j, j+1), ldda); magma_zgemm( MagmaNoTrans, MagmaNoTrans, nb, m-(j+1)*nb, nb, c_neg_one, dAT(j, j+1), ldda, dAT(j+1, j ), ldda, c_one, dAT(j+1, j+1), ldda ); } else { magma_ztrsm( MagmaRight, MagmaUpper, MagmaNoTrans, MagmaUnit, n-s*nb, nb, c_one, dAT(j, j ), ldda, dAT(j, j+1), ldda); magma_zgemm( MagmaNoTrans, MagmaNoTrans, n-(j+1)*nb, m-(j+1)*nb, nb, c_neg_one, dAT(j, j+1), ldda, dAT(j+1, j ), ldda, c_one, dAT(j+1, j+1), ldda ); } } magma_int_t nb0 = min(m - s*nb, n - s*nb); if ( nb0 > 0 ) { rows = m - s*nb; cols = maxm - s*nb; magmablas_ztranspose( nb0, rows, dAT(s,s), ldda, dA, cols ); magma_zgetmatrix( rows, nb0, dA, cols, work, lda ); // make sure that gpu queue is empty magma_device_sync(); // do the cpu part lapackf77_zgetrf( &rows, &nb0, work, &lda, ipiv+s*nb, &iinfo); if (*info == 0 && iinfo > 0) *info = iinfo + s*nb; for( i=s*nb; i < s*nb + nb0; ++i ) { ipiv[i] += s*nb; } magmablas_zlaswp( n, dAT, ldda, s*nb + 1, s*nb + nb0, ipiv, 1 ); // upload j-th panel magma_zsetmatrix( rows, nb0, work, lda, dA, cols ); magmablas_ztranspose( rows, nb0, dA, cols, dAT(s,s), ldda ); magma_ztrsm( MagmaRight, MagmaUpper, MagmaNoTrans, MagmaUnit, n-s*nb-nb0, nb0, c_one, dAT(s,s), ldda, dAT(s,s)+nb0, ldda); } // undo transpose if (maxdim*maxdim < 2*maxm*maxn) { magmablas_ztranspose_inplace( ldda, dAT, ldda ); magma_zgetmatrix( m, n, da, ldda, A, lda ); } else { magmablas_ztranspose( n, m, dAT, ldda, da, maxm ); magma_zgetmatrix( m, n, da, maxm, A, lda ); magma_free( dAT ); } magma_free( dA ); magma_queue_destroy( stream[0] ); if (orig_stream == NULL) { magma_queue_destroy( stream[1] ); } magmablasSetKernelStream( orig_stream ); } return *info; } /* magma_zgetrf */ #undef dAT
[ "kjbartel@users.noreply.github.com" ]
kjbartel@users.noreply.github.com
e10406aaf03fc5a69d12580bee608dbe1dac8050
5ac0f730915dab46aa831e06212e3f06e7586aa2
/Framework/Parser.cpp
e73a71b2c2f93aa8dbf4e7161b234916e01e43a3
[]
no_license
Danelo13/ElProyecto
1b494fd310b023b7116e0270b81475f571f22c89
c7f1d28215126e54f1ef57c563f54aabe296cdfd
refs/heads/master
2021-01-16T00:41:07.718695
2017-08-10T23:33:13
2017-08-10T23:33:13
99,969,666
0
0
null
null
null
null
UTF-8
C++
false
false
1,308
cpp
#include "Parser.h" Cparser::Cparser() { } Cparser::~Cparser() { } bool Cparser::OpenFile(const char * Filename) { Unnombre.open(Filename, fstream::in); if (!Unnombre.is_open()) { return false; } return true; } void Cparser::Literate(const char * Filename, vector<unsigned short> &index, vector<CVertex4> &Vertex) { if (OpenFile(Filename)) { getline(Unnombre, reader); if (reader == "xof 0303txt 0032") { while (!Unnombre.eof()) { getline(Unnombre, reader); if (reader == " Mesh mesh_pinata_cerdo_ {") { Unnombre >> NVertx >> Courrier; for (int i = 0; i < NVertx; i++) { CVertex4 V; Unnombre >> holder >> Courrier; V.x = holder; Unnombre >> holder >> Courrier; V.y = holder; Unnombre >> holder >> Courrier >> Courrier; V.z= holder; Vertex.push_back(V); } Unnombre >> NIndex >> Courrier; for (int i = 0; i < NIndex; i++) { unsigned short Ind; Unnombre >> Courrier >> Courrier >> holder >> Courrier; Ind = holder; index.push_back(Ind); Unnombre >> holder >> Courrier; Ind = holder; index.push_back(Ind); Unnombre >> holder >> Courrier >> Courrier; Ind = holder; index.push_back(Ind); } } } } Unnombre.close(); } }
[ "danelo130@gmail.com" ]
danelo130@gmail.com
36d926727524fbec8603eebadabc54a3be8cfdee
1dbf007249acad6038d2aaa1751cbde7e7842c53
/vpc/include/huaweicloud/vpc/v2/model/CreateRouteTableResponse.h
9f50a446a449461d3220501bbb14774b76c1685c
[]
permissive
huaweicloud/huaweicloud-sdk-cpp-v3
24fc8d93c922598376bdb7d009e12378dff5dd20
71674f4afbb0cd5950f880ec516cfabcde71afe4
refs/heads/master
2023-08-04T19:37:47.187698
2023-08-03T08:25:43
2023-08-03T08:25:43
324,328,641
11
10
Apache-2.0
2021-06-24T07:25:26
2020-12-25T09:11:43
C++
UTF-8
C++
false
false
1,451
h
#ifndef HUAWEICLOUD_SDK_VPC_V2_MODEL_CreateRouteTableResponse_H_ #define HUAWEICLOUD_SDK_VPC_V2_MODEL_CreateRouteTableResponse_H_ #include <huaweicloud/vpc/v2/VpcExport.h> #include <huaweicloud/core/utils/ModelBase.h> #include <huaweicloud/core/http/HttpResponse.h> #include <huaweicloud/vpc/v2/model/RouteTableResp.h> namespace HuaweiCloud { namespace Sdk { namespace Vpc { namespace V2 { namespace Model { using namespace HuaweiCloud::Sdk::Core::Utils; using namespace HuaweiCloud::Sdk::Core::Http; /// <summary> /// Response Object /// </summary> class HUAWEICLOUD_VPC_V2_EXPORT CreateRouteTableResponse : public ModelBase, public HttpResponse { public: CreateRouteTableResponse(); virtual ~CreateRouteTableResponse(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; bool fromJson(const web::json::value& json) override; ///////////////////////////////////////////// /// CreateRouteTableResponse members /// <summary> /// /// </summary> RouteTableResp getRoutetable() const; bool routetableIsSet() const; void unsetroutetable(); void setRoutetable(const RouteTableResp& value); protected: RouteTableResp routetable_; bool routetableIsSet_; #ifdef RTTR_FLAG RTTR_ENABLE() #endif }; } } } } } #endif // HUAWEICLOUD_SDK_VPC_V2_MODEL_CreateRouteTableResponse_H_
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com