blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
76020f6747290f3b03acf149a48b41ef144526a8
549f6031b335cb387ffce493adcce31967be6759
/src/output/writer.hpp
0f807ad7944a666b3eccf8daf4c96a977a0b9c63
[ "BSD-2-Clause" ]
permissive
rollbear/crpcut
d4152dcdd80640118c473f9952a3eb18a0ea1419
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
refs/heads/master
2020-05-07T06:00:06.781863
2019-04-09T05:53:00
2019-04-09T05:53:00
180,293,662
1
1
BSD-2-Clause
2020-05-07T03:55:15
2019-04-09T05:46:17
C++
UTF-8
C++
false
false
3,417
hpp
/* * Copyright 2012 Bjorn Fahller <bjorn@fahller.se> * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 OUTPUT_WRITER_HPP #define OUTPUT_WRITER_HPP #include <iosfwd> extern "C" { # include <sys/types.h> # include <iconv.h> } #include <crpcut.hpp> namespace crpcut { namespace output { template <bool b> struct enable_if; template <> struct enable_if<true> { typedef void type; }; class buffer; class writer { public: typedef enum { translated, verbatim } type; writer(buffer& buff, const char *to_charset, const char *subst); virtual ~writer(); std::size_t write(std::string s, type t = verbatim) const { return write(s.c_str(), s.length(), t); } std::size_t write(datatypes::fixed_string s, type t = verbatim) const { return write(s.str, s.len, t); } std::size_t write(const char *s, type t = verbatim) const { return write(s, wrapped::strlen(s), t); } template <std::size_t N> std::size_t write(const char (&str)[N], type t = verbatim) const { return write(&str[0], N - 1, t); } std::size_t write(const stream::oastream &o, type t = verbatim) const { return write(o.begin(), o.size(), t); } std::size_t write(const std::ostringstream &os, type t = verbatim) const; std::size_t write(const char *str, std::size_t len, type t = verbatim) const; template <typename T> std::size_t write(T val, typename enable_if<std::numeric_limits<T>::is_integer>::type * = 0) { stream::toastream<std::numeric_limits<T>::digits10 + 2> o; o << val; return write(o); } private: virtual datatypes::fixed_string escape(char c) const; std::size_t do_write(const char *p, std::size_t len) const; std::size_t do_write_converted(const char *buff, std::size_t len) const; buffer &buffer_; iconv_t iconv_handle_; const char *illegal_substitute_; std::size_t illegal_substitute_len_; }; } } #endif // OUTPUT_WRITER_HPP
[ "bjorn@fahller.se" ]
bjorn@fahller.se
261f01374f04dbf5939f23f02c085891cca2531f
fe700e4049e166dda741d3008d3f087720fa64be
/1st term/11-2019/21-11-2019/player.h
cbea13dc657d3bae6851ed0bcae1c0de6e90435b
[]
no_license
SashoStoichkovArchive/TUES_11_OOP
cbb5528166a2565685687313a0919eb3865ff9e7
bc3721bc410175c34d5d49297e53e54444751c46
refs/heads/master
2022-11-12T23:33:06.457340
2020-06-30T11:10:54
2020-06-30T11:10:54
209,707,087
0
0
null
null
null
null
UTF-8
C++
false
false
160
h
#ifndef PLAYER_H #define PLAYER_H #include "character.h" class Player : public Character { public: int id; void set_id(int id); }; #endif
[ "sashostoichkov@gmail.com" ]
sashostoichkov@gmail.com
01e956a54b571c18887ba2607770916094aa4d2b
496d9a80ac7b1e306fdef77eb7fb45e602e5ffd9
/plugins/alexainterface/ObserverManager.cpp
d5310bb4c24d01cd920fc5f49a206faa3fc48eb4
[]
no_license
SMHPersonalRubbishery/qtvoiceassistant
98127840bf2d8b0b142ac860b78ab0c1cbc19083
799fa5a6ee2f5a322d6a6dbe407d41e674d96bac
refs/heads/master
2023-01-06T07:05:56.909089
2019-10-29T14:06:44
2019-10-29T14:36:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,116
cpp
/**************************************************************************** ** ** Copyright (C) 2019 Luxoft Sweden AB ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Neptune 3 UI. ** ** $QT_BEGIN_LICENSE:GPL-QTAS$ ** Commercial License Usage ** Licensees holding valid commercial Qt Automotive Suite licenses may use ** this file in accordance with the commercial license agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and The Qt Company. For ** licensing terms and conditions see https://www.qt.io/terms-conditions. ** For further information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 or (at your option) any later version ** approved by the KDE Free Qt Foundation. The licenses are as published by ** the Free Software Foundation and appearing in the file LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ** SPDX-License-Identifier: GPL-3.0 ** ****************************************************************************/ #include <iostream> #include <sstream> #include <AVSCommon/Utils/SDKVersion.h> #include "ObserverManager.h" #include <QDebug> using namespace alexaClientSDK::avsCommon::sdkInterfaces; ObserverManager::ObserverManager(QObject *parent) : QObject (parent) { } void ObserverManager::onSettingChanged(const std::string& key, const std::string& value) { m_executor.submit([key, value]() { std::string msg = key + " set to " + value; qDebug("SETTINGS: %s set to %s", key.c_str(), value.c_str()); //TODO: Add a signal here //TODO: should be move in a separate class }); } void ObserverManager::onSpeakerSettingsChanged( const SpeakerManagerObserverInterface::Source& source, const SpeakerInterface::Type& type, const SpeakerInterface::SpeakerSettings& settings) { m_executor.submit([source, type, settings]() { std::ostringstream oss; oss << "SOURCE:" << source << " TYPE:" << type << " VOLUME:" << static_cast<int>(settings.volume) << " MUTE:" << settings.mute; qDebug() << oss.str().c_str(); //TODO: Add a signal here //TODO: should be move in a separate class }); } void ObserverManager::onSetIndicator(avsCommon::avs::IndicatorState state) { m_executor.submit([state]() { qDebug("Notification indicator state: %d", state); //TODO: Emit a signal if this state is needed }); } //TODO: Would be good to split this into many different classes which inherit every single interface from the SDK //or at least two or three with similar meanings but not a bunch of those in the same class as it was done in the Alexa Interface
[ "enemtsev@luxoft.com" ]
enemtsev@luxoft.com
9b1cd5953c7551730522d4c5c38e86876f5d7bc6
4c8ac5a3e7feb00f4c920d6ea0bd0a30f1dfe5ce
/src/main.cpp
52ae637f46c0c52306217b7dd0bf82c57f748311
[]
no_license
YUXUANCHENG/cells
93ce4cd396eda204645ba5e596642728b8c87f51
1666af2a056325b6aacae2198088d3b51e6c2f51
refs/heads/master
2023-05-07T22:18:04.214307
2021-05-31T01:07:40
2021-05-31T01:07:40
262,202,692
0
0
null
2020-05-08T01:59:50
2020-05-08T01:59:49
null
UTF-8
C++
false
false
571
cpp
#include "cell_jamming.h" #include "CLI.h" #include "CLI_hopper.h" // use std name space using namespace std; int main(int argc, char const *argv[]){ //jamming main_function; //main_function.sp_NVE_arg(argv); //main_function.sp_NVE_tao(argv); Bumpy_CLI<> cli; //BumpyDimer_CLI<> cli; //DPM_CLI<> cli; //BumpyEllipse_CLI<> cli; //DPM_Hopper_CLI<> cli; //Bumpy_Hopper_CLI<> cli; //cli.findJamming(argv); //cli.NVE(argv); //cli.NVEvsDPhi(argv); //cli.hopperFlow(argv); //cli.deformation(argv); cli.calTao(argv); system("pause"); return 0; }
[ "yuxuancheng@outlook.com" ]
yuxuancheng@outlook.com
2cbadefc439dc173b8c22860c327a2cb62311a0d
aaf7b95178b1342ef0f7cb41cda19e8d62dd82e4
/src/P2p/PeerListManager.h
b10cca12cd27995b9dec54162502d72ecd3d6b7f
[ "MIT", "BSD-3-Clause" ]
permissive
mounirrquiba/novocoin-project
45c70b306eaa23350e2f398ae3057595dede6698
cb99bf47014343eabc0d1131d93fa050a07e430d
refs/heads/master
2020-03-10T03:07:01.908338
2018-04-09T22:29:13
2018-04-09T22:29:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,979
h
// Copyright (c) 2018 The Novocoin developers, Parts of this file are originally copyright (c) 2011-2016 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include <list> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/identity.hpp> #include <boost/multi_index/member.hpp> #include "P2pProtocolTypes.h" #include "CryptoNoteConfig.h" namespace CryptoNote { class ISerializer; /************************************************************************/ /* */ /************************************************************************/ class PeerlistManager { struct by_time{}; struct by_id{}; struct by_addr{}; typedef boost::multi_index_container< PeerlistEntry, boost::multi_index::indexed_by< // access by peerlist_entry::net_adress boost::multi_index::ordered_unique<boost::multi_index::tag<by_addr>, boost::multi_index::member<PeerlistEntry, NetworkAddress, &PeerlistEntry::adr> >, // sort by peerlist_entry::last_seen< boost::multi_index::ordered_non_unique<boost::multi_index::tag<by_time>, boost::multi_index::member<PeerlistEntry, uint64_t, &PeerlistEntry::last_seen> > > > peers_indexed; public: class Peerlist { public: Peerlist(peers_indexed& peers, size_t maxSize); size_t count() const; bool get(PeerlistEntry& entry, size_t index) const; void trim(); private: peers_indexed& m_peers; const size_t m_maxSize; }; PeerlistManager(); bool init(bool allow_local_ip); size_t get_white_peers_count() const { return m_peers_white.size(); } size_t get_gray_peers_count() const { return m_peers_gray.size(); } bool merge_peerlist(const std::list<PeerlistEntry>& outer_bs); bool get_peerlist_head(std::list<PeerlistEntry>& bs_head, uint32_t depth = CryptoNote::P2P_DEFAULT_PEERS_IN_HANDSHAKE) const; bool get_peerlist_full(std::list<PeerlistEntry>& pl_gray, std::list<PeerlistEntry>& pl_white) const; bool get_white_peer_by_index(PeerlistEntry& p, size_t i) const; bool get_gray_peer_by_index(PeerlistEntry& p, size_t i) const; bool append_with_peer_white(const PeerlistEntry& pr); bool append_with_peer_gray(const PeerlistEntry& pr); bool set_peer_just_seen(PeerIdType peer, uint32_t ip, uint32_t port); bool set_peer_just_seen(PeerIdType peer, const NetworkAddress& addr); bool set_peer_unreachable(const PeerlistEntry& pr); bool is_ip_allowed(uint32_t ip) const; void trim_white_peerlist(); void trim_gray_peerlist(); void serialize(ISerializer& s); Peerlist& getWhite(); Peerlist& getGray(); private: std::string m_config_folder; bool m_allow_local_ip; peers_indexed m_peers_gray; peers_indexed m_peers_white; Peerlist m_whitePeerlist; Peerlist m_grayPeerlist; }; }
[ "37153171+techqc@users.noreply.github.com" ]
37153171+techqc@users.noreply.github.com
cb15569046969bec01f15c2c6c101a7d5bc1272b
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_602_httpd-2.4.3.cpp
d7cb2a915a16bb2315057fa73e8ae9d56e5a5894
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,470
cpp
static APR_INLINE const char *header_inout_cmd(cmd_parms *cmd, void *indirconf, const char *action, const char *hdr, const char *value, const char *subs, const char *envclause) { headers_conf *dirconf = indirconf; const char *condition_var = NULL; const char *colon; header_entry *new; ap_expr_info_t *expr = NULL; apr_array_header_t *fixup = (cmd->info == &hdr_in) ? dirconf->fixup_in : (cmd->info == &hdr_out_always) ? dirconf->fixup_err : dirconf->fixup_out; new = (header_entry *) apr_array_push(fixup); if (!strcasecmp(action, "set")) new->action = hdr_set; else if (!strcasecmp(action, "add")) new->action = hdr_add; else if (!strcasecmp(action, "append")) new->action = hdr_append; else if (!strcasecmp(action, "merge")) new->action = hdr_merge; else if (!strcasecmp(action, "unset")) new->action = hdr_unset; else if (!strcasecmp(action, "echo")) new->action = hdr_echo; else if (!strcasecmp(action, "edit")) new->action = hdr_edit; else if (!strcasecmp(action, "edit*")) new->action = hdr_edit_r; else return "first argument must be 'add', 'set', 'append', 'merge', " "'unset', 'echo', 'edit', or 'edit*'."; if (new->action == hdr_edit || new->action == hdr_edit_r) { if (subs == NULL) { return "Header edit requires a match and a substitution"; } new->regex = ap_pregcomp(cmd->pool, value, AP_REG_EXTENDED); if (new->regex == NULL) { return "Header edit regex could not be compiled"; } new->subs = subs; } else { /* there's no subs, so envclause is really that argument */ if (envclause != NULL) { return "Too many arguments to directive"; } envclause = subs; } if (new->action == hdr_unset) { if (value) { if (envclause) { return "header unset takes two arguments"; } envclause = value; value = NULL; } } else if (new->action == hdr_echo) { ap_regex_t *regex; if (value) { if (envclause) { return "Header echo takes two arguments"; } envclause = value; value = NULL; } if (cmd->info != &hdr_out_onsuccess && cmd->info != &hdr_out_always) return "Header echo only valid on Header " "directives"; else { regex = ap_pregcomp(cmd->pool, hdr, AP_REG_EXTENDED | AP_REG_NOSUB); if (regex == NULL) { return "Header echo regex could not be compiled"; } } new->regex = regex; } else if (!value) return "Header requires three arguments"; /* Handle the envclause on Header */ if (envclause != NULL) { if (strcasecmp(envclause, "early") == 0) { condition_var = condition_early; } else if (strncasecmp(envclause, "env=", 4) == 0) { if ((envclause[4] == '\0') || ((envclause[4] == '!') && (envclause[5] == '\0'))) { return "error: missing environment variable name. " "envclause should be in the form env=envar "; } condition_var = envclause + 4; } else if (strncasecmp(envclause, "expr=", 5) == 0) { const char *err = NULL; expr = ap_expr_parse_cmd(cmd, envclause + 5, 0, &err, NULL); if (err) { return apr_pstrcat(cmd->pool, "Can't parse envclause/expression: ", err, NULL); } } else { return apr_pstrcat(cmd->pool, "Unknown parameter: ", envclause, NULL); } } if ((colon = ap_strchr_c(hdr, ':'))) { hdr = apr_pstrmemdup(cmd->pool, hdr, colon-hdr); } new->header = hdr; new->condition_var = condition_var; new->expr = expr; return parse_format_string(cmd->pool, new, value); }
[ "993273596@qq.com" ]
993273596@qq.com
9dd7dde68348e565432df98ed441d7da63da3b95
778b931b27793be88e5473042350ccc7d7fb486f
/NICV/源.cpp
33d66c6ded156b13ba18be0071941093b539858e
[]
no_license
zhoul14/SpeechCodePrime
28171a6cb59f2023c7e1f22763b16bb4033702bd
35fe89d5817433e0141e4b755209961da6ce0764
refs/heads/master
2021-01-20T15:06:48.919182
2017-05-09T07:39:28
2017-05-09T07:39:28
90,716,887
0
0
null
null
null
null
IBM852
C++
false
false
8,471
cpp
#include <iostream> #include "FeatureFileSet.h" #include "DTWCluster.h" #include "CWaveFormatFile.h" #include <string> #include <fstream> #include "EFeature.h" #include "ClusterParam.h" #include "DisCluster.h" #define MAXFRAME 5000 #define HALF_FRAMELEN 1 float threshold = 0.0f; bool AutoRate = true; int simplePointCenter = 0; int maxCCnt = 3; long long int cltCount = 0; long long int FrameCount = 0; string DirMatchMainFile(string filename){ auto iter = filename.rbegin(); while (*iter != '#') iter++; iter++; string out; while (*iter != '\\'){ out += *iter; iter++; } reverse(out.begin(), out.end()); return out; } vector<string> readWavList(string filename) { vector<string> r; ifstream infile(filename); string t; while (infile >> t) { r.push_back(t); } infile.close(); return r; } void getClusterInfoFile(const string& configName, const float& rate, const int& iterTime, const int & clusterFlag){ ClusterParam rparam(configName.c_str()); vector<RSpeechFile> inputs = rparam.getRecFiles(); vector<float> energyFeature; for (int ii = 0; ii != inputs.size(); ii++) { printf("Filesú║%.2f%%\t%s\n",(float)(ii) / inputs.size() * 100, inputs[ii].getFeatureFileName().c_str()); int p = inputs[ii].getFeatureFileName().find_last_of('/'), q = inputs[ii].getFeatureFileName().find_last_of('.'); string d45Filename = inputs[ii].getFeatureFileName(); string cltDirName = d45Filename.substr(0, p + 1)+ to_string(AutoRate ? threshold : rate).substr(0,4); if (GetFileAttributes(cltDirName.c_str()) == INVALID_FILE_ATTRIBUTES) { CreateDirectory(cltDirName.c_str(), NULL); } string outFilename = string(cltDirName + d45Filename.substr(p, q - p) + ".clt"); //string outFilename = string(d45Filename.substr(0, q) + ".clt") ; int fDim = rparam.getFdim(); long cnt = 0; long maxIter = 55; FeatureFileSet input(inputs[ii].getFeatureFileName(), inputs[ii].getMaskFileName(), inputs[ii].getAnswerFileName(), fDim); int sentence = input.getSpeechNum(); ClusterIndex* Headvec = new ClusterIndex[sentence]; int* InfoVec = new int[sentence* (MAXFRAME)]; long offset = sentence * sizeof(ClusterIndex); double fileAdjoinDistance = 0.0f, sumRate = 0.0f; int fileFrameNum = 0; for (int j = 0; j != sentence; j++) { printf("%.2f%%\r",(float)(j + 1)/sentence * 100); int segNum = input.getSegNum(j); #if HALF_FRAMELEN int fNum = input.getFrameNumInSpeech_half_framelen(j); double* features = new double[fNum * fDim]; input.getSpeechAt_half_framelen(j, features, fNum); auto speechNum = fNum; #else auto speechNum = input.getFrameNumInSpeech(j); auto firstIdx = input.getFirstFrameNumInSpeech(j); int fNum = input.getFrameNumInSpeech(j); double* features = new double[fNum * fDim]; input.getSpeechAt(j, features); int* jumpTable = new int[segNum]; input.getJumpTable(j, jumpTable); #endif int minFrameLen = (speechNum); for (int k = 0; k != maxIter; k++) { DTWCluster clust(fDim); double myrate = clust.initDistance(features, fDim, fNum, rate - k * 0.05); //clust.init((double)minFrameLen/(rate + k * 0.005), iterTime, fDim); double res = clust.doCluster(features, minFrameLen, clusterFlag, /*jumpTable*/ NULL, segNum); fileAdjoinDistance += res * minFrameLen; fileFrameNum += minFrameLen; //cout << myrate << endl; if(myrate > threshold && k < maxIter - 1 && AutoRate && rate - (k + 1) * 0.05 >=0){ continue; } sumRate += myrate; /* if(res < threshold && k < maxIter - 1 && AutoRate && rate + k *0.005 < 1.1 ){ continue; }*/ //cout<< "Rate:"<< myrate <<"res:"<<res<<endl; auto infovec = clust.getClusterInfo(simplePointCenter); for (auto ii : infovec) { InfoVec[cnt] = ii; cnt++; } Headvec[j].ClusterNum = infovec.size(); Headvec[j].offset = offset; offset += Headvec[j].ClusterNum * sizeof(float); break; } //debug //delete []jumpTable; delete []features; } //cout<<"Average AdjoinDistance:"<<fileAdjoinDistance/fileFrameNum<<endl; cout<<"Average sumRate:"<<sumRate/sentence<<endl; FILE* fp = fopen(outFilename.c_str(),"wb+"); fwrite(Headvec, sizeof(ClusterIndex) ,sentence, fp); fwrite(InfoVec, sizeof(long), cnt, fp); fclose(fp); delete []Headvec; delete []InfoVec; } } void getClusterInfoFileDis(const string& configName, const float& rate, const int& iterTime, const int & clusterFlag){ ClusterParam rparam(configName.c_str()); vector<RSpeechFile> inputs = rparam.getRecFiles(); vector<float> energyFeature; for (int ii = 0; ii != inputs.size(); ii++) { printf("Filesú║%.2f%%\t%s\n",(float)(ii) / inputs.size() * 100, inputs[ii].getFeatureFileName().c_str()); int p = inputs[ii].getFeatureFileName().find_last_of('/'), q = inputs[ii].getFeatureFileName().find_last_of('.'); string d45Filename = inputs[ii].getFeatureFileName(); //string cltDirName = d45Filename.substr(0, p + 1)+ to_string(AutoRate ? threshold : rate).substr(0,4); string cltDirName = d45Filename.substr(0, p + 1)+ to_string(rate * 100).substr(0,4); if (GetFileAttributes(cltDirName.c_str()) == INVALID_FILE_ATTRIBUTES) { CreateDirectory(cltDirName.c_str(), NULL); } string outFilename = string(cltDirName + d45Filename.substr(p, q - p) + ".clt"); //string outFilename = string(d45Filename.substr(0, q) + ".clt") ; int fDim = rparam.getFdim(); long cnt = 0; FeatureFileSet input(inputs[ii].getFeatureFileName(), inputs[ii].getMaskFileName(), inputs[ii].getAnswerFileName(), fDim); int sentence = input.getSpeechNum(); ClusterIndex* Headvec = new ClusterIndex[sentence]; int* InfoVec = new int[sentence* (MAXFRAME)]; long offset = sentence * sizeof(ClusterIndex); double fileAdjoinDistance = 0.0f, sumRate = 0.0f; int fileFrameNum = 0; for (int j = 0; j != sentence; j++) { printf("%.2f%%\r",(float)(j + 1)/sentence * 100); #if HALF_FRAMELEN int fNum = input.getFrameNumInSpeech_half_framelen(j); auto speechNum1 = input.getFrameNumInSpeech(j); double* features = new double[fNum * fDim]; input.getSpeechAt_half_framelen(j, features, fNum); auto speechNum = fNum; #else auto speechNum = input.getFrameNumInSpeech(j); auto firstIdx = input.getFirstFrameNumInSpeech(j); int fNum = input.getFrameNumInSpeech(j); double* features = new double[fNum * fDim]; input.getSpeechAt(j, features); int* jumpTable = new int[segNum]; input.getJumpTable(j, jumpTable); #endif int minFrameLen = (speechNum); DisCluster clust(fDim); clust.init(fDim, rate, maxCCnt); //clust.init((double)minFrameLen/(rate + k * 0.005), iterTime, fDim); double res = clust.doCluster(features, minFrameLen);//, clusterFlag, /*jumpTable*/ NULL, segNum); vector<int> infovec = clust.getClusterInfo(); //cout<< "rate:" << 1/res << endl; sumRate += 1/res; for (auto ii : infovec) { InfoVec[cnt] = ii; cnt++; } Headvec[j].ClusterNum = infovec.size(); Headvec[j].offset = offset; offset += Headvec[j].ClusterNum * sizeof(float); cltCount += infovec.size(); FrameCount += minFrameLen; //debug delete []features; } //cout<<"Average AdjoinDistance:"<<fileAdjoinDistance/fileFrameNum<<endl; cout<<"Average sumRate:"<<sumRate/sentence<<endl; FILE* fp = fopen(outFilename.c_str(),"wb+"); fwrite(Headvec, sizeof(ClusterIndex) ,sentence, fp); fwrite(InfoVec, sizeof(long), cnt, fp); fclose(fp); delete []Headvec; delete []InfoVec; } } // Dtw.exe rate iterTime threshold MeanCenter simplePointCenter int main(int argc, char** argv){ string configFile(argv[1]); float rate = atof(argv[2]); rate /= 100; maxCCnt = atof(argv[3]); int iterTime = 1; if (argc > 4) { //iterTime = atof(argv[3]); threshold = atof(argv[4]); AutoRate = threshold != 0.0f; } int clusterflag = DTWCluster::MEAN_CENTER; cout<<"argc:"<<argc<<endl; if (argc >= 6) { clusterflag = atof(argv[5]); if(clusterflag == 0)cout << "Mean_Center" << endl; if(clusterflag == 5)cout << "Medoid_Center" << endl; cout << "clusterFlage" << clusterflag <<endl; } if (argc == 7) { simplePointCenter = atof(argv[6]); if(simplePointCenter != 0)cout << "simplePointCenter " << endl; } getClusterInfoFileDis(configFile, rate, iterTime, clusterflag); FILE* f = fopen((/*to_string(rate*100)*/string("log") + ".txt").c_str(),"a+"); fprintf(f,"%f %lf\n",rate * 100,((double)FrameCount/cltCount)); fclose(f); return 0; }
[ "1214279441@qq.com" ]
1214279441@qq.com
010e0d48e3e262fcb46b8983cdb8839f6415d05b
40e60e01ede0b99f14d5e01603e0cd15009b98dc
/Round2_492/R2_492A.cpp
fc193a947e35ce9addba0f5166fe448e873840b9
[]
no_license
mylvoh0714/Codeforces
d01de00928a7f075fc5e0fc7c656b028a646b1c0
7339a1b8de4d0d95d38f293822628c37b202c65c
refs/heads/master
2020-03-25T15:34:11.883461
2018-11-16T10:43:06
2018-11-16T10:43:06
143,882,211
0
0
null
null
null
null
UTF-8
C++
false
false
288
cpp
#include <iostream> #include <vector> using namespace std; int main() { int ans = 0; cin.tie(NULL); ios_base::sync_with_stdio(false); int n; cin >> n; ans += n/100; n %= 100; ans += n/20; n %= 20; ans += n/10; n %= 10; ans += n/5; n %= 5; ans += n; cout << ans << '\n'; }
[ "mylvoh0714@gmail.com" ]
mylvoh0714@gmail.com
b516ef225e5f427b44e52bc04b117dfec0ea90fb
f45c8775c0517fdc46939e6d5d728a09a7fe55e3
/codeforces/1238/A.cpp
71192100262b8184b8137068cfaecf1917da40ae
[]
no_license
Radhesh-Sarma/Competitive-Coding
6550af86545d7456923c559a78784af201f57e4e
ce71acaa912249717a8f6cbf7584034548db7951
refs/heads/main
2023-02-23T09:40:57.401882
2021-01-31T15:53:24
2021-01-31T15:53:24
191,410,831
0
1
null
2019-06-11T16:34:32
2019-06-11T16:34:31
null
UTF-8
C++
false
false
1,548
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 int long long #define all(v) v.begin(),v.end() #define rep(i,a,b) for(int i = a; i <=b; i++) #define rep2(i,a,b) for(int i = a; i>=b; i--) #define f first #define s second #define PB push_back #define MP make_pair #define db long double #define trace1(x) cerr<<#x<<": "<<x<<endl #define trace2(x, y) cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl #define trace3(x, y, z) cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl #define trace4(a, b, c, d) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl #define trace5(a, b, c, d, e) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl #define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl #define cases int testcases;cin>>testcases; while(testcases--) int32_t main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif cases { int x,y; cin >> x >> y; if(x == y+1) { cout << "NO" << endl; } else { cout << "YES" << endl; } } return 0; }
[ "radhesh@pop-os.localdomain" ]
radhesh@pop-os.localdomain
4c060fbecbd8b8eebb0dd199b80e0d55ad035f7b
b6c9433cefda8cfe76c8cb6550bf92dde38e68a8
/epoc32/include/mw/remconmediabrowsepanic.h
25866fc0cb96366f9c61c51e0638abc30d269dfa
[]
no_license
fedor4ever/public-headers
667f8b9d0dc70aa3d52d553fd4cbd5b0a532835f
3666a83565a8de1b070f5ac0b22cc0cbd59117a4
refs/heads/master
2021-01-01T05:51:44.592006
2010-03-31T11:33:34
2010-03-31T11:33:34
33,378,397
0
0
null
null
null
null
UTF-8
C++
false
false
1,123
h
// Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // /** @file @publishedAll @released */ #ifndef REMCONMEDIABROWSEPANIC_H #define REMCONMEDIABROWSEPANIC_H #include <e32base.h> _LIT(KMediaBrowsePanicName, "RcMediaBrowse"); enum TRemConMediaBrowsePanic { EFolderListingProvidedTwice = 0, EFolderItemResultWithoutRequest = 1, EInvalidFolderType = 2, EInvalidPlayableValue = 3, EInvalidMediaType = 4, EMediaElementItemResultWithoutRequest = 5, ESearchResultWithoutRequest = 6, /** The value of the media library state cookie must not be zero. */ EZeroMediaLibraryStateCookie = 7, }; class MediaBrowsePanic { public: static void Panic(TRemConMediaBrowsePanic aPanic); }; #endif //REMCONMEDIABROWSEPANIC_H
[ "williamr@symbian.org" ]
williamr@symbian.org
e656fd2ac8e37189c723469fa290f2f821061261
3065c354273b4e31892f836294e1c71c176c82a4
/Classes/Pushui/CLoginDay.cpp
573ebe9d5d244138e0ddf04e1763d7646a3ac778
[]
no_license
kerasking/magicpet
ca2d27568d875b5d48a0287d0761fc5c1620b6e8
a482cc06fdcb73e2a99b8be315df969e8a9882d4
refs/heads/master
2021-05-28T04:10:14.619895
2012-10-16T05:39:37
2012-10-16T05:39:37
null
0
0
null
null
null
null
GB18030
C++
false
false
1,702
cpp
/*****************************************************************************/ //File name: filecpp //Author: huyan //Description: 任务完成弹出界面、 /******************************************************************************/ #include "CLoginDay.h" #include "../GameConstant.h" #include "../CGameMessage.h" #include "../Sprite/CPet.h" CLoginDay::CLoginDay( ) { } //------------------------------------------------------------------ // // CLoginDay::~CLoginDay() { } //--------------------------------------------------------------------- // // void CLoginDay::onEnter() { CCXMLLayer::onEnter(); LoadPlist( "Landaward.plist" ); CCNode *pNode = GetXMLNodeFromKey( "t2dSceneObject_money" ); CCLabelTTF *pLabel = CCLabelTTF::labelWithString( "+1000", kFontSystem[FONT_LARGE].fontName, kFontSystem[FONT_LARGE].fontSize ); pLabel->setPosition( pNode->getPosition() ); pLabel->setColor( ccBlack ); addChild( pLabel,100 ); pNode = GetXMLNodeFromKey( "t2dSceneObject_stamina" ); pLabel = CCLabelTTF::labelWithString( "+100", kFontSystem[FONT_LARGE].fontName, kFontSystem[FONT_LARGE].fontSize ); pLabel->setPosition( pNode->getPosition() ); pLabel->setColor( ccBlack ); addChild( pLabel,100 ); g_pPetDataBlock->maxstaminapoint = 100; g_pPetDataBlock->petmoney += 1000; } void CLoginDay::FadeOut() { for( int i = 0; i < getChildren()->count(); i ++ ) { ((CCNode*)(getChildren()->objectAtIndex(i)))->runAction( CCSequence::actions( CCDelayTime::actionWithDuration(3.0f), CCFadeOut::actionWithDuration( 5.0f ),NULL ) ); } } //----------------------------------------------------------------------- // // void CLoginDay::onExit() { CCXMLLayer::onExit(); }
[ "huyanoperation@163.com" ]
huyanoperation@163.com
a4aabb217cb344e52d1fdbcd830b6d6c4d3c326d
0784ac6ffc07d57f90ee24e05b37be8fdeb8e6ff
/src/qt/guiutil.cpp
cfd8686d6c100194142b4e811788c136031a6709
[ "MIT" ]
permissive
shapeshifter1/lycancoin-release
55a2c14345711f0170b6dd9afde06e7347124fa0
fbf9313502b35a7a88c40b28789457ff3f996649
refs/heads/master
2021-05-03T13:37:16.230391
2014-11-04T07:02:50
2014-11-04T07:02:50
120,510,917
0
0
null
2018-02-06T19:16:01
2018-02-06T19:16:01
null
UTF-8
C++
false
false
13,505
cpp
#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include "base58.h" #include <QString> #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { if(uri.scheme() != QString("Lycancoin")) return false; // check if the address is valid CBitcoinAddress addressFromUri(uri.path().toStdString()); if (!addressFromUri.IsValid()) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert lycancoin:// to lycancoin: // // Cannot handle this later, because lycancoin:// will cause Qt to see the part after // as host, // which will lowercase it (and thus invalidate the address). if(uri.startsWith("lycancoin://")) { uri.replace(0, 11, "lycancoin:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.LYC)" or "Description (*.LYC *.LYC ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt/>" + HtmlEscape(tooltip, true); widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "lycancoin.lnk"; } bool GetStartOnSystemStartup() { // check for lycancoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "lycancoin.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a lycancoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=lycancoin\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("Lycancoin-qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " Lycancoin-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("lycancoin-qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in nonbreaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stderr, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
[ "root@ubuntu.(none)" ]
root@ubuntu.(none)
7444a306f7f0f74e7ef1fb431d33dff6bc34b087
90118fe5f8b37ae7100a90e1861d870def26b010
/vertex.cpp
b376521504719e3ff17d0b7ac418ed3071cd02df
[]
no_license
o-farag/SoftbodySim
d0bdb39345faae1ba663f6bfa5197d733e8c6eca
9c354df9324ff40c4a0357c0377cefed30d80379
refs/heads/main
2023-04-23T22:43:17.860981
2021-05-07T05:06:07
2021-05-07T05:06:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
295
cpp
#include "vertex.h" #include "globals.h" squishPoint::squishPoint(float x, float y) { position = sf::Vector2f(x, y); this->shape.setRadius(10.f); this->shape.setFillColor(sf::Color::Red); this->shape.setPosition(x, y); } void squishPoint::CreatePoint(float x, float y) { }
[ "omar.farag@mail.utoronto.ca" ]
omar.farag@mail.utoronto.ca
9f8a1b5d530162333c14eb275b40c41fbb5e9da5
8c815edc0713520c0b743d3e45754cba7531be18
/MyPhysics/DynamicDlg.h
05a42f1eea0d7bbd8727c7a632e434f5460cb0d9
[]
no_license
shutuu/MyPhysics3D
76eb8f464e7ebd5ac90dbf1456e78347bf9ecd49
8ba10988297e2edcff4a2e0dc0490b1154fcdd57
refs/heads/master
2020-04-05T15:41:17.750980
2015-04-12T14:43:42
2015-04-12T14:43:42
null
0
0
null
null
null
null
GB18030
C++
false
false
669
h
#pragma once #include "resource.h" #include "globals.h" // CDynamicDlg 对话框 class CDynamicDlg : public CDialog { DECLARE_DYNAMIC(CDynamicDlg) public: CDynamicDlg(const MyObject* object, CWnd* pParent = NULL); virtual ~CDynamicDlg(); // 对话框数据 enum { IDD = IDD_DYNAMIC }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: float vlx; float vly; float vlz; float vax; float vay; float vaz; float ilx; float ily; float ilz; float iax; float iay; float iaz; float flx; float fly; float flz; float fax; float fay; float faz; };
[ "wsysuper@gmail.com" ]
wsysuper@gmail.com
113eacf77c44d8381ec9e22a77d05fa6b5e89305
f600632b57c6dd003f3c72d703643f61433e2edc
/Arrays/longest-consecutive-subsequence.cpp
98816e113994a1c3b4fb0002347f7f0f366a8f47
[]
no_license
EesarapuAkshay/Coding
51b2fb7b772f938f1b8ca17cb504519d88ad182c
e8925118c7edf6b65b7672be430bed06ec32209a
refs/heads/main
2023-07-16T23:18:03.351743
2021-08-25T18:27:36
2021-08-25T18:27:36
373,233,205
0
0
null
null
null
null
UTF-8
C++
false
false
722
cpp
//https://practice.geeksforgeeks.org/problems/longest-consecutive-subsequence2449/1# class Solution{ public: // arr[] : the input array // N : size of the array arr[] //Function to return length of longest subsequence of consecutive integers. int findLongestConseqSubseq(int arr[], int N) { //Your code here int hash[1000000]={0}; for(int i=0;i<N;i++){ hash[arr[i]]++; } int max=0,cnt=0; for(int i=1;i<1000000;i++){ if(hash[i]>=1){ cnt++; if(cnt>max){ max=cnt; } } else{ cnt=0; } } return max; } };
[ "noreply@github.com" ]
EesarapuAkshay.noreply@github.com
0e21e1c00772373f3b07751faac62679391b89dd
eb47bf8011f957e95a84ac64aab29598c59081a1
/src/Body/VisionSensor.h
683cbaf9a728ceff423a8d513a181a0c92d14bbf
[ "Zlib", "MIT" ]
permissive
choreonoid/choreonoid
fd776aaab99d9ec544e5ceec04fbc283b8a3aee3
94b353722d5b9ff10e9c0ca8982e549f85b5f59f
refs/heads/master
2023-09-01T12:27:17.849641
2023-08-04T13:54:12
2023-08-04T13:54:12
274,977,786
117
30
NOASSERTION
2023-05-23T08:25:33
2020-06-25T17:36:56
C++
UTF-8
C++
false
false
1,737
h
#ifndef CNOID_BODY_VISION_SENSOR_H #define CNOID_BODY_VISION_SENSOR_H #include "Device.h" #include <memory> #include "exportdecl.h" namespace cnoid { class Mapping; class CNOID_EXPORT VisionSensor : public Device { public: VisionSensor(); VisionSensor(const VisionSensor& org, bool copyStateOnly = false); void copyVisionSensorStateFrom(const VisionSensor& other); virtual void forEachActualType(std::function<bool(const std::type_info& type)> func) override; virtual bool on() const override; virtual void on(bool on) override; const Matrix3& opticalFrameRotation() const { return spec->R_optical; } template<typename Derived> void setOpticalFrameRotation(const Eigen::MatrixBase<Derived>& R) { spec->R_optical = R; } enum OpticalFrameType { GL, CV, Robotics }; static const Matrix3& opticalFrameRotationOfType(int opticalFrameType); void setOpticalFrame(int opticalFrameType); double frameRate() const { return frameRate_; } void setFrameRate(double r) { frameRate_ = r; } /** Time [s] consumed in shooting the current image */ double delay() const { return delay_; } void setDelay(double time) { delay_ = time; } static int visionSensorStateSize(); virtual const double* readState(const double* buf) override; virtual double* writeState(double* out_buf) const override; bool readSpecifications(const Mapping* info); bool writeSpecifications(Mapping* info) const; private: bool on_; double frameRate_; double delay_; struct Spec { EIGEN_MAKE_ALIGNED_OPERATOR_NEW Matrix3 R_optical; }; std::unique_ptr<Spec> spec; }; typedef ref_ptr<VisionSensor> VisionSensorPtr; } #endif
[ "s.nakaoka@gmail.com" ]
s.nakaoka@gmail.com
adb04faf7cac7f1665c9fe805d2e4a8c49b3de62
bf9d7e9ff077e26219a73cbbbc468c2806ae6b7f
/MapleStory/SceneManager.h
cf61c92a7848edc0043375a72628104e5c1d6ad4
[]
no_license
OnAndOff-Game/MapleStory
1ddb15223959ff56eec979fa6271c49f88a6d53c
f528fb0b6d3790c39f2102a39c43a89914ec303a
refs/heads/master
2023-07-20T04:54:45.293074
2019-08-30T09:42:41
2019-08-30T09:42:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
401
h
#pragma once class SceneManager { public: SceneManager(); void LoadScene(const char *pName); void LoadScene(int index); void RenderScene(Gdiplus::Graphics* _memG); void Init(); void Update(float Delta); void SendLButtonDown(UINT nFlags, CPoint point); void Release(); Scene* GetCurScene(); static SceneManager& GetInstance(); private: std::vector<Scene*> mScene; Scene* CurScene; };
[ "ndp0426@gmail.com" ]
ndp0426@gmail.com
e5e3fcc9b38204cf7889c6e630b2cb3fabbf95a5
5bc9095b81b31df526ab74968f0c90aa328517b5
/03-Bit Magic/C-06-Power of two more efficient 2.cpp
ccd6164f05a1a63d89f9dd5d8b7d33a46f4a038c
[]
no_license
MIRRORPIE/Geeksforgeeks-DSA
a86249916a6b295f9f823f4583945dbf8d87ff10
fe3178f7a132e3982ad6572e775b11889aebb106
refs/heads/main
2023-01-06T07:44:50.941218
2020-11-06T19:26:33
2020-11-06T19:26:33
303,091,734
0
0
null
null
null
null
UTF-8
C++
false
false
205
cpp
#include <iostream> using namespace std; bool isPow2(int n) { if(n == 0) return true; return ((n & (n - 1)) == 0); } int main() { int n = 4; printf("%s", isPow2(n)? "true": "false"); }
[ "raushankumar1047@pec.edu" ]
raushankumar1047@pec.edu
e0b321de410b2223c08a8d3734cbd470e92ecff0
3578980634bc1c579e765a567d051ec50b257b85
/Source/App.h
65f3c31757826145e4f9c4aea0525d825bc29880
[]
no_license
konglor/PatchServer
dc29b8e29732fc8b0410188c91a7165d83418746
763bac27a6bbc174c8306e9f1ce6e471aabf7e8d
refs/heads/master
2022-01-20T07:56:55.888821
2019-07-16T20:38:21
2019-07-16T20:38:21
193,952,714
0
0
null
null
null
null
UTF-8
C++
false
false
325
h
#ifndef __APP_H__ #define __APP_H__ #include "PatchServer.h" #include "GateServer.h" class PatchApp { private: PatchServer* m_pPatchServer; GateServer* m_pGateServer; Thread* m_tPatchThread; Thread* m_tGateThread; public: PatchApp(); ~PatchApp(); void init(); void shut(); }; extern PatchApp g_PatchApp; #endif
[ "kmlor031@gmail.com" ]
kmlor031@gmail.com
9b6503a19116b36a17bed0f1bfcba72d292a36e1
5c23b302684f260fbbad2edfe19dd7cf16fd822c
/ch15/exercise_15_15_main.cpp
462108d8afdb9d8e31c778169944c239fdc263a7
[]
no_license
platoTao/CPP_Primer_Answer
123c99b0283ba15d51037cf16f2a6886b570d394
b1837239c9d58e54587f7a5ae44ee220238f5c95
refs/heads/master
2021-04-03T06:43:04.089574
2018-06-10T06:25:57
2018-06-10T06:25:57
124,714,759
0
0
null
null
null
null
UTF-8
C++
false
false
112
cpp
#include"Bulk_quote.h" int main() { Bulk_quote item("x",4.5,10,0.1); print_total(std::cout,item,30); }
[ "1209015200@qq.com" ]
1209015200@qq.com
333dfdb8a943f8716b2843c693781666c9dc5ce7
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
/textproc/isearch/patches/patch-src_infix2rpn.cxx
109f624a59d629a6376dcacd809490b68bd2b64d
[]
no_license
NetBSD/pkgsrc
a0732c023519650ef821ab89c23ab6ab59e25bdb
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
refs/heads/trunk
2023-09-01T07:40:12.138283
2023-09-01T05:25:19
2023-09-01T05:25:19
88,439,572
321
138
null
2023-07-12T22:34:14
2017-04-16T20:04:15
null
UTF-8
C++
false
false
965
cxx
$NetBSD: patch-src_infix2rpn.cxx,v 1.1 2012/12/21 10:29:47 dholland Exp $ Chase after the C++ standard: - use "std" qualification - string constants are const char * --- src/infix2rpn.cxx~ 1998-05-12 16:49:08.000000000 +0000 +++ src/infix2rpn.cxx @@ -241,7 +241,7 @@ INFIX2RPN::ProcessOp(const operators op, //standardizes the various possible representations of //the various operators. -CHR * +const CHR * INFIX2RPN::StandardizeOpName(const STRING op) { if ( (op ^= "AND") || (op == "&&") ) return "AND"; @@ -261,13 +261,13 @@ INFIX2RPN::StandardizeOpName(const STRIN //converts the internal operator token name to a standard string -CHR * +const CHR * INFIX2RPN::op2string(const operators op) { switch(op) { case LeftParen: case NOP: //shouldn't happen, but makes gcc -WALL happy. - cerr << "LeftParen || NOP?" << endl; + std::cerr << "LeftParen || NOP?" << std::endl; break; case BoolOR: return "OR";
[ "dholland@pkgsrc.org" ]
dholland@pkgsrc.org
75532af670d2c1f4de0a56cba337b4f3e3ad72f4
4d5cf5fc9dc3b6a08797eac7af9d12c2725ced70
/raspi_temp_server/main.cpp
48d82ff39527f909c086db18e68bd1fa768042b6
[]
no_license
mholmes633/raspi_temp_server
a4c8b708363d1cb486d7f3aba3b20f152ea0aac2
2d1bf563e593a463892da7047076ec58f838efbd
refs/heads/master
2021-05-21T22:42:55.171041
2020-04-03T20:51:42
2020-04-03T20:51:42
252,838,452
0
0
null
null
null
null
UTF-8
C++
false
false
3,949
cpp
#include <iostream> #include "dht22.h" #include <wiringPi.h> #include <unistd.h> #include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #include <arpa/inet.h> #define PORT 54000 #define CELSIUS 1 #define FAHRENHEIT 0 int main(void) { dht22* pDHT22 = new dht22(); if (wiringPiSetup() == -1) exit(EXIT_FAILURE); int server_fd, new_socket, valread, err; struct sockaddr_in address; int opt = 1; int addrlen = sizeof(address); char buffer[1024] = { 0 }; // Creating socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Forcefully attaching socket to the port 8080 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("192.168.1.51"); address.sin_port = htons(PORT); // Forcefully attaching socket to the port 8080 if (bind(server_fd, (struct sockaddr*) & address, sizeof(address)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } if ((new_socket = accept(server_fd, (struct sockaddr*) & address, (socklen_t*)&addrlen)) < 0) { perror("accept"); exit(EXIT_FAILURE); } bool loop = true; bool connected = true; while (loop) { if (connected == true) { valread = read(new_socket, buffer, 1024); printf("%s\n", buffer); if (valread == 0) break; if (buffer[0] == 'q') { connected = false; shutdown(server_fd, SHUT_RDWR); } else if (buffer[0] == 'r') { err = pDHT22->readDHT22(FAHRENHEIT); if (err == 0) { sprintf(buffer, "%.0f degF %.0f %%", pDHT22->getTemperature(), pDHT22->getHumidity()); send(new_socket, buffer, strlen(buffer), 0); } else { sprintf(buffer, "DHT22 read error ... try again"); send(new_socket, buffer, strlen(buffer), 0); } } else { send(new_socket, buffer, strlen(buffer), 0); } } else { // Creating socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Forcefully attaching socket to the port 8080 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("192.168.1.51"); address.sin_port = htons(PORT); // Forcefully attaching socket to the port 8080 if (bind(server_fd, (struct sockaddr*) & address, sizeof(address)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } if ((new_socket = accept(server_fd, (struct sockaddr*) & address, (socklen_t*)&addrlen)) < 0) { perror("accept"); exit(EXIT_FAILURE); } connected = true; } } return 0; }
[ "mikeholmes633@gmail.com" ]
mikeholmes633@gmail.com
213c96f9b3c008bb82e947fd7ce61d1a25ebb03c
bb622c05d5138d295509a4185725510a54f7974c
/src/qt/paymentserver.cpp
08190ebd46accb9a48ffe9e9ecbcd9df338928f7
[]
no_license
Sandy-Project/grumpycoin
531df1099537a9897e13c13c75fbdb0c9ce547f4
3f686cd6c033770c4067430b7caca35344b6e2ba
refs/heads/master
2021-01-18T06:09:56.990505
2014-04-04T05:43:39
2014-04-04T05:43:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,576
cpp
// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2013-2079 Dr. Kimoto Chan // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "paymentserver.h" #include "guiconstants.h" #include "ui_interface.h" #include "util.h" #include <QByteArray> #include <QDataStream> #include <QDebug> #include <QFileOpenEvent> #include <QHash> #include <QLocalServer> #include <QLocalSocket> #include <QStringList> #if QT_VERSION < 0x050000 #include <QUrl> #endif using namespace boost; const int GRUMPYCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds const QString GRUMPYCOIN_IPC_PREFIX("grumpycoin:"); // // Create a name that is unique for: // testnet / non-testnet // data directory // static QString ipcServerName() { QString name("GrumpyCoinQt"); // Append a simple hash of the datadir // Note that GetDataDir(true) returns a different path // for -testnet versus main net QString ddir(GetDataDir(true).string().c_str()); name.append(QString::number(qHash(ddir))); return name; } // // This stores payment requests received before // the main GUI window is up and ready to ask the user // to send payment. // static QStringList savedPaymentRequests; // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // bool PaymentServer::ipcSendCommandLine() { bool fResult = false; const QStringList& args = qApp->arguments(); for (int i = 1; i < args.size(); i++) { if (!args[i].startsWith(GRUMPYCOIN_IPC_PREFIX, Qt::CaseInsensitive)) continue; savedPaymentRequests.append(args[i]); } foreach (const QString& arg, savedPaymentRequests) { QLocalSocket* socket = new QLocalSocket(); socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); if (!socket->waitForConnected(GRUMPYCOIN_IPC_CONNECT_TIMEOUT)) return false; QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << arg; out.device()->seek(0); socket->write(block); socket->flush(); socket->waitForBytesWritten(GRUMPYCOIN_IPC_CONNECT_TIMEOUT); socket->disconnectFromServer(); delete socket; fResult = true; } return fResult; } PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true) { // Install global event filter to catch QFileOpenEvents on the mac (sent when you click grumpycoin: links) parent->installEventFilter(this); QString name = ipcServerName(); // Clean up old socket leftover from a crash: QLocalServer::removeServer(name); uriServer = new QLocalServer(this); if (!uriServer->listen(name)) qDebug() << tr("Cannot start grumpycoin: click-to-pay handler"); else connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); } bool PaymentServer::eventFilter(QObject *object, QEvent *event) { // clicking on grumpycoin: URLs creates FileOpen events on the Mac: if (event->type() == QEvent::FileOpen) { QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event); if (!fileEvent->url().isEmpty()) { if (saveURIs) // Before main window is ready: savedPaymentRequests.append(fileEvent->url().toString()); else emit receivedURI(fileEvent->url().toString()); return true; } } return false; } void PaymentServer::uiReady() { saveURIs = false; foreach (const QString& s, savedPaymentRequests) emit receivedURI(s); savedPaymentRequests.clear(); } void PaymentServer::handleURIConnection() { QLocalSocket *clientConnection = uriServer->nextPendingConnection(); while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) clientConnection->waitForReadyRead(); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); QDataStream in(clientConnection); in.setVersion(QDataStream::Qt_4_0); if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { return; } QString message; in >> message; if (saveURIs) savedPaymentRequests.append(message); else emit receivedURI(message); }
[ "grumpycoin@gmail.com" ]
grumpycoin@gmail.com
bd5fa32d071f8835504e5a2dfaef2871acc96f43
948e99a7b8dd581dc3b024481063a21c0cd0a4a4
/PDxProjects/PSC_TBSExporter/PMatrixExp.cpp
261d4a539c3706090eb031bc365d3f9f247bd152
[ "Apache-2.0" ]
permissive
bear1704/DX11_Portfolio
70be74f821f58d1c538fcb2d4b32b4d27cbf92d4
8ab70c793cf7f10eceaea34afb786264828c09a0
refs/heads/master
2021-02-16T22:56:19.258566
2020-03-05T02:28:02
2020-03-05T02:28:02
245,050,671
0
0
null
null
null
null
UHC
C++
false
false
5,824
cpp
#include "pch.h" #include "PMatrixExp.h" void PMatrixExp::PreProcess(INode* node) { if (node == nullptr) return; AddObject(node); int numberof_children = node->NumberOfChildren(); for (int i = 0; i < numberof_children; i++) { INode* child = node->GetChildNode(i); PreProcess(child); } } bool PMatrixExp::Export() { SwitchAllNodeToMesh(); scene_.numberof_materials = pmtl_list_.size(); scene_.numberof_meshes = mesh_list_.size(); _wfopen_s(&file, filename_.c_str(), _T("wb")); _ftprintf(file, _T("%s %d"), _T("MatrixExporter_v2"), object_list_.size()); _ftprintf(file, _T("\n%s"), L"#HEADER INFO [FirstFrame/LastFrame/FrameRate/TickPerFrame/MeshListSize/PMaterialListSize] "); _ftprintf(file, _T("\n%d %d %d %d %d %d"), scene_.first_frame, scene_.last_frame, scene_.frame_rate, scene_.tick_per_frame, scene_.numberof_meshes, scene_.numberof_materials); for (int imesh = 0; imesh < mesh_list_.size(); imesh++) { //mesh list _ftprintf(file, _T("\n%s"), L"#OBJECT INFO [MeshListName/ParentName/TRILISTSIZE/Box max xzy/Box min xzy]"); _ftprintf(file, _T("\n%s %s %d %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f"), mesh_list_[imesh].name, mesh_list_[imesh].parent_name, mesh_list_[imesh].tri_list.size(), mesh_list_[imesh].bounding_box.pmax.x, mesh_list_[imesh].bounding_box.pmax.z, mesh_list_[imesh].bounding_box.pmax.y, mesh_list_[imesh].bounding_box.pmin.x, mesh_list_[imesh].bounding_box.pmin.z, mesh_list_[imesh].bounding_box.pmin.y); _ftprintf(file, _T("\n#WORLD MATRIX")); _ftprintf(file, _T("\n\t%10.4f %10.4f %10.4f %10.4f\n\t%10.4f %10.4f %10.4f %10.4f\n\t%10.4f %10.4f %10.4f %10.4f\n\t%10.4f %10.4f %10.4f %10.4f"), mesh_list_[imesh].world_d3d._11, mesh_list_[imesh].world_d3d._12, mesh_list_[imesh].world_d3d._13, mesh_list_[imesh].world_d3d._14, mesh_list_[imesh].world_d3d._21, mesh_list_[imesh].world_d3d._22, mesh_list_[imesh].world_d3d._23, mesh_list_[imesh].world_d3d._24, mesh_list_[imesh].world_d3d._31, mesh_list_[imesh].world_d3d._32, mesh_list_[imesh].world_d3d._33, mesh_list_[imesh].world_d3d._34, mesh_list_[imesh].world_d3d._41, mesh_list_[imesh].world_d3d._42, mesh_list_[imesh].world_d3d._43, mesh_list_[imesh].world_d3d._44); mesh_list_[imesh].tri_list; auto subtri_list = mesh_list_[imesh].buffer_list; for (int iSubTri = 0; iSubTri < subtri_list.size(); iSubTri++) { std::vector<PNCT>& vertex_list = mesh_list_[imesh].vertex_list[iSubTri]; _ftprintf(file, _T("\nVertexList %d"), vertex_list.size()); for (int iver = 0; iver < vertex_list.size(); iver++) { _ftprintf(file, _T("\n%10.4f %10.4f %10.4f"), vertex_list[iver].p.x, vertex_list[iver].p.y, vertex_list[iver].p.z); _ftprintf(file, _T(" %10.4f %10.4f %10.4f"), vertex_list[iver].n.x, vertex_list[iver].n.y, vertex_list[iver].n.z); _ftprintf(file, _T(" %10.4f %10.4f %10.4f %10.4f"), vertex_list[iver].c.x, vertex_list[iver].c.y, vertex_list[iver].c.z, vertex_list[iver].c.w); _ftprintf(file, _T(" %10.4f %10.4f"), vertex_list[iver].t.x, vertex_list[iver].t.y); } std::vector<int> index_list = mesh_list_[imesh].index_list[iSubTri]; _ftprintf(file, _T("\nIndexList %d"), index_list.size()); for (int index = 0; index < index_list.size(); index += 3) { _ftprintf(file, _T("\n%d %d %d"), index_list[index + 0], index_list[index + 1], index_list[index + 2]); } } ExportAnimation(mesh_list_[imesh]); } fclose(file); MessageBox(GetActiveWindow(), filename_.c_str(), _T("Succeed!"), MB_OK); return false; } bool PMatrixExp::SwitchAllNodeToMesh() { for (int i = 0; i < object_list_.size(); i++) { INode* node = object_list_[i]; PMesh mesh; mesh.name = FixupName(node->GetName()); INode* parent_node = node->GetParentNode(); if (parent_node && parent_node->IsRootNode() == false) mesh.parent_name = FixupName(parent_node->GetName()); Matrix3 world_3dsmax = node->GetNodeTM(interval_.Start()); CopyMatrix3(mesh.world_d3d, world_3dsmax); mesh.material_id = FindMaterialIndex(node); Object* object = node->GetObjectRef(); Control* control = node->GetTMController(); object->GetDeformBBox(0, mesh.bounding_box, &node->GetObjectTM(0)); mesh.type = OBJECT_TYPE::CLASS_GEOM; if (object && object->ClassID() == Class_ID(BONE_CLASS_ID, 0)) mesh.type = OBJECT_TYPE::CLASS_BONE; else if (object && object->ClassID() == Class_ID(DUMMY_CLASS_ID, 0)) mesh.type = OBJECT_TYPE::CLASS_DUMMY; else if (control && control->ClassID() == BIPBODY_CONTROL_CLASS_ID) mesh.type = OBJECT_TYPE::CLASS_BIPED; else if (control && control->ClassID() == BIPSLAVE_CONTROL_CLASS_ID) mesh.type = OBJECT_TYPE::CLASS_BIPED; if (mesh.type != OBJECT_TYPE::CLASS_GEOM) { GetMesh(node, mesh); } GetAnimation(node, mesh); mesh_list_.push_back(mesh); } return true; } void PMatrixExp::SetUniqueBuffer(PMesh& mesh) { mesh.vertex_list.resize(1); mesh.index_list.resize(1); std::vector<TriComponent>& tri_array = mesh.tri_list; std::vector<PNCT>& vertex_list = mesh.vertex_list[0]; std::vector<int>& index_list = mesh.index_list[0]; for (int iFace = 0; iFace < mesh.tri_list.size(); iFace++) { TriComponent& comp = tri_array[iFace]; for (int iver = 0; iver < 3; iver++) { int pos = IsEqualVertexAndVertexList(comp.v[iver], vertex_list); if (pos < 0) //겹치는게 없는 경우 { vertex_list.push_back(comp.v[iver]); //버텍스리스트에 버텍스 추가 pos = vertex_list.size() - 1; //index = 현재까지 버텍스 들어간 갯수 - 1(1이면 0, 2이면 1..) } index_list.push_back(pos); //index 추가 (3개씩) } } } PMatrixExp::PMatrixExp() { } PMatrixExp::~PMatrixExp() { }
[ "34018251+bear1704@users.noreply.github.com" ]
34018251+bear1704@users.noreply.github.com
ce8542bf190ebe36dc0d967104cda14c76f77976
2cf6dd24ab8a959501940938cd1e0b7653b3fc64
/week12/sweepers/src/sweepers.cpp
99c294a26514ac0d4abd4cf86fa8097677a26b58
[]
no_license
jaitd/algolab
0d07cfd7354ca0f5c036ae31bff08f97b8e2ffb5
8fdd894ca117d6df8496b2cae6b4280a31d175d2
refs/heads/master
2021-05-27T08:31:51.566231
2015-01-09T19:46:16
2015-01-09T19:46:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,251
cpp
#include <iostream> #include <vector> #include <cmath> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/push_relabel_max_flow.hpp> #include <boost/graph/connected_components.hpp> #include <boost/tuple/tuple.hpp> using namespace std; using namespace boost; typedef adjacency_list_traits<vecS, vecS, directedS> traits_t; typedef adjacency_list<vecS, vecS, directedS, no_property, property<edge_capacity_t, long, property<edge_residual_capacity_t, long, property<edge_reverse_t, traits_t::edge_descriptor> > > > graph_t; typedef property_map<graph_t, edge_capacity_t>::type edge_capacity_map_t; typedef property_map<graph_t, edge_residual_capacity_t>::type residual_capacity_map_t; typedef property_map<graph_t, edge_reverse_t>::type reverse_edge_map_t; typedef graph_traits<graph_t>::vertex_descriptor vertex_t; typedef graph_traits<graph_t>::edge_descriptor edge_t; void mf_add_edge(int u, int v, long c, edge_capacity_map_t &capacity, reverse_edge_map_t &rev_edge, graph_t &g) { edge_t e, reverse_edge; tie(e, tuples::ignore) = add_edge(u, v, g); tie(reverse_edge, tuples::ignore) = add_edge(v, u, g); capacity[e] = c; capacity[reverse_edge] = 0; rev_edge[e] = reverse_edge; rev_edge[reverse_edge] = e; } int main() { ios_base::sync_with_stdio(false); int t; cin >> t; for(int i=0; i<t; ++i) { int n, m, s; cin >> n >> m >> s; vector<int> starting_locations(n, 0); for(int j=0; j<s; ++j) { int x; cin >> x; starting_locations[x]++; } vector<int> exit_locations(n, 0); for(int j=0; j<s; ++j) { int x; cin >> x; exit_locations[x]++; } graph_t g(n); edge_capacity_map_t capacity = get(edge_capacity, g); reverse_edge_map_t rev_edge = get(edge_reverse, g); for(int j=0; j<m; ++j) { int x, y; cin >> x >> y; mf_add_edge(x, y, 1, capacity, rev_edge, g); mf_add_edge(y, x, 1, capacity, rev_edge, g); } bool is_eulerian = true; auto vs = vertices(g); for(auto vit = vs.first; vit != vs.second; ++vit) { int count = out_degree(*vit, g); if(starting_locations[*vit] > 0) count+=2; if(exit_locations[*vit] > 0) count+=2; count /= 2; if(count % 2 != 0) { is_eulerian = false; break; } } if(!is_eulerian) { cout << "no" << endl; continue; } int source = add_vertex(g); int sink = add_vertex(g); // connect source to entrances and exits to sink for(int j=0; j<n; ++j) { if(starting_locations[j] > 0) mf_add_edge(source, j, starting_locations[j], capacity, rev_edge, g); } for(int j=0; j<n; ++j) { if(exit_locations[j] > 0) mf_add_edge(j, sink, exit_locations[j], capacity, rev_edge, g); } long flow = push_relabel_max_flow(g, source, sink); if(flow == s) cout << "yes" << endl; else cout << "no" << endl; } return 0; }
[ "jait.dixit@gmail.com" ]
jait.dixit@gmail.com
f7b0f2273a7033a795a7fd58d9e73563d2eda800
370b105e552baa787557cb58de5c13970c8a6be7
/bt_editor/bt_editor/RootNodeModel.hpp
88a96166737be5b3047923da08b46879e76e3046
[]
no_license
gonnavis/youbot
94108dbab80634c25a14ea7df1f5bf3d9e1f9bab
23e7cd875d4598f4a439dce6835b17ca97e87135
refs/heads/master
2023-03-15T13:07:24.316861
2020-05-16T09:34:06
2020-05-16T09:34:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,394
hpp
#pragma once #include <QtCore/QObject> #include <QtWidgets/QLabel> #include <node_editor/NodeDataModel> #include <iostream> #include <memory> using QtNodes::PortType; using QtNodes::PortIndex; using QtNodes::NodeData; using QtNodes::NodeDataType; using QtNodes::NodeDataModel; class RootNodeModel : public NodeDataModel { public: RootNodeModel() {} virtual ~RootNodeModel() {} public: bool captionVisible() const override { return true; } public: unsigned int nPorts(PortType portType) const override { return (portType==PortType::In) ? 0:1; } NodeDataType dataType(PortType portType, PortIndex portIndex) const override final { return NodeDataType {"", ""}; } std::shared_ptr<NodeData> outData(PortIndex port) override { return nullptr; } void setInData(std::shared_ptr<NodeData> data, int) override final {} int BTType() { return BT::ROOT; } QString get_line_edit() { return QString("ROOT"); } std::unique_ptr<NodeDataModel> clone() const override { return std::unique_ptr<NodeDataModel>( new RootNodeModel ); } QString caption() const override { return QString("Root"); } QString name() const override { return QString("Root"); } QWidget *embeddedWidget() override { return nullptr; } virtual ConnectionPolicy portOutConnectionPolicy(PortIndex /*portIndex*/) const { return ConnectionPolicy::One; } };
[ "miccol@kth.se" ]
miccol@kth.se
031435634ca7746a01158a5bc532a4dd91de79b1
f1f9ba2c03972434429ed064e4cd602216c615a2
/04-ASCI-V2/Deck.h
d2dd767dc757e3f103a5fbd05a657146aa124264
[]
no_license
RogerTerrill-CPP/blackjack
c60cc23ba434eeafdf5dfe42e5a7c136cfc1908e
83a449cf021b984fd2c6384b1b32938dfc01634d
refs/heads/master
2020-05-23T07:41:40.810155
2019-05-14T19:00:02
2019-05-14T19:00:02
186,681,820
0
0
null
null
null
null
UTF-8
C++
false
false
962
h
#ifndef DECK_H #define DECK_H #include "Card.h" #include <vector> using namespace std; class Deck { public: //Constructor Deck(); //Creates a new deck of 52 cards void newDeck(); //Shuffles deck of any size void shuffle(); //Prints deck of any size void printDeck(); //Returns specific card of element i string printCardinHand(int i); //Deals a card to object passed by reference void deal(Deck& inputDeck); //Clears deck object of all cards void clearHand(); //Returns the total value of hand int handTotal(); //Returns the value of a single card at element i int valueOfCard(int i); //Checks to see of the hand is over 21 bool bust(); //Checks to see if hand is > 21 and change ace to 1 void checkAce(); //Print all cards in hand void printResult(); //Check to see if the vector object is empty bool emptyDeck(); private: //Vector of object Card declaration vector<Card> vectorDeck; }; #endif // DECK_H
[ "lpaddikt@gmail.com" ]
lpaddikt@gmail.com
b683ae0bcb3017c7e41eda4405bbe6a0e3dd448b
e29926043a39f0b94d867338187ef3e1e94d3987
/libraries/Ethernet/utility/w5500.cpp
72550d58ba472c879238def4231ba53c8374fa3b
[]
no_license
linuxha/mqtt_cloud
6e989cddf108a36a8c131980d5062113b21a8417
3c2f8d3e5a047dcc08eb3afc550602ca5bfd044b
refs/heads/master
2016-08-09T23:05:29.416422
2015-10-22T13:33:09
2015-10-22T13:33:09
44,743,635
0
1
null
null
null
null
UTF-8
C++
false
false
3,640
cpp
/* * Copyright (c) 2010 by WIZnet <support@wiznet.co.kr> * * This file is free software; you can redistribute it and/or modify * it under the terms of either the GNU General Public License version 2 * or the GNU Lesser General Public License version 2.1, both as * published by the Free Software Foundation. */ #include <stdio.h> #include <string.h> //#include <avr/interrupt.h> #include "w5100.h" #if defined(W5500_ETHERNET_SHIELD) // W5500 controller instance W5500Class W5100; void W5500Class::init(void) { Serial.println("W5500 init"); initSS(); delay(300); SPI.begin(); for (int i=0; i<MAX_SOCK_NUM; i++) { uint8_t cntl_byte = (0x0C + (i<<5)); write( 0x1E, cntl_byte, 2); //0x1E - Sn_RXBUF_SIZE write( 0x1F, cntl_byte, 2); //0x1F - Sn_TXBUF_SIZE } } uint16_t W5500Class::getTXFreeSize(SOCKET s) { uint16_t val=0, val1=0; do { val1 = readSnTX_FSR(s); if (val1 != 0) val = readSnTX_FSR(s); } while (val != val1); return val; } uint16_t W5500Class::getRXReceivedSize(SOCKET s) { uint16_t val=0,val1=0; do { val1 = readSnRX_RSR(s); if (val1 != 0) val = readSnRX_RSR(s); } while (val != val1); return val; } void W5500Class::send_data_processing(SOCKET s, const uint8_t *data, uint16_t len) { // This is same as having no offset in a call to send_data_processing_offset send_data_processing_offset(s, 0, data, len); } void W5500Class::send_data_processing_offset(SOCKET s, uint16_t data_offset, const uint8_t *data, uint16_t len) { uint16_t ptr = readSnTX_WR(s); uint8_t cntl_byte = (0x14+(s<<5)); ptr += data_offset; write(ptr, cntl_byte, data, len); ptr += len; writeSnTX_WR(s, ptr); } void W5500Class::recv_data_processing(SOCKET s, uint8_t *data, uint16_t len, uint8_t peek) { uint16_t ptr; ptr = readSnRX_RD(s); read_data(s, ptr, data, len); if (!peek) { ptr += len; writeSnRX_RD(s, ptr); } } // void W5500Class::read_data(SOCKET s, volatile uint8_t *src, volatile uint8_t *dst, uint16_t len) { void W5500Class::read_data(SOCKET s, uint16_t src, uint8_t * dstBuf, uint16_t len) { uint8_t cntl_byte = (0x18+(s<<5)); #if defined(__PIC32MX__) read(src, cntl_byte, dstBuf, len); #else read((uint16_t)src , cntl_byte, (uint8_t *) dst, len); #endif } uint8_t W5500Class::write(uint16_t _addr, uint8_t _cb, uint8_t _data) { setSS(); SPI.transfer(_addr >> 8); SPI.transfer(_addr & 0xFF); SPI.transfer(_cb); SPI.transfer(_data); resetSS(); return 1; } uint16_t W5500Class::write(uint16_t _addr, uint8_t _cb, const uint8_t *_buf, uint16_t _len) { setSS(); SPI.transfer(_addr >> 8); SPI.transfer(_addr & 0xFF); SPI.transfer(_cb); for (uint16_t i=0; i<_len; i++){ SPI.transfer(_buf[i]); } resetSS(); return _len; } uint8_t W5500Class::read(uint16_t _addr, uint8_t _cb) { setSS(); SPI.transfer(_addr >> 8); SPI.transfer(_addr & 0xFF); SPI.transfer(_cb); uint8_t _data = SPI.transfer(0); resetSS(); return _data; } uint16_t W5500Class::read(uint16_t _addr, uint8_t _cb, uint8_t *_buf, uint16_t _len) { setSS(); SPI.transfer(_addr >> 8); SPI.transfer(_addr & 0xFF); SPI.transfer(_cb); for (uint16_t i=0; i<_len; i++){ _buf[i] = SPI.transfer(0); } resetSS(); return _len; } void W5500Class::execCmdSn(SOCKET s, SockCMD _cmd) { // Send command to socket writeSnCR(s, _cmd); // Wait for command to complete while (readSnCR(s)) ; } #endif
[ "ncherry@linuxha.com" ]
ncherry@linuxha.com
e5f120cf9dc587ec476865d8170e2af73a3ec155
7ae0efc9798b7c9fa720022ed5d763d6ab27cd13
/paddle/fluid/operators/fused/attn_bias_add.cu.h
f2f6b6bfe01d1ed279d37bfdb9236461a3c19911
[ "Apache-2.0" ]
permissive
ceci3/Paddle
e1d0b56a1bb1de9a0d26977868795f86e2c0580b
e4d475eabd83e7a6fa1e88c64c28747450f87d66
refs/heads/develop
2023-08-03T03:43:35.139011
2022-02-08T11:36:07
2022-02-08T11:36:07
171,274,803
0
3
Apache-2.0
2021-08-24T07:14:24
2019-02-18T11:49:16
C++
UTF-8
C++
false
false
11,521
h
/* Copyright (c) 2021 PaddlePaddle Authors. 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. */ #pragma once #ifdef __NVCC__ #include "cub/cub.cuh" #endif #ifdef __HIPCC__ #include <hipcub/hipcub.hpp> namespace cub = hipcub; #endif #include "paddle/fluid/platform/device/gpu/gpu_dnn.h" #ifdef __HIPCC__ #define LAUNCH_BOUNDS(BlockDim) __launch_bounds__(BlockDim) #else #define LAUNCH_BOUNDS(BlockDim) #endif #include "paddle/fluid/operators/elementwise/elementwise_functor.h" #include "paddle/fluid/operators/elementwise/elementwise_op_broadcast.cu.h" #include "paddle/fluid/operators/kernel_primitives/kernel_primitives.h" #include "paddle/fluid/operators/reduce_ops/reduce_op.cu.h" #include "paddle/fluid/platform/fast_divmod.h" namespace paddle { namespace operators { #define MAX_INPUT_NUM 2 template <typename T> using CudnnDataType = platform::CudnnDataType<T>; template <typename T> using ReduceParamType = typename CudnnDataType<T>::BatchNormParamType; template <typename InT, typename OutT, int ShapeSize, int VecSize, int DATA_PER_THREAD, typename Functor> __global__ void BroadcastKernelBinary( const InT* __restrict__ in0, const InT* __restrict__ in1, OutT* out, framework::Array<bool, MAX_INPUT_NUM> use_broadcast, uint32_t numel, framework::Array<kps::details::BroadcastConfig<ShapeSize>, MAX_INPUT_NUM> configlists, int main_tid, int tail_tid, Functor func) { int fix = blockIdx.x * blockDim.x * VecSize; int num = tail_tid; InT arg0[VecSize * DATA_PER_THREAD]; InT arg1[VecSize * DATA_PER_THREAD]; OutT result[VecSize * DATA_PER_THREAD]; if (blockIdx.x < main_tid) { num = blockDim.x * VecSize; // blockIdx.x < main_tid } // load in0 if (use_broadcast[0]) { kernel_primitives::ReadDataBc<InT, VecSize, DATA_PER_THREAD, 1, ShapeSize>( arg0, in0, fix, configlists[0], numel); } else { kernel_primitives::ReadData<InT, VecSize, 1, 1>(arg0, in0 + fix, num); } // load in1 if (use_broadcast[1]) { kernel_primitives::ReadDataBc<InT, VecSize, DATA_PER_THREAD, 1, ShapeSize>( arg1, in1, fix, configlists[1], numel); } else { kernel_primitives::ReadData<InT, VecSize, 1, 1>(arg1, in1 + fix, num); } // compute kernel_primitives::ElementwiseBinary<InT, OutT, VecSize, 1, 1, Functor>( result, arg0, arg1, func); // store kernel_primitives::WriteData<OutT, VecSize, 1, 1, true>(out + fix, result, num); } // bias add forward impl for "[m, n] + [n] = [m, n]" template <typename T> void LaunchBiasAddFwKernel(const platform::CUDADeviceContext& ctx, int m, int n, const T* in0, const T* in1, T* out) { int in_vec_size = std::min(platform::GetVectorizedSize<T>(in0), platform::GetVectorizedSize<T>(in1)); int out_vec_size = std::min(4, platform::GetVectorizedSize<T>(out)); int vec_size = std::min(out_vec_size, in_vec_size); int numel = m * n; const int threads = 256; const int data_per_thread = 1; int blocks = ((numel + vec_size * data_per_thread - 1) / (vec_size * data_per_thread) + threads - 1) / threads; int main_tid = numel / (data_per_thread * vec_size * threads); int tail_tid = numel % (data_per_thread * vec_size * threads); framework::Array<kps::details::BroadcastConfig<2>, MAX_INPUT_NUM> configlists; framework::Array<bool, MAX_INPUT_NUM> use_broadcast; use_broadcast[0] = false; use_broadcast[1] = false; if (m != 1) { use_broadcast[1] = true; } // Here, dims are transposed due to the logic in BroadcastConfig. std::vector<int64_t> input1_dims = {n, 1}; std::vector<int64_t> out_dims = {n, m}; configlists[1] = kps::details::BroadcastConfig<2>(out_dims, input1_dims, 2); auto func = AddFunctor<T>(); auto stream = ctx.stream(); switch (vec_size) { case 4: { BroadcastKernelBinary<T, T, 2, 4, data_per_thread><<<blocks, threads, 0, stream>>>( in0, in1, out, use_broadcast, numel, configlists, main_tid, tail_tid, func); break; } case 2: { BroadcastKernelBinary<T, T, 2, 2, data_per_thread><<<blocks, threads, 0, stream>>>( in0, in1, out, use_broadcast, numel, configlists, main_tid, tail_tid, func); break; } case 1: { BroadcastKernelBinary<T, T, 2, 1, data_per_thread><<<blocks, threads, 0, stream>>>( in0, in1, out, use_broadcast, numel, configlists, main_tid, tail_tid, func); break; } default: { PADDLE_THROW(platform::errors::Unimplemented( "Unsupported vectorized size: %d !", vec_size)); break; } } } template <typename T, int BlockDim> __global__ void LAUNCH_BOUNDS(BlockDim) Compute1DColumnReduceKernel(const int reduce_num, const int left_num, const T* in, T* out) { typedef cub::BlockReduce<ReduceParamType<T>, BlockDim> BlockReduce; __shared__ typename BlockReduce::TempStorage mean_storage; for (int i = blockIdx.x; i < left_num; i += gridDim.x) { ReduceParamType<T> x_sum = static_cast<ReduceParamType<T>>(0); for (int j = threadIdx.x; j < reduce_num; j += blockDim.x) { const int index = j * left_num + i; ReduceParamType<T> x_i = static_cast<ReduceParamType<T>>(in[index]); x_sum += x_i; } x_sum = BlockReduce(mean_storage).Reduce(x_sum, cub::Sum()); if (threadIdx.x == 0) { out[i] = static_cast<T>(x_sum); } } } template <typename T> void Launch1DColumnReduce(gpuStream_t stream, const int max_threads, const int reduce_num, const int left_num, const T* d_out, T* d_bias) { const int block = 256; const int max_blocks = std::max(max_threads / block, 1); const int grid = std::min(left_num, max_blocks); Compute1DColumnReduceKernel<T, block><<<grid, block, 0, stream>>>( reduce_num, left_num, d_out, d_bias); } void SetConfigForColumnReduce(const int max_threads, const int reduce_num, const int left_num, int* blocking_size, bool* should_reduce_again, dim3* block_dim, dim3* grid_dim) { block_dim->z = 1; grid_dim->z = 1; *should_reduce_again = false; int num_block = (max_threads / left_num); if (num_block > 1 && reduce_num >= REDUCE_SPLIT_BOUNDARY) { *blocking_size = pten::kernels::details::GetLastPow2(reduce_num / num_block); if (*blocking_size <= 1) { *blocking_size = pten::kernels::details::GetLastPow2(sqrt(reduce_num)); } else if (*blocking_size * 2 < reduce_num) { *blocking_size *= 2; } *should_reduce_again = true; block_dim->x = 32; block_dim->y = 1; grid_dim->x = (left_num + block_dim->x - 1) / block_dim->x; grid_dim->y = (reduce_num + *blocking_size - 1) / *blocking_size; } else { block_dim->x = 32; *blocking_size = reduce_num; grid_dim->x = (left_num + block_dim->x - 1) / block_dim->x; grid_dim->y = 1; } } template <typename T> __global__ void BiasAddBwSinglePassKernel(const T* in, int reduce_num, int left_num, T* out) { int idx = blockIdx.x * blockDim.x + threadIdx.x; ReduceParamType<T> x_sum = static_cast<ReduceParamType<T>>(0); if (idx < left_num) { for (int iy = 0; iy < reduce_num; iy++) { int id = iy * left_num + idx; ReduceParamType<T> x_val = static_cast<ReduceParamType<T>>(in[id]); x_sum += x_val; } out[idx] = static_cast<T>(x_sum); } } template <typename T> __global__ void BiasAddBw2DReduceKernel(const T* x, int reduce_num, int left_num, int workload_per_thread, ReduceParamType<T>* temp_x_sum) { int idx = blockIdx.x * blockDim.x + threadIdx.x; int idy = blockIdx.y * workload_per_thread; T x_val; ReduceParamType<T> x_sum = static_cast<ReduceParamType<T>>(0); if (idx < left_num) { int loop = reduce_num - idy; loop = loop > workload_per_thread ? workload_per_thread : loop; for (int iy = 0; iy < loop; iy++) { int id = (idy + iy) * left_num + idx; ReduceParamType<T> x_val = static_cast<ReduceParamType<T>>(x[id]); x_sum += x_val; } temp_x_sum[idx + blockIdx.y * left_num] = x_sum; } } template <typename T> __global__ void BiasAddBw1DReduceKernel(const ReduceParamType<T>* temp_sum, int workload_per_thread, int left_num, T* out) { int idx = blockIdx.x * blockDim.x + threadIdx.x; ReduceParamType<T> x_sum = static_cast<ReduceParamType<T>>(0); if (idx < left_num) { for (int iy = 0; iy < workload_per_thread; iy++) { int id = iy * left_num + idx; x_sum += temp_sum[id]; } out[idx] = static_cast<T>(x_sum); } } template <typename T> void Launch2DColumnReduce(const platform::CUDADeviceContext& dev_ctx, const int max_threads, const int reduce_num, const int left_num, const T* d_out, T* d_bias) { dim3 block; dim3 grid; bool should_reduce_again = false; int blocking_size = 1; SetConfigForColumnReduce(max_threads, reduce_num, left_num, &blocking_size, &should_reduce_again, &block, &grid); const auto& stream = dev_ctx.stream(); if (!should_reduce_again) { BiasAddBwSinglePassKernel<T><<<grid, block, 0, stream>>>(d_out, reduce_num, left_num, d_bias); } else { framework::Tensor tmp_sum; tmp_sum.Resize({grid.y, left_num}); tmp_sum.mutable_data<ReduceParamType<T>>(dev_ctx.GetPlace()); BiasAddBw2DReduceKernel<T><<<grid, block, 0, stream>>>( d_out, reduce_num, left_num, blocking_size, tmp_sum.template data<ReduceParamType<T>>()); BiasAddBw1DReduceKernel<T><<<grid.x, block.x, 0, stream>>>( tmp_sum.template data<ReduceParamType<T>>(), grid.y, left_num, d_bias); } } // bias add backward impl whose pattern are column-reduce with d_out[m, n] as // input // and d_bias[n] as output. template <typename T> void LaunchBiasAddBwKernel(const platform::CUDADeviceContext& dev_ctx, int m, int n, const T* d_out, T* d_bias) { int max_threads = dev_ctx.GetMaxPhysicalThreadCount(); int reduce_num = m; int left_num = n; bool is_large_enough = (reduce_num > REDUCE_SPLIT_BOUNDARY / 2) || (left_num > REDUCE_SPLIT_BOUNDARY); if (!is_large_enough) { Launch1DColumnReduce(dev_ctx.stream(), max_threads, reduce_num, left_num, d_out, d_bias); } else { Launch2DColumnReduce(dev_ctx, max_threads, reduce_num, left_num, d_out, d_bias); } } #undef MAX_INPUT_NUM } // namespace operators } // namespace paddle
[ "noreply@github.com" ]
ceci3.noreply@github.com
c48a5efb6f53a4632bd8438c404b62ff16fa6321
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
/2017-2021/2019/iroha/day1/i.cpp
db6dc0407834fbe6ed996fac36ee1538b6308a4a
[]
no_license
kmjp/procon
27270f605f3ae5d80fbdb28708318a6557273a57
8083028ece4be1460150aa3f0e69bdb57e510b53
refs/heads/master
2023-09-04T11:01:09.452170
2023-09-03T15:25:21
2023-09-03T15:25:21
30,825,508
23
2
null
2023-08-18T14:02:07
2015-02-15T11:25:23
C++
UTF-8
C++
false
false
2,735
cpp
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) //------------------------------------------------------- int N,M,K; int A[101010],B[101010],C[101010]; vector<int> Cs[101010]; template<int um> class UF_pop { public: vector<int> par,rank; vector<vector<int>> hist; UF_pop() {par=rank=vector<int>(um,0); for(int i=0;i<um;i++) par[i]=i;} void reinit() {int i; FOR(i,um) rank[i]=0,par[i]=i;} int operator[](int x) {return (par[x]==x)?(x):operator[](par[x]);} void pop() { if(hist.size()) { auto a=hist.back(); hist.pop_back(); par[a[0]]=a[1]; rank[a[0]]=a[2]; par[a[3]]=a[4]; rank[a[3]]=a[5]; } } void operator()(int x,int y) { x=operator[](x); y=operator[](y); hist.push_back({x,par[x],rank[x],y,par[y],rank[y]}); if(x==y) return; if(rank[x]<rank[y]) par[x]=y; else rank[x]+=(rank[x]==rank[y]), par[y]=x; } }; UF_pop<101010> uf; int dist[101010]; set<int> cand[101010]; vector<int> V[202020]; vector<int> D[202020]; int did[202020]; void solve() { int i,j,k,l,r,x,y; string s; cin>>N>>M>>K; FOR(i,M) { cin>>A[i]>>B[i]>>C[i]; A[i]--; B[i]--; C[i]--; Cs[C[i]].push_back(i); } int id=0; FOR(i,101010) if(Cs[i].size()) { FORR(c,Cs[i]) { uf(A[c],B[c]); } FORR(c,Cs[i]) { if(did[A[c]]==0) { did[A[c]]=1; D[uf[A[c]]].push_back(A[c]); } if(did[B[c]]==0) { did[B[c]]=1; D[uf[B[c]]].push_back(B[c]); } } FORR(c,Cs[i]) { did[A[c]]=did[B[c]]=0; if(D[A[c]].size()) { swap(V[id],D[A[c]]); FORR(v,V[id]) cand[v].insert(id); id++; } if(D[B[c]].size()) { swap(V[id],D[B[c]]); FORR(v,V[id]) cand[v].insert(id); id++; } uf.pop(); } } queue<int> Q; FOR(i,N) dist[i]=202020; dist[0]=0; Q.push(0); while(Q.size()) { int cur=Q.front(); Q.pop(); FORR(c,cand[cur]) { FORR(v,V[c]) if(v!=cur) { if(dist[v]>dist[cur]+1) { dist[v]=dist[cur]+1; Q.push(v); } cand[v].erase(c); } } cand[cur].clear(); } if(dist[N-1]==202020) cout<<-1<<endl; else cout<<dist[N-1]*K<<endl; } int main(int argc,char** argv){ string s;int i; if(argc==1) ios::sync_with_stdio(false), cin.tie(0); FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin); cout.tie(0); solve(); return 0; }
[ "kmjp@users.noreply.github.com" ]
kmjp@users.noreply.github.com
0992f2ca04da389dbca33025ae1e26d20d42a437
2c9cbbbb0cf7c172cacc8823dee711ccb7c4e6d1
/CodingPlatform/SPOJ/PPATH.cpp
2c7416e1cfcd5be7ddd7af2a72661f59c78886bc
[]
no_license
vishnu0179/Competitive
45d164a3f863d7b56ab7309f3c1baed610719f7e
9ca266fdf04194158504f96c252c48750f0cfdf6
refs/heads/master
2023-01-03T05:03:44.067408
2020-11-02T11:10:45
2020-11-02T11:10:45
309,345,595
0
0
null
null
null
null
UTF-8
C++
false
false
1,683
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; vector<int> adjList[10001]; int vis[10001]; int dist[10001]; vector<int> primes; bool isPrime(int n) { int temp = sqrt(n); for(int i=2; i<=temp;i++) { if(n%i==0) return false; } return true; } bool isValid(int a, int b) { int count = 0; while(a>0) { if(a%10!=b%10) count++; a/=10; b/=10; if(count>1) break; } if(count!=1) return false; return true; } void buildGraph(){ for(int i=1000;i<=9999;i++) { if(isPrime(i)) primes.push_back(i); } for(int i=0;i<primes.size();i++) { for(int j=i+1;j<primes.size();j++) { int a = primes[i]; int b = primes[j]; if(isValid(a, b)) { adjList[primes[i]].push_back(b); adjList[primes[j]].push_back(a); } } } } void bfs(int src) { vis[src] = 1; queue<int> q; q.push(src); //cout<<src<<" "; dist[src] = 0; vis[src] = 1; while (!q.empty()) { int curr = q.front(); //cout<<curr; q.pop(); for(int child: adjList[curr]) { if(vis[child]==0) { vis[child]= 1; dist[child] = dist[curr] + 1; q.push(child); } } } } int main() { freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); buildGraph(); int t; cin>>t; while(t--) { int src, dest; cin>>src>>dest; for(int i = 1000;i<=9999;i++) { vis[i] = 0; dist[i] = -1; } bfs(src); if(dist[dest]==-1) { cout<<"Impossible"<<endl; continue; } cout<<dist[dest]<<endl; } return 0; }
[ "vjvj140@gmail.com" ]
vjvj140@gmail.com
5dab6f5cda4f0a7e96d68250e9f0c491a2e96485
68d8e0c67695f49ce404a7961c8ad24bb36f9604
/2/eight.cpp
dc667ff6e59b0a01a5bf711b1629da85a9457035
[]
no_license
getty55/nb
3bfeab3bd25e3192eee63caa8c2d862305c8096f
6490d0d23d18d2586ca4dca8e4af0989e71198f0
refs/heads/master
2020-09-10T00:43:24.148112
2019-12-11T03:48:47
2019-12-11T03:48:47
221,607,367
0
0
null
null
null
null
UTF-8
C++
false
false
1,107
cpp
#include <iostream> #include <unordered_set> struct Linked_list{ char val; Linked_list* next; Linked_list(char v) : val{v}, next{nullptr} {} }; void print_list(Linked_list* head){ auto p = head; while (p){ std::cout << p->val; p = p->next; if (p) std::cout << " -> "; } std::cout << '\n'; } Linked_list* loop_detection(Linked_list* head){ if (!head) return nullptr; std::unordered_set<Linked_list*> m; auto p = head; while (p){ if (m.find(p) != m.end()) return p; m.insert(p); p = p->next; } return nullptr; } int main(){ Linked_list* boom = new Linked_list('C'); Linked_list* ll = new Linked_list('A'); ll->next = new Linked_list('B'); ll->next->next = boom; ll->next->next->next = new Linked_list('D'); ll->next->next->next->next = new Linked_list('E'); ll->next->next->next->next->next = boom; //print_list(ll); auto a = loop_detection(ll); if (!a) std::cout << "no loop detected\n"; else std::cout << "loop detected at node: " << a->val << '\n'; }
[ "gettubby55@gmail.com" ]
gettubby55@gmail.com
a3d4bfaf66fdea70b5141d07661efcd2f6b8b9a1
3844678a0fb3b1f0838fb04bc57fd93dee6ee631
/siteApps/fftWaveform-1-0/fftwaveApp/src/asubSin2FFT.cpp
9224fb3dec5f4a47f8d1722d4962e23c653e0bf4
[]
no_license
jeonghanlee/Work
daa9295da3af3ff6c3a68daf51fac804dd1942cd
bef817911ea29fe091547f001ac35ac3765d8258
refs/heads/master
2022-09-28T03:59:29.435017
2022-09-15T18:26:34
2022-09-15T18:26:34
91,843,357
3
0
null
2019-01-08T16:10:37
2017-05-19T20:34:36
VHDL
UTF-8
C++
false
false
4,350
cpp
#include <unistd.h> #include <cstdio> #include <string> #include <fstream> #include <iomanip> #include <bitset> #include <algorithm> #include <cmath> #include <complex> #include <iostream> #include <dbAccess.h> #include <link.h> #include <dbDefs.h> #include <dbLock.h> #include <dbAddr.h> #include <dbCommon.h> #include <epicsThread.h> #include <epicsMessageQueue.h> #include <registryFunction.h> #include <recSup.h> #include <waveformRecord.h> #include <compressRecord.h> #include <aSubRecord.h> #include <epicsExport.h> #include <iocsh.h> #include <Eigen/Dense> #include <unsupported/Eigen/FFT> #define OUTFILE 0 using namespace std; using namespace Eigen; static int sin2fftDebug = 0; // static long InitSin2FFT(aSubRecord *pRec) { return(0); } // static long ProcSin2FFT(aSubRecord *pRec) { long status = 0; //INPA DBADDR *pdbWave = (DBADDR*)(&pRec->inpa)->value.pv_link.pvt; compressRecord *pWave = (compressRecord *)pdbWave->precord; long nelm = pdbWave->no_elements; double *sinval = (double*)pRec->a; #if 1 //for FFT X-Y Waveform //OUTA Y FFT Amplitude DBADDR *pdbFFTDBAddr = (DBADDR*)(&pRec->outa)->value.pv_link.pvt; waveformRecord *pFFTWave = (waveformRecord *)pdbFFTDBAddr->precord; double *pFFTWaveVal = (double*)pRec->vala; //OUTB X Frequency DBADDR *pdbFFTFreqAddr = (DBADDR*)(&pRec->outb)->value.pv_link.pvt; waveformRecord *pFFTFreqWave = (waveformRecord *)pdbFFTFreqAddr->precord; double *pFFTFreqWaveVal = (double*)pRec->valb; #endif double const Fs = 2*100; // Nyquist [Hz] double const Ts = 1./Fs; // [s] Eigen::VectorXd time(nelm); Eigen::VectorXcd fvalues(nelm); Eigen::VectorXd freq(nelm); for(int i = 0; i < nelm; ++i){ time(i) = i * Ts; fvalues(i) = sinval[i]; fvalues(i) = fvalues(i)/(0.5*nelm); freq(i) = Fs * i / double(nelm); } Eigen::FFT<double> fft; Eigen::VectorXcd ffreq(nelm); fft.fwd(ffreq, fvalues); if(sin2fftDebug) { static int first = 1; if(first) { std::ofstream fftres("fft_result.txt"); for(int i = 0; i < nelm; ++i){ fftres << freq(i) << " " << std::abs(ffreq(i)) << "\n"; } fftres.close(); first++; }; }; #if 1 for(int i = 0; i < ffreq.size(); i++) { pFFTFreqWaveVal[i] = freq(i); pFFTWaveVal[i] = std::abs(ffreq(i)); }; #endif dbProcess((dbCommon*)pFFTWave); dbProcess((dbCommon*)pFFTFreqWave); return(status); #if 0 unsigned const N = 10000; // Sample Count //double const Fs = 32; // [Hz] double const Fs = 2*100; // Nyquist [Hz] double const Ts = 1./Fs; // [s] const double f0 = 5; // [Hz] const double f1 = 10; // [Hz] const double f2 = 50; // [Hz] const double f3 = 60; // [Hz] using namespace std; //std::complex<double> f(std::complex<double> const & t){ double f(double const & t){ //return (std::sin(2*M_PI*f0*t)); // //Add Amplitude //return (std::sin(2*M_PI*f0*t)*3.0); // //Add Other wave //return 2.0*cos(2*M_PI*2*t) + 3.0*sin(2*M_PI*4*t) + 4.0*sin(2*M_PI*6*t); return 3.0*sin(2*M_PI*f0*t) + 5.0*sin(2*M_PI*f1*t) + 4.0*cos(2*M_PI*f2*t) + 2.0*cos(2*M_PI*f3*t); } int main(){ std::ofstream xrec("xrec.txt"); std::ofstream sin("sin.txt"); //Eigen::VectorXcd time(N); Eigen::VectorXd time(N); //Eigen::VectorXcd f_values(N); Eigen::VectorXd f_values(N); Eigen::VectorXd freq(N); for(int u = 0; u < N; ++u){ time(u) = u * Ts; //f_values(u) = f(time(u)); // Y_Val need real scale f_values(u) = f(time(u)); // Count //sin << u << " " << f_values(u).real() << "\n"; sin << u << " " << f_values(u) << "\n"; f_values(u) = f_values(u)/(0.5*N); freq(u) = Fs * u / double(N); } Eigen::FFT<double> fft; Eigen::VectorXcd f_freq(N); fft.fwd(f_freq, f_values); //for(int u = 0; u < N; ++u){ //Remove Nyquist Freq. //for(int u = 0; u < N/2; ++u){ for(int u = 0; u < N; ++u){ xrec << freq(u) << " " << std::abs(f_freq(u)) << "\n"; } xrec.close(); sin.close(); } #endif //GNU Plot Script //set key off //set grid //set output "figure.png" //set xlabel "Frequency [Hz]" //plot [-1:100] [-1:10] "xrec.txt" with impulses, "xrec.txt" with points pt 4 } /* Register these symbols for use by IOC code: */ epicsRegisterFunction(InitSin2FFT); epicsRegisterFunction(ProcSin2FFT); epicsExportAddress(int, sin2fftDebug);
[ "silee7103@gmail.com" ]
silee7103@gmail.com
becdf09bfd367724e68b6e3ebced83f387d7492d
90d39aa2f36783b89a17e0687980b1139b6c71ce
/CQM/9/SERIES.cpp
7777e8b10aff71c19695b36f3eb18336c9f2f678
[]
no_license
nims11/coding
634983b21ad98694ef9badf56ec8dfc950f33539
390d64aff1f0149e740629c64e1d00cd5fb59042
refs/heads/master
2021-03-22T08:15:29.770903
2018-05-28T23:27:37
2018-05-28T23:27:37
247,346,971
4
0
null
null
null
null
UTF-8
C++
false
false
1,897
cpp
/* Nimesh Ghelani (nims11) */ #include<iostream> #include<cstdio> #include<cmath> #include<algorithm> #include<map> #include<string> #include<vector> #include<queue> #include<cstring> #include<cstdlib> #include<cassert> #include<cmath> #include<stack> #include<set> #include<utility> #define in_T int t;for(scanf("%d",&t);t--;) #define in_I(a) scanf("%d",&a) #define in_F(a) scanf("%lf",&a) #define in_L(a) scanf("%lld",&a) #define in_S(a) scanf("%s",a) #define newline printf("\n") #define MAX(a,b) a>b?a:b #define MIN(a,b) a<b?a:b #define SWAP(a,b) {int tmp=a;a=b;b=tmp;} #define P_I(a) printf("%d",a) using namespace std; const int m = 1000000007; long long S[3][3]; long long B[3][3] = {{2, 2, 1}, {1, 0, 0}, {0, 1, 0}}; void matpow(long long M[3][3], long long n) { if(n>1) { matpow(M, n>>1); for(int i=0;i<3;i++) for(int j=0;j<3;j++) S[i][j] = M[i][j]; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { M[i][j] = 0; for(int k=0;k<3;k++) M[i][j] = (M[i][j] + (S[i][k]*S[k][j])%m)%m; } } } if(n>1 && n&1) { for(int i=0;i<3;i++) for(int j=0;j<3;j++) S[i][j] = M[i][j]; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { M[i][j] = 0; for(int k=0;k<3;k++) M[i][j] = (M[i][j] + (S[i][k]*B[k][j])%m)%m; } } } } int getans(int n){ if(n == 0)return 0; if(n == 1)return 2; if(n == 2)return 5; long long M[3][3] = {{2, 2, 1}, {1, 0, 0}, {0, 1, 0}}; matpow(M,n-2); return (M[0][0]*5+M[0][1]*2)%m; } int main() { in_T{ int n; in_I(n); printf("%d\n", getans(n)); } }
[ "nimeshghelani@gmail.com" ]
nimeshghelani@gmail.com
4ff3064902f55f8dadc59f1f8ffdbee037662e2d
7b821efabe772942f45b2e4e0a5f919a27c47de5
/llvm/linkgtest/EasyCL/util/easycl_stringhelper.cpp
8562e9f78c2e3bcce31c297569ef7394c958a105
[ "Apache-2.0" ]
permissive
hughperkins/pub-prototyping
0d7b4bae2a0829dc8026006d2adb737f42bbe3a9
7bc1a0582e7ab8e8a7f70ade40dd1275bdfe25b6
refs/heads/master
2022-07-09T18:07:54.041518
2022-07-02T17:44:56
2022-07-02T17:44:56
92,943,709
16
3
null
null
null
null
UTF-8
C++
false
false
3,057
cpp
// Copyright Hugh Perkins 2014, 2015 hughperkins at gmail // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include <string> #include <vector> #include <sstream> using namespace std; #include "util/easycl_stringhelper.h" namespace easycl { vector<string> split(const string &str, const string &separator) { vector<string> splitstring; int start = 0; int npos = (int)str.find(separator); while (npos != (int)str.npos) { splitstring.push_back(str.substr(start, npos-start)); start = npos + (int)separator.length(); npos = (int)str.find(separator, start); } splitstring.push_back(str.substr(start) ); return splitstring; } string trim(const string &target) { int origlen = (int)target.size(); int startpos = -1; for(int i = 0; i < origlen; i++) { if(target[i] != ' ' && target[i] != '\r' && target[i] != '\n') { startpos = i; break; } } int endpos = -1; for(int i = origlen - 1; i >= 0; i--) { if(target[i] != ' ' && target[i] != '\r' && target[i] != '\n') { endpos = i; break; } } if(startpos == -1 || endpos == -1) { return ""; } return target.substr(startpos, endpos-startpos + 1); } string replace(string targetString, string oldValue, string newValue) { size_t pos = targetString.find(oldValue); if(pos == string::npos) { return targetString; } return targetString.replace(pos, oldValue.length(), newValue); } string replaceGlobal(string targetString, string oldValue, string newValue) { int pos = 0; string resultString = ""; size_t targetPos = targetString.find(oldValue, pos); while(targetPos != string::npos) { string preOld = targetString.substr(pos, targetPos - pos); resultString += preOld + newValue; pos = targetPos + oldValue.length(); targetPos = targetString.find(oldValue, pos); } resultString += targetString.substr(pos); return resultString; } std::string toLower(std::string in) { int len = static_cast<int>(in.size()); char *buffer = new char[len + 1]; for(int i = 0; i < len; i++) { char thischar = in[i]; thischar = tolower(thischar); buffer[i] = thischar; } buffer[len] = 0; std::string result = std::string(buffer); delete[] buffer; return result; } void strcpy_safe(char *destination, char const*source, int maxLength) { int i = 0; for(i = 0; i < maxLength; i++) { destination[i] = source[i]; if(source[i] == 0) { break; } } destination[i] = 0; } }
[ "hughperkins@gmail.com" ]
hughperkins@gmail.com
53dc427fabfdfcb4ec989afcea03b22dbdb479c6
f51049c139bcea6626b9cbc338e7f6ba89ec09c7
/Final/Disk/Software/RescueProject/Clp-1.9.0/Clp/src/ClpMain.cpp
b47bd6f52f127d5b8f839c0c7dc5e39bf65191d0
[]
no_license
YanivFais/thesis_msc_dist_alg
e147f4603e084e02054f6d5737392c92f479e891
9d495062516fa7960814a560e4956278d6d7b750
refs/heads/master
2023-01-29T05:27:20.307668
2020-04-12T12:12:41
2020-04-12T12:12:41
255,051,982
0
0
null
2023-01-26T23:54:42
2020-04-12T09:47:21
C++
UTF-8
C++
false
false
93,542
cpp
// Copyright (C) 2002, International Business Machines // Corporation and others. All Rights Reserved. #include "CoinPragma.hpp" #include <cassert> #include <cstdio> #include <cstdlib> #include <cmath> #include <cfloat> #include <string> #include <iostream> int boundary_sort=1000; int boundary_sort2=1000; int boundary_sort3=10000; #include "CoinPragma.hpp" #include "CoinHelperFunctions.hpp" #include "CoinSort.hpp" // History since 1.0 at end #define CLPVERSION "1.09.00" #include "CoinMpsIO.hpp" #include "CoinFileIO.hpp" #include "ClpFactorization.hpp" #include "CoinTime.hpp" #include "ClpSimplex.hpp" #include "ClpSimplexOther.hpp" #include "ClpSolve.hpp" #include "ClpPackedMatrix.hpp" #include "ClpPlusMinusOneMatrix.hpp" #include "ClpNetworkMatrix.hpp" #include "ClpDualRowSteepest.hpp" #include "ClpDualRowDantzig.hpp" #include "ClpLinearObjective.hpp" #include "ClpPrimalColumnSteepest.hpp" #include "ClpPrimalColumnDantzig.hpp" #include "ClpPresolve.hpp" #include "CbcOrClpParam.hpp" #include "CoinSignal.hpp" #ifdef DMALLOC #include "dmalloc.h" #endif #ifdef WSSMP_BARRIER #define FOREIGN_BARRIER #endif #ifdef UFL_BARRIER #define FOREIGN_BARRIER #endif #ifdef TAUCS_BARRIER #define FOREIGN_BARRIER #endif static double totalTime=0.0; static bool maskMatches(const int * starts, char ** masks, std::string & check); static ClpSimplex * currentModel = NULL; extern "C" { static void #if defined(_MSC_VER) __cdecl #endif // _MSC_VER signal_handler(int whichSignal) { if (currentModel!=NULL) currentModel->setMaximumIterations(0); // stop at next iterations return; } } //############################################################################# #ifdef NDEBUG #undef NDEBUG #endif int mainTest (int argc, const char *argv[],int algorithm, ClpSimplex empty, bool doPresolve,int switchOff,bool doVector); static void statistics(ClpSimplex * originalModel, ClpSimplex * model); static void generateCode(const char * fileName,int type); // Returns next valid field int CbcOrClpRead_mode=1; FILE * CbcOrClpReadCommand=stdin; int #if defined(_MSC_VER) __cdecl #endif // _MSC_VER main (int argc, const char *argv[]) { // next {} is just to make sure all memory should be freed - for debug { double time1 = CoinCpuTime(),time2; // Set up all non-standard stuff //int numberModels=1; ClpSimplex * models = new ClpSimplex[1]; // default action on import int allowImportErrors=0; int keepImportNames=1; int doIdiot=-1; int outputFormat=2; int slpValue=-1; int cppValue=-1; int printOptions=0; int printMode=0; int presolveOptions=0; int doCrash=0; int doVector=0; int doSprint=-1; // set reasonable defaults int preSolve=5; bool preSolveFile=false; models->setPerturbation(50); models->messageHandler()->setPrefix(false); const char dirsep = CoinFindDirSeparator(); std::string directory; std::string dirSample; std::string dirNetlib; std::string dirMiplib; if (dirsep == '/') { directory = "./"; dirSample = "../../Data/Sample/"; dirNetlib = "../../Data/Netlib/"; dirMiplib = "../../Data/miplib3/"; } else { directory = ".\\"; dirSample = "..\\..\\Data\\Sample\\"; dirNetlib = "..\\..\\Data\\Netlib\\"; dirMiplib = "..\\..\\Data\\miplib3\\"; } std::string defaultDirectory = directory; std::string importFile =""; std::string exportFile ="default.mps"; std::string importBasisFile =""; int basisHasValues=0; int substitution=3; int dualize=3; // dualize if looks promising std::string exportBasisFile ="default.bas"; std::string saveFile ="default.prob"; std::string restoreFile ="default.prob"; std::string solutionFile ="stdout"; std::string solutionSaveFile ="solution.file"; std::string printMask=""; CbcOrClpParam parameters[CBCMAXPARAMETERS]; int numberParameters ; establishParams(numberParameters,parameters) ; parameters[whichParam(BASISIN,numberParameters,parameters)].setStringValue(importBasisFile); parameters[whichParam(BASISOUT,numberParameters,parameters)].setStringValue(exportBasisFile); parameters[whichParam(PRINTMASK,numberParameters,parameters)].setStringValue(printMask); parameters[whichParam(DIRECTORY,numberParameters,parameters)].setStringValue(directory); parameters[whichParam(DIRSAMPLE,numberParameters,parameters)].setStringValue(dirSample); parameters[whichParam(DIRNETLIB,numberParameters,parameters)].setStringValue(dirNetlib); parameters[whichParam(DIRMIPLIB,numberParameters,parameters)].setStringValue(dirMiplib); parameters[whichParam(DUALBOUND,numberParameters,parameters)].setDoubleValue(models->dualBound()); parameters[whichParam(DUALTOLERANCE,numberParameters,parameters)].setDoubleValue(models->dualTolerance()); parameters[whichParam(EXPORT,numberParameters,parameters)].setStringValue(exportFile); parameters[whichParam(IDIOT,numberParameters,parameters)].setIntValue(doIdiot); parameters[whichParam(IMPORT,numberParameters,parameters)].setStringValue(importFile); parameters[whichParam(SOLVERLOGLEVEL,numberParameters,parameters)].setIntValue(models->logLevel()); parameters[whichParam(MAXFACTOR,numberParameters,parameters)].setIntValue(models->factorizationFrequency()); parameters[whichParam(MAXITERATION,numberParameters,parameters)].setIntValue(models->maximumIterations()); parameters[whichParam(OUTPUTFORMAT,numberParameters,parameters)].setIntValue(outputFormat); parameters[whichParam(PRESOLVEPASS,numberParameters,parameters)].setIntValue(preSolve); parameters[whichParam(PERTVALUE,numberParameters,parameters)].setIntValue(models->perturbation()); parameters[whichParam(PRIMALTOLERANCE,numberParameters,parameters)].setDoubleValue(models->primalTolerance()); parameters[whichParam(PRIMALWEIGHT,numberParameters,parameters)].setDoubleValue(models->infeasibilityCost()); parameters[whichParam(RESTORE,numberParameters,parameters)].setStringValue(restoreFile); parameters[whichParam(SAVE,numberParameters,parameters)].setStringValue(saveFile); parameters[whichParam(TIMELIMIT,numberParameters,parameters)].setDoubleValue(models->maximumSeconds()); parameters[whichParam(SOLUTION,numberParameters,parameters)].setStringValue(solutionFile); parameters[whichParam(SAVESOL,numberParameters,parameters)].setStringValue(solutionSaveFile); parameters[whichParam(SPRINT,numberParameters,parameters)].setIntValue(doSprint); parameters[whichParam(SUBSTITUTION,numberParameters,parameters)].setIntValue(substitution); parameters[whichParam(DUALIZE,numberParameters,parameters)].setIntValue(dualize); parameters[whichParam(PRESOLVETOLERANCE,numberParameters,parameters)].setDoubleValue(1.0e-8); int verbose=0; // total number of commands read int numberGoodCommands=0; bool * goodModels = new bool[1]; // Hidden stuff for barrier int choleskyType = 0; int gamma=0; int scaleBarrier=0; int doKKT=0; int crossover=2; // do crossover unless quadratic int iModel=0; goodModels[0]=false; //models[0].scaling(1); //models[0].setDualBound(1.0e6); //models[0].setDualTolerance(1.0e-7); //ClpDualRowSteepest steep; //models[0].setDualRowPivotAlgorithm(steep); //models[0].setPrimalTolerance(1.0e-7); //ClpPrimalColumnSteepest steepP; //models[0].setPrimalColumnPivotAlgorithm(steepP); std::string field; std::cout<<"Coin LP version "<<CLPVERSION <<", build "<<__DATE__<<std::endl; // Print command line if (argc>1) { printf("command line - "); for (int i=0;i<argc;i++) printf("%s ",argv[i]); printf("\n"); } while (1) { // next command field=CoinReadGetCommand(argc,argv); // exit if null or similar if (!field.length()) { if (numberGoodCommands==1&&goodModels[0]) { // we just had file name - do dual or primal field="either"; } else if (!numberGoodCommands) { // let's give the sucker a hint std::cout <<"Clp takes input from arguments ( - switches to stdin)" <<std::endl <<"Enter ? for list of commands or help"<<std::endl; field="-"; } else { break; } } // see if ? at end int numberQuery=0; if (field!="?"&&field!="???") { int length = field.length(); int i; for (i=length-1;i>0;i--) { if (field[i]=='?') numberQuery++; else break; } field=field.substr(0,length-numberQuery); } // find out if valid command int iParam; int numberMatches=0; int firstMatch=-1; for ( iParam=0; iParam<numberParameters; iParam++ ) { int match = parameters[iParam].matches(field); if (match==1) { numberMatches = 1; firstMatch=iParam; break; } else { if (match&&firstMatch<0) firstMatch=iParam; numberMatches += match>>1; } } if (iParam<numberParameters&&!numberQuery) { // found CbcOrClpParam found = parameters[iParam]; CbcOrClpParameterType type = found.type(); int valid; numberGoodCommands++; if (type==GENERALQUERY) { std::cout<<"In argument list keywords have leading - " ", -stdin or just - switches to stdin"<<std::endl; std::cout<<"One command per line (and no -)"<<std::endl; std::cout<<"abcd? gives list of possibilities, if only one + explanation"<<std::endl; std::cout<<"abcd?? adds explanation, if only one fuller help"<<std::endl; std::cout<<"abcd without value (where expected) gives current value"<<std::endl; std::cout<<"abcd value sets value"<<std::endl; std::cout<<"Commands are:"<<std::endl; int maxAcross=5; bool evenHidden=false; if ((verbose&8)!=0) { // even hidden evenHidden = true; verbose &= ~8; } if (verbose) maxAcross=1; int limits[]={1,101,201,301,401}; std::vector<std::string> types; types.push_back("Double parameters:"); types.push_back("Int parameters:"); types.push_back("Keyword parameters:"); types.push_back("Actions or string parameters:"); int iType; for (iType=0;iType<4;iType++) { int across=0; if ((verbose%4)!=0) std::cout<<std::endl; std::cout<<types[iType]<<std::endl; if ((verbose&2)!=0) std::cout<<std::endl; for ( iParam=0; iParam<numberParameters; iParam++ ) { int type = parameters[iParam].type(); if ((parameters[iParam].displayThis()||evenHidden)&& type>=limits[iType] &&type<limits[iType+1]) { if (!across) { if ((verbose&2)==0) std::cout<<" "; else std::cout<<"Command "; } std::cout<<parameters[iParam].matchName()<<" "; across++; if (across==maxAcross) { across=0; if (verbose) { // put out description as well if ((verbose&1)!=0) std::cout<<parameters[iParam].shortHelp(); std::cout<<std::endl; if ((verbose&2)!=0) { std::cout<<"---- description"<<std::endl; parameters[iParam].printLongHelp(); std::cout<<"----"<<std::endl<<std::endl; } } else { std::cout<<std::endl; } } } } if (across) std::cout<<std::endl; } } else if (type==FULLGENERALQUERY) { std::cout<<"Full list of commands is:"<<std::endl; int maxAcross=5; int limits[]={1,101,201,301,401}; std::vector<std::string> types; types.push_back("Double parameters:"); types.push_back("Int parameters:"); types.push_back("Keyword parameters and others:"); types.push_back("Actions:"); int iType; for (iType=0;iType<4;iType++) { int across=0; std::cout<<types[iType]<<std::endl; for ( iParam=0; iParam<numberParameters; iParam++ ) { int type = parameters[iParam].type(); if (type>=limits[iType] &&type<limits[iType+1]) { if (!across) std::cout<<" "; std::cout<<parameters[iParam].matchName()<<" "; across++; if (across==maxAcross) { std::cout<<std::endl; across=0; } } } if (across) std::cout<<std::endl; } } else if (type<101) { // get next field as double double value = CoinReadGetDoubleField(argc,argv,&valid); if (!valid) { parameters[iParam].setDoubleParameter(models+iModel,value); } else if (valid==1) { std::cout<<" is illegal for double parameter "<<parameters[iParam].name()<<" value remains "<< parameters[iParam].doubleValue()<<std::endl; } else { std::cout<<parameters[iParam].name()<<" has value "<< parameters[iParam].doubleValue()<<std::endl; } } else if (type<201) { // get next field as int int value = CoinReadGetIntField(argc,argv,&valid); if (!valid) { if (parameters[iParam].type()==PRESOLVEPASS) preSolve = value; else if (parameters[iParam].type()==IDIOT) doIdiot = value; else if (parameters[iParam].type()==SPRINT) doSprint = value; else if (parameters[iParam].type()==OUTPUTFORMAT) outputFormat = value; else if (parameters[iParam].type()==SLPVALUE) slpValue = value; else if (parameters[iParam].type()==CPP) cppValue = value; else if (parameters[iParam].type()==PRESOLVEOPTIONS) presolveOptions = value; else if (parameters[iParam].type()==PRINTOPTIONS) printOptions = value; else if (parameters[iParam].type()==SUBSTITUTION) substitution = value; else if (parameters[iParam].type()==DUALIZE) dualize = value; else if (parameters[iParam].type()==VERBOSE) verbose = value; parameters[iParam].setIntParameter(models+iModel,value); } else if (valid==1) { std::cout<<" is illegal for integer parameter "<<parameters[iParam].name()<<" value remains "<< parameters[iParam].intValue()<<std::endl; } else { std::cout<<parameters[iParam].name()<<" has value "<< parameters[iParam].intValue()<<std::endl; } } else if (type<301) { // one of several strings std::string value = CoinReadGetString(argc,argv); int action = parameters[iParam].parameterOption(value); if (action<0) { if (value!="EOL") { // no match parameters[iParam].printOptions(); } else { // print current value std::cout<<parameters[iParam].name()<<" has value "<< parameters[iParam].currentOption()<<std::endl; } } else { parameters[iParam].setCurrentOption(action); // for now hard wired switch (type) { case DIRECTION: if (action==0) models[iModel].setOptimizationDirection(1); else if (action==1) models[iModel].setOptimizationDirection(-1); else models[iModel].setOptimizationDirection(0); break; case DUALPIVOT: if (action==0) { ClpDualRowSteepest steep(3); models[iModel].setDualRowPivotAlgorithm(steep); } else if (action==1) { //ClpDualRowDantzig dantzig; ClpDualRowSteepest dantzig(5); models[iModel].setDualRowPivotAlgorithm(dantzig); } else if (action==2) { // partial steep ClpDualRowSteepest steep(2); models[iModel].setDualRowPivotAlgorithm(steep); } else { ClpDualRowSteepest steep; models[iModel].setDualRowPivotAlgorithm(steep); } break; case PRIMALPIVOT: if (action==0) { ClpPrimalColumnSteepest steep(3); models[iModel].setPrimalColumnPivotAlgorithm(steep); } else if (action==1) { ClpPrimalColumnSteepest steep(0); models[iModel].setPrimalColumnPivotAlgorithm(steep); } else if (action==2) { ClpPrimalColumnDantzig dantzig; models[iModel].setPrimalColumnPivotAlgorithm(dantzig); } else if (action==3) { ClpPrimalColumnSteepest steep(4); models[iModel].setPrimalColumnPivotAlgorithm(steep); } else if (action==4) { ClpPrimalColumnSteepest steep(1); models[iModel].setPrimalColumnPivotAlgorithm(steep); } else if (action==5) { ClpPrimalColumnSteepest steep(2); models[iModel].setPrimalColumnPivotAlgorithm(steep); } else if (action==6) { ClpPrimalColumnSteepest steep(10); models[iModel].setPrimalColumnPivotAlgorithm(steep); } break; case SCALING: models[iModel].scaling(action); break; case AUTOSCALE: models[iModel].setAutomaticScaling(action!=0); break; case SPARSEFACTOR: models[iModel].setSparseFactorization((1-action)!=0); break; case BIASLU: models[iModel].factorization()->setBiasLU(action); break; case PERTURBATION: if (action==0) models[iModel].setPerturbation(50); else models[iModel].setPerturbation(100); break; case ERRORSALLOWED: allowImportErrors = action; break; case INTPRINT: printMode=action; break; case KEEPNAMES: keepImportNames = 1-action; break; case PRESOLVE: if (action==0) preSolve = 5; else if (action==1) preSolve=0; else if (action==2) preSolve=10; else preSolveFile=true; break; case PFI: models[iModel].factorization()->setForrestTomlin(action==0); break; case CRASH: doCrash=action; break; case VECTOR: doVector=action; break; case MESSAGES: models[iModel].messageHandler()->setPrefix(action!=0); break; case CHOLESKY: choleskyType = action; break; case GAMMA: gamma=action; break; case BARRIERSCALE: scaleBarrier=action; break; case KKT: doKKT=action; break; case CROSSOVER: crossover=action; break; default: abort(); } } } else { // action if (type==EXIT) break; // stop all switch (type) { case DUALSIMPLEX: case PRIMALSIMPLEX: case EITHERSIMPLEX: case BARRIER: // synonym for dual case BAB: if (goodModels[iModel]) { double objScale = parameters[whichParam(OBJSCALE2,numberParameters,parameters)].doubleValue(); if (objScale!=1.0) { int iColumn; int numberColumns=models[iModel].numberColumns(); double * dualColumnSolution = models[iModel].dualColumnSolution(); ClpObjective * obj = models[iModel].objectiveAsObject(); assert(dynamic_cast<ClpLinearObjective *> (obj)); double offset; double * objective = obj->gradient(NULL,NULL,offset,true); for (iColumn=0;iColumn<numberColumns;iColumn++) { dualColumnSolution[iColumn] *= objScale; objective[iColumn] *= objScale;; } int iRow; int numberRows=models[iModel].numberRows(); double * dualRowSolution = models[iModel].dualRowSolution(); for (iRow=0;iRow<numberRows;iRow++) dualRowSolution[iRow] *= objScale; models[iModel].setObjectiveOffset(objScale*models[iModel].objectiveOffset()); } ClpSolve::SolveType method; ClpSolve::PresolveType presolveType; ClpSimplex * model2 = models+iModel; if (dualize) { bool tryIt=true; double fractionColumn=1.0; double fractionRow=1.0; if (dualize==3) { dualize=1; int numberColumns=model2->numberColumns(); int numberRows=model2->numberRows(); if (numberRows<50000||5*numberColumns>numberRows) { tryIt=false; } else { fractionColumn=0.1; fractionRow=0.1; } } if (tryIt) { model2 = static_cast<ClpSimplexOther *> (model2)->dualOfModel(fractionRow,fractionColumn); if (model2) { printf("Dual of model has %d rows and %d columns\n", model2->numberRows(),model2->numberColumns()); model2->setOptimizationDirection(1.0); } else { model2 = models+iModel; dualize=0; } } else { dualize=0; } } ClpSolve solveOptions; solveOptions.setPresolveActions(presolveOptions); solveOptions.setSubstitution(substitution); if (preSolve!=5&&preSolve) { presolveType=ClpSolve::presolveNumber; if (preSolve<0) { preSolve = - preSolve; if (preSolve<=100) { presolveType=ClpSolve::presolveNumber; printf("Doing %d presolve passes - picking up non-costed slacks\n", preSolve); solveOptions.setDoSingletonColumn(true); } else { preSolve -=100; presolveType=ClpSolve::presolveNumberCost; printf("Doing %d presolve passes - picking up costed slacks\n", preSolve); } } } else if (preSolve) { presolveType=ClpSolve::presolveOn; } else { presolveType=ClpSolve::presolveOff; } solveOptions.setPresolveType(presolveType,preSolve); if (type==DUALSIMPLEX||type==BAB) { method=ClpSolve::useDual; } else if (type==PRIMALSIMPLEX) { method=ClpSolve::usePrimalorSprint; } else if (type==EITHERSIMPLEX) { method=ClpSolve::automatic; } else { method = ClpSolve::useBarrier; if (crossover==1) { method=ClpSolve::useBarrierNoCross; } else if (crossover==2) { ClpObjective * obj = models[iModel].objectiveAsObject(); if (obj->type()>1) { method=ClpSolve::useBarrierNoCross; presolveType=ClpSolve::presolveOff; solveOptions.setPresolveType(presolveType,preSolve); } } } solveOptions.setSolveType(method); if(preSolveFile) presolveOptions |= 0x40000000; solveOptions.setSpecialOption(4,presolveOptions); solveOptions.setSpecialOption(5,printOptions&1); if (doVector) { ClpMatrixBase * matrix = models[iModel].clpMatrix(); if (dynamic_cast< ClpPackedMatrix*>(matrix)) { ClpPackedMatrix * clpMatrix = dynamic_cast< ClpPackedMatrix*>(matrix); clpMatrix->makeSpecialColumnCopy(); } } if (method==ClpSolve::useDual) { // dual if (doCrash) solveOptions.setSpecialOption(0,1,doCrash); // crash else if (doIdiot) solveOptions.setSpecialOption(0,2,doIdiot); // possible idiot } else if (method==ClpSolve::usePrimalorSprint) { // primal // if slp turn everything off if (slpValue>0) { doCrash=false; doSprint=0; doIdiot=-1; solveOptions.setSpecialOption(1,10,slpValue); // slp method=ClpSolve::usePrimal; } if (doCrash) { solveOptions.setSpecialOption(1,1,doCrash); // crash } else if (doSprint>0) { // sprint overrides idiot solveOptions.setSpecialOption(1,3,doSprint); // sprint } else if (doIdiot>0) { solveOptions.setSpecialOption(1,2,doIdiot); // idiot } else if (slpValue<=0) { if (doIdiot==0) { if (doSprint==0) solveOptions.setSpecialOption(1,4); // all slack else solveOptions.setSpecialOption(1,9); // all slack or sprint } else { if (doSprint==0) solveOptions.setSpecialOption(1,8); // all slack or idiot else solveOptions.setSpecialOption(1,7); // initiative } } if (basisHasValues==-1) solveOptions.setSpecialOption(1,11); // switch off values } else if (method==ClpSolve::useBarrier||method==ClpSolve::useBarrierNoCross) { int barrierOptions = choleskyType; if (scaleBarrier) barrierOptions |= 8; if (doKKT) barrierOptions |= 16; if (gamma) barrierOptions |= 32*gamma; if (crossover==3) barrierOptions |= 256; // try presolve in crossover solveOptions.setSpecialOption(4,barrierOptions); } int status; if (cppValue>=0) { // generate code FILE * fp = fopen("user_driver.cpp","w"); if (fp) { // generate enough to do solveOptions model2->generateCpp(fp); solveOptions.generateCpp(fp); fclose(fp); // now call generate code generateCode("user_driver.cpp",cppValue); } else { std::cout<<"Unable to open file user_driver.cpp"<<std::endl; } } #ifdef CLP_MULTIPLE_FACTORIZATIONS int denseCode = parameters[whichParam(DENSE,numberParameters,parameters)].intValue(); model2->factorization()->setGoDenseThreshold(denseCode); int smallCode = parameters[whichParam(SMALLFACT,numberParameters,parameters)].intValue(); model2->factorization()->setGoSmallThreshold(smallCode); model2->factorization()->goDenseOrSmall(model2->numberRows()); #endif try { status=model2->initialSolve(solveOptions); } catch (CoinError e) { e.print(); status=-1; } if (dualize) { int returnCode=static_cast<ClpSimplexOther *> (models+iModel)->restoreFromDual(model2); if (model2->status()==3) returnCode=0; delete model2; if (returnCode&&dualize!=2) { currentModel = models+iModel; // register signal handler signal(SIGINT,signal_handler); models[iModel].primal(1); currentModel=NULL; } } if (status>=0) basisHasValues=1; } else { std::cout<<"** Current model not valid"<<std::endl; } break; case STATISTICS: if (goodModels[iModel]) { // If presolve on look at presolved bool deleteModel2=false; ClpSimplex * model2 = models+iModel; if (preSolve) { ClpPresolve pinfo; int presolveOptions2 = presolveOptions&~0x40000000; if ((presolveOptions2&0xffff)!=0) pinfo.setPresolveActions(presolveOptions2); pinfo.setSubstitution(substitution); if ((printOptions&1)!=0) pinfo.statistics(); double presolveTolerance = parameters[whichParam(PRESOLVETOLERANCE,numberParameters,parameters)].doubleValue(); model2 = pinfo.presolvedModel(models[iModel],presolveTolerance, true,preSolve); if (model2) { printf("Statistics for presolved model\n"); deleteModel2=true; } else { printf("Presolved model looks infeasible - will use unpresolved\n"); model2 = models+iModel; } } else { printf("Statistics for unpresolved model\n"); model2 = models+iModel; } statistics(models+iModel,model2); if (deleteModel2) delete model2; } else { std::cout<<"** Current model not valid"<<std::endl; } break; case TIGHTEN: if (goodModels[iModel]) { int numberInfeasibilities = models[iModel].tightenPrimalBounds(); if (numberInfeasibilities) std::cout<<"** Analysis indicates model infeasible"<<std::endl; } else { std::cout<<"** Current model not valid"<<std::endl; } break; case PLUSMINUS: if (goodModels[iModel]) { ClpMatrixBase * saveMatrix = models[iModel].clpMatrix(); ClpPackedMatrix* clpMatrix = dynamic_cast< ClpPackedMatrix*>(saveMatrix); if (clpMatrix) { ClpPlusMinusOneMatrix * newMatrix = new ClpPlusMinusOneMatrix(*(clpMatrix->matrix())); if (newMatrix->getIndices()) { models[iModel].replaceMatrix(newMatrix); delete saveMatrix; std::cout<<"Matrix converted to +- one matrix"<<std::endl; } else { std::cout<<"Matrix can not be converted to +- 1 matrix"<<std::endl; } } else { std::cout<<"Matrix not a ClpPackedMatrix"<<std::endl; } } else { std::cout<<"** Current model not valid"<<std::endl; } break; case NETWORK: if (goodModels[iModel]) { ClpMatrixBase * saveMatrix = models[iModel].clpMatrix(); ClpPackedMatrix* clpMatrix = dynamic_cast< ClpPackedMatrix*>(saveMatrix); if (clpMatrix) { ClpNetworkMatrix * newMatrix = new ClpNetworkMatrix(*(clpMatrix->matrix())); if (newMatrix->getIndices()) { models[iModel].replaceMatrix(newMatrix); delete saveMatrix; std::cout<<"Matrix converted to network matrix"<<std::endl; } else { std::cout<<"Matrix can not be converted to network matrix"<<std::endl; } } else { std::cout<<"Matrix not a ClpPackedMatrix"<<std::endl; } } else { std::cout<<"** Current model not valid"<<std::endl; } break; case IMPORT: { // get next field field = CoinReadGetString(argc,argv); if (field=="$") { field = parameters[iParam].stringValue(); } else if (field=="EOL") { parameters[iParam].printString(); break; } else { parameters[iParam].setStringValue(field); } std::string fileName; bool canOpen=false; // See if gmpl file int gmpl=0; std::string gmplData; if (field=="-") { // stdin canOpen=true; fileName = "-"; } else { // See if .lp { const char * c_name = field.c_str(); int length = strlen(c_name); if (length>3&&!strncmp(c_name+length-3,".lp",3)) gmpl=-1; // .lp } bool absolutePath; if (dirsep=='/') { // non Windows (or cygwin) absolutePath=(field[0]=='/'); } else { //Windows (non cycgwin) absolutePath=(field[0]=='\\'); // but allow for : if (strchr(field.c_str(),':')) absolutePath=true; } if (absolutePath) { fileName = field; } else if (field[0]=='~') { char * environVar = getenv("HOME"); if (environVar) { std::string home(environVar); field=field.erase(0,1); fileName = home+field; } else { fileName=field; } } else { fileName = directory+field; // See if gmpl (model & data) - or even lp file int length = field.size(); int percent = field.find('%'); if (percent<length&&percent>0) { gmpl=1; fileName = directory+field.substr(0,percent); gmplData = directory+field.substr(percent+1); if (percent<length-1) gmpl=2; // two files printf("GMPL model file %s and data file %s\n", fileName.c_str(),gmplData.c_str()); } } std::string name=fileName; if (fileCoinReadable(name)) { // can open - lets go for it canOpen=true; if (gmpl==2) { FILE *fp; fp=fopen(gmplData.c_str(),"r"); if (fp) { fclose(fp); } else { canOpen=false; std::cout<<"Unable to open file "<<gmplData<<std::endl; } } } else { std::cout<<"Unable to open file "<<fileName<<std::endl; } } if (canOpen) { int status; if (!gmpl) status =models[iModel].readMps(fileName.c_str(), keepImportNames!=0, allowImportErrors!=0); else if (gmpl>0) status= models[iModel].readGMPL(fileName.c_str(), (gmpl==2) ? gmplData.c_str() : NULL, keepImportNames!=0); else status= models[iModel].readLp(fileName.c_str(),1.0e-12); if (!status||(status>0&&allowImportErrors)) { goodModels[iModel]=true; // sets to all slack (not necessary?) models[iModel].createStatus(); time2 = CoinCpuTime(); totalTime += time2-time1; time1=time2; // Go to canned file if just input file if (CbcOrClpRead_mode==2&&argc==2) { // only if ends .mps char * find = const_cast<char *>(strstr(fileName.c_str(),".mps")); if (find&&find[4]=='\0') { find[1]='p'; find[2]='a';find[3]='r'; FILE *fp=fopen(fileName.c_str(),"r"); if (fp) { CbcOrClpReadCommand=fp; // Read from that file CbcOrClpRead_mode=-1; } } } } else { // errors std::cout<<"There were "<<status<< " errors on input"<<std::endl; } } } break; case EXPORT: if (goodModels[iModel]) { double objScale = parameters[whichParam(OBJSCALE2,numberParameters,parameters)].doubleValue(); if (objScale!=1.0) { int iColumn; int numberColumns=models[iModel].numberColumns(); double * dualColumnSolution = models[iModel].dualColumnSolution(); ClpObjective * obj = models[iModel].objectiveAsObject(); assert(dynamic_cast<ClpLinearObjective *> (obj)); double offset; double * objective = obj->gradient(NULL,NULL,offset,true); for (iColumn=0;iColumn<numberColumns;iColumn++) { dualColumnSolution[iColumn] *= objScale; objective[iColumn] *= objScale;; } int iRow; int numberRows=models[iModel].numberRows(); double * dualRowSolution = models[iModel].dualRowSolution(); for (iRow=0;iRow<numberRows;iRow++) dualRowSolution[iRow] *= objScale; models[iModel].setObjectiveOffset(objScale*models[iModel].objectiveOffset()); } // get next field field = CoinReadGetString(argc,argv); if (field=="$") { field = parameters[iParam].stringValue(); } else if (field=="EOL") { parameters[iParam].printString(); break; } else { parameters[iParam].setStringValue(field); } std::string fileName; bool canOpen=false; if (field[0]=='/'||field[0]=='\\') { fileName = field; } else if (field[0]=='~') { char * environVar = getenv("HOME"); if (environVar) { std::string home(environVar); field=field.erase(0,1); fileName = home+field; } else { fileName=field; } } else { fileName = directory+field; } FILE *fp=fopen(fileName.c_str(),"w"); if (fp) { // can open - lets go for it fclose(fp); canOpen=true; } else { std::cout<<"Unable to open file "<<fileName<<std::endl; } if (canOpen) { // If presolve on then save presolved bool deleteModel2=false; ClpSimplex * model2 = models+iModel; if (dualize&&dualize<3) { model2 = static_cast<ClpSimplexOther *> (model2)->dualOfModel(); printf("Dual of model has %d rows and %d columns\n", model2->numberRows(),model2->numberColumns()); model2->setOptimizationDirection(1.0); preSolve=0; // as picks up from model } if (preSolve) { ClpPresolve pinfo; int presolveOptions2 = presolveOptions&~0x40000000; if ((presolveOptions2&0xffff)!=0) pinfo.setPresolveActions(presolveOptions2); pinfo.setSubstitution(substitution); if ((printOptions&1)!=0) pinfo.statistics(); double presolveTolerance = parameters[whichParam(PRESOLVETOLERANCE,numberParameters,parameters)].doubleValue(); model2 = pinfo.presolvedModel(models[iModel],presolveTolerance, true,preSolve,false,false); if (model2) { printf("Saving presolved model on %s\n", fileName.c_str()); deleteModel2=true; } else { printf("Presolved model looks infeasible - saving original on %s\n", fileName.c_str()); deleteModel2=false; model2 = models+iModel; } } else { printf("Saving model on %s\n", fileName.c_str()); } #if 0 // Convert names int iRow; int numberRows=model2->numberRows(); int iColumn; int numberColumns=model2->numberColumns(); char ** rowNames = NULL; char ** columnNames = NULL; if (model2->lengthNames()) { rowNames = new char * [numberRows]; for (iRow=0;iRow<numberRows;iRow++) { rowNames[iRow] = CoinStrdup(model2->rowName(iRow).c_str()); #ifdef STRIPBLANKS char * xx = rowNames[iRow]; int i; int length = strlen(xx); int n=0; for (i=0;i<length;i++) { if (xx[i]!=' ') xx[n++]=xx[i]; } xx[n]='\0'; #endif } columnNames = new char * [numberColumns]; for (iColumn=0;iColumn<numberColumns;iColumn++) { columnNames[iColumn] = CoinStrdup(model2->columnName(iColumn).c_str()); #ifdef STRIPBLANKS char * xx = columnNames[iColumn]; int i; int length = strlen(xx); int n=0; for (i=0;i<length;i++) { if (xx[i]!=' ') xx[n++]=xx[i]; } xx[n]='\0'; #endif } } CoinMpsIO writer; writer.setMpsData(*model2->matrix(), COIN_DBL_MAX, model2->getColLower(), model2->getColUpper(), model2->getObjCoefficients(), (const char*) 0 /*integrality*/, model2->getRowLower(), model2->getRowUpper(), columnNames, rowNames); // Pass in array saying if each variable integer writer.copyInIntegerInformation(model2->integerInformation()); writer.setObjectiveOffset(model2->objectiveOffset()); writer.writeMps(fileName.c_str(),0,1,1); if (rowNames) { for (iRow=0;iRow<numberRows;iRow++) { free(rowNames[iRow]); } delete [] rowNames; for (iColumn=0;iColumn<numberColumns;iColumn++) { free(columnNames[iColumn]); } delete [] columnNames; } #else model2->writeMps(fileName.c_str(),(outputFormat-1)/2,1+((outputFormat-1)&1)); #endif if (deleteModel2) delete model2; time2 = CoinCpuTime(); totalTime += time2-time1; time1=time2; } } else { std::cout<<"** Current model not valid"<<std::endl; } break; case BASISIN: if (goodModels[iModel]) { // get next field field = CoinReadGetString(argc,argv); if (field=="$") { field = parameters[iParam].stringValue(); } else if (field=="EOL") { parameters[iParam].printString(); break; } else { parameters[iParam].setStringValue(field); } std::string fileName; bool canOpen=false; if (field=="-") { // stdin canOpen=true; fileName = "-"; } else { if (field[0]=='/'||field[0]=='\\') { fileName = field; } else if (field[0]=='~') { char * environVar = getenv("HOME"); if (environVar) { std::string home(environVar); field=field.erase(0,1); fileName = home+field; } else { fileName=field; } } else { fileName = directory+field; } FILE *fp=fopen(fileName.c_str(),"r"); if (fp) { // can open - lets go for it fclose(fp); canOpen=true; } else { std::cout<<"Unable to open file "<<fileName<<std::endl; } } if (canOpen) { int values = models[iModel].readBasis(fileName.c_str()); if (values==0) basisHasValues=-1; else basisHasValues=1; } } else { std::cout<<"** Current model not valid"<<std::endl; } break; case PRINTMASK: // get next field { std::string name = CoinReadGetString(argc,argv); if (name!="EOL") { parameters[iParam].setStringValue(name); printMask = name; } else { parameters[iParam].printString(); } } break; case BASISOUT: if (goodModels[iModel]) { // get next field field = CoinReadGetString(argc,argv); if (field=="$") { field = parameters[iParam].stringValue(); } else if (field=="EOL") { parameters[iParam].printString(); break; } else { parameters[iParam].setStringValue(field); } std::string fileName; bool canOpen=false; if (field[0]=='/'||field[0]=='\\') { fileName = field; } else if (field[0]=='~') { char * environVar = getenv("HOME"); if (environVar) { std::string home(environVar); field=field.erase(0,1); fileName = home+field; } else { fileName=field; } } else { fileName = directory+field; } FILE *fp=fopen(fileName.c_str(),"w"); if (fp) { // can open - lets go for it fclose(fp); canOpen=true; } else { std::cout<<"Unable to open file "<<fileName<<std::endl; } if (canOpen) { ClpSimplex * model2 = models+iModel; model2->writeBasis(fileName.c_str(),outputFormat>1,outputFormat-2); time2 = CoinCpuTime(); totalTime += time2-time1; time1=time2; } } else { std::cout<<"** Current model not valid"<<std::endl; } break; case SAVE: { // get next field field = CoinReadGetString(argc,argv); if (field=="$") { field = parameters[iParam].stringValue(); } else if (field=="EOL") { parameters[iParam].printString(); break; } else { parameters[iParam].setStringValue(field); } std::string fileName; bool canOpen=false; if (field[0]=='/'||field[0]=='\\') { fileName = field; } else if (field[0]=='~') { char * environVar = getenv("HOME"); if (environVar) { std::string home(environVar); field=field.erase(0,1); fileName = home+field; } else { fileName=field; } } else { fileName = directory+field; } FILE *fp=fopen(fileName.c_str(),"wb"); if (fp) { // can open - lets go for it fclose(fp); canOpen=true; } else { std::cout<<"Unable to open file "<<fileName<<std::endl; } if (canOpen) { int status; // If presolve on then save presolved bool deleteModel2=false; ClpSimplex * model2 = models+iModel; if (preSolve) { ClpPresolve pinfo; double presolveTolerance = parameters[whichParam(PRESOLVETOLERANCE,numberParameters,parameters)].doubleValue(); model2 = pinfo.presolvedModel(models[iModel],presolveTolerance, false,preSolve); if (model2) { printf("Saving presolved model on %s\n", fileName.c_str()); deleteModel2=true; } else { printf("Presolved model looks infeasible - saving original on %s\n", fileName.c_str()); deleteModel2=false; model2 = models+iModel; } } else { printf("Saving model on %s\n", fileName.c_str()); } status =model2->saveModel(fileName.c_str()); if (deleteModel2) delete model2; if (!status) { goodModels[iModel]=true; time2 = CoinCpuTime(); totalTime += time2-time1; time1=time2; } else { // errors std::cout<<"There were errors on output"<<std::endl; } } } break; case RESTORE: { // get next field field = CoinReadGetString(argc,argv); if (field=="$") { field = parameters[iParam].stringValue(); } else if (field=="EOL") { parameters[iParam].printString(); break; } else { parameters[iParam].setStringValue(field); } std::string fileName; bool canOpen=false; if (field[0]=='/'||field[0]=='\\') { fileName = field; } else if (field[0]=='~') { char * environVar = getenv("HOME"); if (environVar) { std::string home(environVar); field=field.erase(0,1); fileName = home+field; } else { fileName=field; } } else { fileName = directory+field; } FILE *fp=fopen(fileName.c_str(),"rb"); if (fp) { // can open - lets go for it fclose(fp); canOpen=true; } else { std::cout<<"Unable to open file "<<fileName<<std::endl; } if (canOpen) { int status =models[iModel].restoreModel(fileName.c_str()); if (!status) { goodModels[iModel]=true; time2 = CoinCpuTime(); totalTime += time2-time1; time1=time2; } else { // errors std::cout<<"There were errors on input"<<std::endl; } } } break; case MAXIMIZE: models[iModel].setOptimizationDirection(-1); break; case MINIMIZE: models[iModel].setOptimizationDirection(1); break; case ALLSLACK: models[iModel].allSlackBasis(true); break; case REVERSE: if (goodModels[iModel]) { int iColumn; int numberColumns=models[iModel].numberColumns(); double * dualColumnSolution = models[iModel].dualColumnSolution(); ClpObjective * obj = models[iModel].objectiveAsObject(); assert(dynamic_cast<ClpLinearObjective *> (obj)); double offset; double * objective = obj->gradient(NULL,NULL,offset,true); for (iColumn=0;iColumn<numberColumns;iColumn++) { dualColumnSolution[iColumn] = -dualColumnSolution[iColumn]; objective[iColumn] = -objective[iColumn]; } int iRow; int numberRows=models[iModel].numberRows(); double * dualRowSolution = models[iModel].dualRowSolution(); for (iRow=0;iRow<numberRows;iRow++) { dualRowSolution[iRow] = -dualRowSolution[iRow]; } models[iModel].setObjectiveOffset(-models[iModel].objectiveOffset()); } break; case DIRECTORY: { std::string name = CoinReadGetString(argc,argv); if (name!="EOL") { int length=name.length(); if (name[length-1]==dirsep) { directory = name; } else { directory = name+dirsep; } parameters[iParam].setStringValue(directory); } else { parameters[iParam].printString(); } } break; case DIRSAMPLE: { std::string name = CoinReadGetString(argc,argv); if (name!="EOL") { int length=name.length(); if (name[length-1]==dirsep) { dirSample = name; } else { dirSample = name+dirsep; } parameters[iParam].setStringValue(dirSample); } else { parameters[iParam].printString(); } } break; case DIRNETLIB: { std::string name = CoinReadGetString(argc,argv); if (name!="EOL") { int length=name.length(); if (name[length-1]==dirsep) { dirNetlib = name; } else { dirNetlib = name+dirsep; } parameters[iParam].setStringValue(dirNetlib); } else { parameters[iParam].printString(); } } break; case DIRMIPLIB: { std::string name = CoinReadGetString(argc,argv); if (name!="EOL") { int length=name.length(); if (name[length-1]==dirsep) { dirMiplib = name; } else { dirMiplib = name+dirsep; } parameters[iParam].setStringValue(dirMiplib); } else { parameters[iParam].printString(); } } break; case STDIN: CbcOrClpRead_mode=-1; break; case NETLIB_DUAL: case NETLIB_EITHER: case NETLIB_BARRIER: case NETLIB_PRIMAL: case NETLIB_TUNE: { // create fields for unitTest const char * fields[4]; int nFields=4; fields[0]="fake main from unitTest"; std::string mpsfield = "-dirSample="; mpsfield += dirSample.c_str(); fields[1]=mpsfield.c_str(); std::string netfield = "-dirNetlib="; netfield += dirNetlib.c_str(); fields[2]=netfield.c_str(); fields[3]="-netlib"; int algorithm; if (type==NETLIB_DUAL) { std::cerr<<"Doing netlib with dual algorithm"<<std::endl; algorithm =0; } else if (type==NETLIB_BARRIER) { std::cerr<<"Doing netlib with barrier algorithm"<<std::endl; algorithm =2; } else if (type==NETLIB_EITHER) { std::cerr<<"Doing netlib with dual or primal algorithm"<<std::endl; algorithm =3; } else if (type==NETLIB_TUNE) { std::cerr<<"Doing netlib with best algorithm!"<<std::endl; algorithm =5; // uncomment next to get active tuning // algorithm=6; } else { std::cerr<<"Doing netlib with primal agorithm"<<std::endl; algorithm=1; } int specialOptions = models[iModel].specialOptions(); models[iModel].setSpecialOptions(0); mainTest(nFields,fields,algorithm,models[iModel], (preSolve!=0),specialOptions,doVector!=0); } break; case UNITTEST: { // create fields for unitTest const char * fields[2]; int nFields=2; fields[0]="fake main from unitTest"; std::string dirfield = "-dirSample="; dirfield += dirSample.c_str(); fields[1]=dirfield.c_str(); int specialOptions = models[iModel].specialOptions(); models[iModel].setSpecialOptions(0); int algorithm=-1; if (models[iModel].numberRows()) algorithm=7; mainTest(nFields,fields,algorithm,models[iModel],(preSolve!=0),specialOptions,doVector!=0); } break; case FAKEBOUND: if (goodModels[iModel]) { // get bound double value = CoinReadGetDoubleField(argc,argv,&valid); if (!valid) { std::cout<<"Setting "<<parameters[iParam].name()<< " to DEBUG "<<value<<std::endl; int iRow; int numberRows=models[iModel].numberRows(); double * rowLower = models[iModel].rowLower(); double * rowUpper = models[iModel].rowUpper(); for (iRow=0;iRow<numberRows;iRow++) { // leave free ones for now if (rowLower[iRow]>-1.0e20||rowUpper[iRow]<1.0e20) { rowLower[iRow]=CoinMax(rowLower[iRow],-value); rowUpper[iRow]=CoinMin(rowUpper[iRow],value); } } int iColumn; int numberColumns=models[iModel].numberColumns(); double * columnLower = models[iModel].columnLower(); double * columnUpper = models[iModel].columnUpper(); for (iColumn=0;iColumn<numberColumns;iColumn++) { // leave free ones for now if (columnLower[iColumn]>-1.0e20|| columnUpper[iColumn]<1.0e20) { columnLower[iColumn]=CoinMax(columnLower[iColumn],-value); columnUpper[iColumn]=CoinMin(columnUpper[iColumn],value); } } } else if (valid==1) { abort(); } else { std::cout<<"enter value for "<<parameters[iParam].name()<< std::endl; } } break; case REALLY_SCALE: if (goodModels[iModel]) { ClpSimplex newModel(models[iModel], models[iModel].scalingFlag()); printf("model really really scaled\n"); models[iModel]=newModel; } break; case USERCLP: // Replace the sample code by whatever you want if (goodModels[iModel]) { ClpSimplex * thisModel = &models[iModel]; printf("Dummy user code - model has %d rows and %d columns\n", thisModel->numberRows(),thisModel->numberColumns()); } break; case HELP: std::cout<<"Coin LP version "<<CLPVERSION <<", build "<<__DATE__<<std::endl; std::cout<<"Non default values:-"<<std::endl; std::cout<<"Perturbation "<<models[0].perturbation()<<" (default 100)" <<std::endl; CoinReadPrintit( "Presolve being done with 5 passes\n\ Dual steepest edge steep/partial on matrix shape and factorization density\n\ Clpnnnn taken out of messages\n\ If Factorization frequency default then done on size of matrix\n\n\ (-)unitTest, (-)netlib or (-)netlibp will do standard tests\n\n\ You can switch to interactive mode at any time so\n\ clp watson.mps -scaling off -primalsimplex\nis the same as\n\ clp watson.mps -\nscaling off\nprimalsimplex" ); break; case SOLUTION: if (goodModels[iModel]) { // get next field field = CoinReadGetString(argc,argv); if (field=="$") { field = parameters[iParam].stringValue(); } else if (field=="EOL") { parameters[iParam].printString(); break; } else { parameters[iParam].setStringValue(field); } std::string fileName; FILE *fp=NULL; if (field=="-"||field=="EOL"||field=="stdout") { // stdout fp=stdout; fprintf(fp,"\n"); } else if (field=="stderr") { // stderr fp=stderr; fprintf(fp,"\n"); } else { if (field[0]=='/'||field[0]=='\\') { fileName = field; } else if (field[0]=='~') { char * environVar = getenv("HOME"); if (environVar) { std::string home(environVar); field=field.erase(0,1); fileName = home+field; } else { fileName=field; } } else { fileName = directory+field; } fp=fopen(fileName.c_str(),"w"); } if (fp) { // Write solution header (suggested by Luigi Poderico) double objValue = models[iModel].getObjValue()*models[iModel].getObjSense(); int iStat = models[iModel].status(); if (iStat==0) { fprintf(fp, "optimal\n" ); } else if (iStat==1) { // infeasible fprintf(fp, "infeasible\n" ); } else if (iStat==2) { // unbounded fprintf(fp, "unbounded\n" ); } else if (iStat==3) { fprintf(fp, "stopped on iterations or time\n" ); } else if (iStat==4) { fprintf(fp, "stopped on difficulties\n" ); } else if (iStat==5) { fprintf(fp, "stopped on ctrl-c\n" ); } else { fprintf(fp, "status unknown\n" ); } fprintf(fp, "Objective value %15.8g\n", objValue); // make fancy later on int iRow; int numberRows=models[iModel].numberRows(); int lengthName = models[iModel].lengthNames(); // 0 if no names // in general I don't want to pass around massive // amounts of data but seems simpler here std::vector<std::string> rowNames = *(models[iModel].rowNames()); std::vector<std::string> columnNames = *(models[iModel].columnNames()); double * dualRowSolution = models[iModel].dualRowSolution(); double * primalRowSolution = models[iModel].primalRowSolution(); double * rowLower = models[iModel].rowLower(); double * rowUpper = models[iModel].rowUpper(); double primalTolerance = models[iModel].primalTolerance(); char format[6]; sprintf(format,"%%-%ds",CoinMax(lengthName,8)); bool doMask = (printMask!=""&&lengthName); int * maskStarts=NULL; int maxMasks=0; char ** masks =NULL; if (doMask) { int nAst =0; const char * pMask2 = printMask.c_str(); char pMask[100]; int iChar; int lengthMask = strlen(pMask2); assert (lengthMask<100); if (*pMask2=='"') { if (pMask2[lengthMask-1]!='"') { printf("mismatched \" in mask %s\n",pMask2); break; } else { strcpy(pMask,pMask2+1); *strchr(pMask,'"')='\0'; } } else if (*pMask2=='\'') { if (pMask2[lengthMask-1]!='\'') { printf("mismatched ' in mask %s\n",pMask2); break; } else { strcpy(pMask,pMask2+1); *strchr(pMask,'\'')='\0'; } } else { strcpy(pMask,pMask2); } if (lengthMask>lengthName) { printf("mask %s too long - skipping\n",pMask); break; } maxMasks = 1; for (iChar=0;iChar<lengthMask;iChar++) { if (pMask[iChar]=='*') { nAst++; maxMasks *= (lengthName+1); } } int nEntries = 1; maskStarts = new int[lengthName+2]; masks = new char * [maxMasks]; char ** newMasks = new char * [maxMasks]; int i; for (i=0;i<maxMasks;i++) { masks[i] = new char[lengthName+1]; newMasks[i] = new char[lengthName+1]; } strcpy(masks[0],pMask); for (int iAst=0;iAst<nAst;iAst++) { int nOldEntries = nEntries; nEntries=0; for (int iEntry = 0;iEntry<nOldEntries;iEntry++) { char * oldMask = masks[iEntry]; char * ast = strchr(oldMask,'*'); assert (ast); int length = strlen(oldMask)-1; int nBefore = ast-oldMask; int nAfter = length-nBefore; // and add null nAfter++; for (int i=0;i<=lengthName-length;i++) { char * maskOut = newMasks[nEntries]; CoinMemcpyN(oldMask,nBefore,maskOut); for (int k=0;k<i;k++) maskOut[k+nBefore]='?'; CoinMemcpyN(ast+1,nAfter,maskOut+nBefore+i); nEntries++; assert (nEntries<=maxMasks); } } char ** temp = masks; masks = newMasks; newMasks = temp; } // Now extend and sort int * sort = new int[nEntries]; for (i=0;i<nEntries;i++) { char * maskThis = masks[i]; int length = strlen(maskThis); while (maskThis[length-1]==' ') length--; maskThis[length]='\0'; sort[i]=length; } CoinSort_2(sort,sort+nEntries,masks); int lastLength=-1; for (i=0;i<nEntries;i++) { int length = sort[i]; while (length>lastLength) maskStarts[++lastLength] = i; } maskStarts[++lastLength]=nEntries; delete [] sort; for (i=0;i<maxMasks;i++) delete [] newMasks[i]; delete [] newMasks; } if (printMode>2) { for (iRow=0;iRow<numberRows;iRow++) { int type=printMode-3; if (primalRowSolution[iRow]>rowUpper[iRow]+primalTolerance|| primalRowSolution[iRow]<rowLower[iRow]-primalTolerance) { fprintf(fp,"** "); type=2; } else if (fabs(primalRowSolution[iRow])>1.0e-8) { type=1; } else if (numberRows<50) { type=3; } if (doMask&&!maskMatches(maskStarts,masks,rowNames[iRow])) type=0; if (type) { fprintf(fp,"%7d ",iRow); if (lengthName) fprintf(fp,format,rowNames[iRow].c_str()); fprintf(fp,"%15.8g %15.8g\n",primalRowSolution[iRow], dualRowSolution[iRow]); } } } int iColumn; int numberColumns=models[iModel].numberColumns(); double * dualColumnSolution = models[iModel].dualColumnSolution(); double * primalColumnSolution = models[iModel].primalColumnSolution(); double * columnLower = models[iModel].columnLower(); double * columnUpper = models[iModel].columnUpper(); for (iColumn=0;iColumn<numberColumns;iColumn++) { int type=(printMode>3) ? 1 : 0; if (primalColumnSolution[iColumn]>columnUpper[iColumn]+primalTolerance|| primalColumnSolution[iColumn]<columnLower[iColumn]-primalTolerance) { fprintf(fp,"** "); type=2; } else if (fabs(primalColumnSolution[iColumn])>1.0e-8) { type=1; } else if (numberColumns<50) { type=3; } if (doMask&&!maskMatches(maskStarts,masks, columnNames[iColumn])) type =0; if (type) { fprintf(fp,"%7d ",iColumn); if (lengthName) fprintf(fp,format,columnNames[iColumn].c_str()); fprintf(fp,"%15.8g %15.8g\n", primalColumnSolution[iColumn], dualColumnSolution[iColumn]); } } if (fp!=stdout) fclose(fp); if (masks) { delete [] maskStarts; for (int i=0;i<maxMasks;i++) delete [] masks[i]; delete [] masks; } } else { std::cout<<"Unable to open file "<<fileName<<std::endl; } } else { std::cout<<"** Current model not valid"<<std::endl; } break; case SAVESOL: if (goodModels[iModel]) { // get next field field = CoinReadGetString(argc,argv); if (field=="$") { field = parameters[iParam].stringValue(); } else if (field=="EOL") { parameters[iParam].printString(); break; } else { parameters[iParam].setStringValue(field); } std::string fileName; if (field[0]=='/'||field[0]=='\\') { fileName = field; } else if (field[0]=='~') { char * environVar = getenv("HOME"); if (environVar) { std::string home(environVar); field=field.erase(0,1); fileName = home+field; } else { fileName=field; } } else { fileName = directory+field; } saveSolution(models+iModel,fileName); } else { std::cout<<"** Current model not valid"<<std::endl; } break; default: abort(); } } } else if (!numberMatches) { std::cout<<"No match for "<<field<<" - ? for list of commands" <<std::endl; } else if (numberMatches==1) { if (!numberQuery) { std::cout<<"Short match for "<<field<<" - completion: "; std::cout<<parameters[firstMatch].matchName()<<std::endl; } else if (numberQuery) { std::cout<<parameters[firstMatch].matchName()<<" : "; std::cout<<parameters[firstMatch].shortHelp()<<std::endl; if (numberQuery>=2) parameters[firstMatch].printLongHelp(); } } else { if (!numberQuery) std::cout<<"Multiple matches for "<<field<<" - possible completions:" <<std::endl; else std::cout<<"Completions of "<<field<<":"<<std::endl; for ( iParam=0; iParam<numberParameters; iParam++ ) { int match = parameters[iParam].matches(field); if (match&&parameters[iParam].displayThis()) { std::cout<<parameters[iParam].matchName(); if (numberQuery>=2) std::cout<<" : "<<parameters[iParam].shortHelp(); std::cout<<std::endl; } } } } delete [] models; delete [] goodModels; } // By now all memory should be freed #ifdef DMALLOC dmalloc_log_unfreed(); dmalloc_shutdown(); #endif return 0; } static void breakdown(const char * name, int numberLook, const double * region) { double range[] = { -COIN_DBL_MAX, -1.0e15,-1.0e11,-1.0e8,-1.0e5,-1.0e4,-1.0e3,-1.0e2,-1.0e1, -1.0, -1.0e-1,-1.0e-2,-1.0e-3,-1.0e-4,-1.0e-5,-1.0e-8,-1.0e-11,-1.0e-15, 0.0, 1.0e-15,1.0e-11,1.0e-8,1.0e-5,1.0e-4,1.0e-3,1.0e-2,1.0e-1, 1.0, 1.0e1,1.0e2,1.0e3,1.0e4,1.0e5,1.0e8,1.0e11,1.0e15, COIN_DBL_MAX}; int nRanges = static_cast<int> (sizeof(range)/sizeof(double)); int * number = new int[nRanges]; memset(number,0,nRanges*sizeof(int)); int * numberExact = new int[nRanges]; memset(numberExact,0,nRanges*sizeof(int)); int i; for ( i=0;i<numberLook;i++) { double value = region[i]; for (int j=0;j<nRanges;j++) { if (value==range[j]) { numberExact[j]++; break; } else if (value<range[j]) { number[j]++; break; } } } printf("\n%s has %d entries\n",name,numberLook); for (i=0;i<nRanges;i++) { if (number[i]) printf("%d between %g and %g",number[i],range[i-1],range[i]); if (numberExact[i]) { if (number[i]) printf(", "); printf("%d exactly at %g",numberExact[i],range[i]); } if (number[i]+numberExact[i]) printf("\n"); } delete [] number; delete [] numberExact; } void sortOnOther(int * column, const CoinBigIndex * rowStart, int * order, int * other, int nRow, int nInRow, int where) { if (nRow<2||where>=nInRow) return; // do initial sort int kRow; int iRow; for ( kRow=0;kRow<nRow;kRow++) { iRow = order[kRow]; other[kRow]=column[rowStart[iRow]+where]; } CoinSort_2(other,other+nRow,order); int first=0; iRow=order[0]; int firstC=column[rowStart[iRow]+where]; kRow=1; while (kRow<nRow) { int lastC=9999999;; for (;kRow<nRow+1;kRow++) { if (kRow<nRow) { iRow=order[kRow]; lastC=column[rowStart[iRow]+where]; } else { lastC=9999999; } if (lastC>firstC) break; } // sort sortOnOther(column,rowStart,order+first,other,kRow-first, nInRow,where+1); firstC=lastC; first=kRow; } } static void statistics(ClpSimplex * originalModel, ClpSimplex * model) { int numberColumns = originalModel->numberColumns(); const char * integerInformation = originalModel->integerInformation(); const double * columnLower = originalModel->columnLower(); const double * columnUpper = originalModel->columnUpper(); int numberIntegers=0; int numberBinary=0; int iRow,iColumn; if (integerInformation) { for (iColumn=0;iColumn<numberColumns;iColumn++) { if (integerInformation[iColumn]) { if (columnUpper[iColumn]>columnLower[iColumn]) { numberIntegers++; if (columnUpper[iColumn]==0.0&&columnLower[iColumn]==1) numberBinary++; } } } } numberColumns = model->numberColumns(); int numberRows = model->numberRows(); columnLower = model->columnLower(); columnUpper = model->columnUpper(); const double * rowLower = model->rowLower(); const double * rowUpper = model->rowUpper(); const double * objective = model->objective(); CoinPackedMatrix * matrix = model->matrix(); CoinBigIndex numberElements = matrix->getNumElements(); const int * columnLength = matrix->getVectorLengths(); //const CoinBigIndex * columnStart = matrix->getVectorStarts(); const double * elementByColumn = matrix->getElements(); int * number = new int[numberRows+1]; memset(number,0,(numberRows+1)*sizeof(int)); int numberObjSingletons=0; /* cType 0 0/inf, 1 0/up, 2 lo/inf, 3 lo/up, 4 free, 5 fix, 6 -inf/0, 7 -inf/up, 8 0/1 */ int cType[9]; std::string cName[]={"0.0->inf,","0.0->up,","lo->inf,","lo->up,","free,","fixed,","-inf->0.0,", "-inf->up,","0.0->1.0"}; int nObjective=0; memset(cType,0,sizeof(cType)); for (iColumn=0;iColumn<numberColumns;iColumn++) { int length=columnLength[iColumn]; if (length==1&&objective[iColumn]) numberObjSingletons++; number[length]++; if (objective[iColumn]) nObjective++; if (columnLower[iColumn]>-1.0e20) { if (columnLower[iColumn]==0.0) { if (columnUpper[iColumn]>1.0e20) cType[0]++; else if (columnUpper[iColumn]==1.0) cType[8]++; else if (columnUpper[iColumn]==0.0) cType[5]++; else cType[1]++; } else { if (columnUpper[iColumn]>1.0e20) cType[2]++; else if (columnUpper[iColumn]==columnLower[iColumn]) cType[5]++; else cType[3]++; } } else { if (columnUpper[iColumn]>1.0e20) cType[4]++; else if (columnUpper[iColumn]==0.0) cType[6]++; else cType[7]++; } } /* rType 0 E 0, 1 E 1, 2 E -1, 3 E other, 4 G 0, 5 G 1, 6 G other, 7 L 0, 8 L 1, 9 L other, 10 Range 0/1, 11 Range other, 12 free */ int rType[13]; std::string rName[]={"E 0.0,","E 1.0,","E -1.0,","E other,","G 0.0,","G 1.0,","G other,", "L 0.0,","L 1.0,","L other,","Range 0.0->1.0,","Range other,","Free"}; memset(rType,0,sizeof(rType)); for (iRow=0;iRow<numberRows;iRow++) { if (rowLower[iRow]>-1.0e20) { if (rowLower[iRow]==0.0) { if (rowUpper[iRow]>1.0e20) rType[4]++; else if (rowUpper[iRow]==1.0) rType[10]++; else if (rowUpper[iRow]==0.0) rType[0]++; else rType[11]++; } else if (rowLower[iRow]==1.0) { if (rowUpper[iRow]>1.0e20) rType[5]++; else if (rowUpper[iRow]==rowLower[iRow]) rType[1]++; else rType[11]++; } else if (rowLower[iRow]==-1.0) { if (rowUpper[iRow]>1.0e20) rType[6]++; else if (rowUpper[iRow]==rowLower[iRow]) rType[2]++; else rType[11]++; } else { if (rowUpper[iRow]>1.0e20) rType[6]++; else if (rowUpper[iRow]==rowLower[iRow]) rType[3]++; else rType[11]++; } } else { if (rowUpper[iRow]>1.0e20) rType[12]++; else if (rowUpper[iRow]==0.0) rType[7]++; else if (rowUpper[iRow]==1.0) rType[8]++; else rType[9]++; } } // Basic statistics printf("\n\nProblem has %d rows, %d columns (%d with objective) and %d elements\n", numberRows,numberColumns,nObjective,numberElements); if (number[0]+number[1]) { printf("There are "); if (numberObjSingletons) printf("%d singletons with objective ",numberObjSingletons); int numberNoObj = number[1]-numberObjSingletons; if (numberNoObj) printf("%d singletons with no objective ",numberNoObj); if (number[0]) printf("** %d columns have no entries",number[0]); printf("\n"); } printf("Column breakdown:\n"); int k; for (k=0;k<static_cast<int> (sizeof(cType)/sizeof(int));k++) { printf("%d of type %s ",cType[k],cName[k].c_str()); if (((k+1)%3)==0) printf("\n"); } if ((k%3)!=0) printf("\n"); printf("Row breakdown:\n"); for (k=0;k<static_cast<int> (sizeof(rType)/sizeof(int));k++) { printf("%d of type %s ",rType[k],rName[k].c_str()); if (((k+1)%3)==0) printf("\n"); } if ((k%3)!=0) printf("\n"); #define SYM #ifndef SYM if (model->logLevel()<2) return ; #endif int kMax = model->logLevel()>3 ? 1000000 : 10; k=0; for (iRow=1;iRow<=numberRows;iRow++) { if (number[iRow]) { k++; printf("%d columns have %d entries\n",number[iRow],iRow); if (k==kMax) break; } } if (k<numberRows) { int kk=k; k=0; for (iRow=numberRows;iRow>=1;iRow--) { if (number[iRow]) { k++; if (k==kMax) break; } } if (k>kk) { printf("\n .........\n\n"); iRow=k; k=0; for (;iRow<numberRows;iRow++) { if (number[iRow]) { k++; printf("%d columns have %d entries\n",number[iRow],iRow); if (k==kMax) break; } } } } delete [] number; printf("\n\n"); if (model->logLevel()==63 #ifdef SYM ||true #endif ) { // get column copy CoinPackedMatrix columnCopy = *matrix; const int * columnLength = columnCopy.getVectorLengths(); number = new int[numberRows+1]; memset(number,0,(numberRows+1)*sizeof(int)); for (iColumn=0;iColumn<numberColumns;iColumn++) { int length=columnLength[iColumn]; number[length]++; } k=0; for (iRow=1;iRow<=numberRows;iRow++) { if (number[iRow]) { k++; } } int * row = columnCopy.getMutableIndices(); const CoinBigIndex * columnStart = columnCopy.getVectorStarts(); double * element = columnCopy.getMutableElements(); int * order = new int[numberColumns]; int * other = new int[numberColumns]; for (iColumn=0;iColumn<numberColumns;iColumn++) { int length=columnLength[iColumn]; order[iColumn]=iColumn; other[iColumn]=length; CoinBigIndex start = columnStart[iColumn]; CoinSort_2(row+start,row+start+length,element+start); } CoinSort_2(other,other+numberColumns,order); int jColumn=number[0]+number[1]; for (iRow=2;iRow<=numberRows;iRow++) { if (number[iRow]) { printf("XX %d columns have %d entries\n",number[iRow],iRow); int kColumn = jColumn+number[iRow]; sortOnOther(row,columnStart, order+jColumn,other,number[iRow],iRow,0); // Now print etc if (iRow<500000) { for (int lColumn =jColumn;lColumn<kColumn;lColumn++) { iColumn = order[lColumn]; CoinBigIndex start = columnStart[iColumn]; if (model->logLevel()==63) { printf("column %d %g <= ",iColumn,columnLower[iColumn]); for (CoinBigIndex i=start;i<start+iRow;i++) printf("( %d, %g) ",row[i],element[i]); printf("<= %g\n",columnUpper[iColumn]); } } } jColumn =kColumn; } } delete [] order; delete [] other; delete [] number; } // get row copy CoinPackedMatrix rowCopy = *matrix; rowCopy.reverseOrdering(); const int * rowLength = rowCopy.getVectorLengths(); number = new int[numberColumns+1]; memset(number,0,(numberColumns+1)*sizeof(int)); for (iRow=0;iRow<numberRows;iRow++) { int length=rowLength[iRow]; number[length]++; } if (number[0]) printf("** %d rows have no entries\n",number[0]); k=0; for (iColumn=1;iColumn<=numberColumns;iColumn++) { if (number[iColumn]) { k++; printf("%d rows have %d entries\n",number[iColumn],iColumn); if (k==kMax) break; } } if (k<numberColumns) { int kk=k; k=0; for (iColumn=numberColumns;iColumn>=1;iColumn--) { if (number[iColumn]) { k++; if (k==kMax) break; } } if (k>kk) { printf("\n .........\n\n"); iColumn=k; k=0; for (;iColumn<numberColumns;iColumn++) { if (number[iColumn]) { k++; printf("%d rows have %d entries\n",number[iColumn],iColumn); if (k==kMax) break; } } } } if (model->logLevel()==63 #ifdef SYM ||true #endif ) { int * column = rowCopy.getMutableIndices(); const CoinBigIndex * rowStart = rowCopy.getVectorStarts(); double * element = rowCopy.getMutableElements(); int * order = new int[numberRows]; int * other = new int[numberRows]; for (iRow=0;iRow<numberRows;iRow++) { int length=rowLength[iRow]; order[iRow]=iRow; other[iRow]=length; CoinBigIndex start = rowStart[iRow]; CoinSort_2(column+start,column+start+length,element+start); } CoinSort_2(other,other+numberRows,order); int jRow=number[0]+number[1]; double * weight = new double[numberRows]; double * randomColumn = new double[numberColumns+1]; double * randomRow = new double [numberRows+1]; int * sortRow = new int [numberRows]; int * possibleRow = new int [numberRows]; int * backRow = new int [numberRows]; int * stackRow = new int [numberRows]; int * sortColumn = new int [numberColumns]; int * possibleColumn = new int [numberColumns]; int * backColumn = new int [numberColumns]; int * backColumn2 = new int [numberColumns]; int * mapRow = new int [numberRows]; int * mapColumn = new int [numberColumns]; int * stackColumn = new int [numberColumns]; double randomLower = CoinDrand48(); double randomUpper = CoinDrand48(); double randomInteger = CoinDrand48(); int * startAdd = new int[numberRows+1]; int * columnAdd = new int [2*numberElements]; double * elementAdd = new double[2*numberElements]; int nAddRows=0; startAdd[0]=0; for (iColumn=0;iColumn<numberColumns;iColumn++) { randomColumn[iColumn] = CoinDrand48(); backColumn2[iColumn]=-1; } for (iColumn=2;iColumn<=numberColumns;iColumn++) { if (number[iColumn]) { printf("XX %d rows have %d entries\n",number[iColumn],iColumn); int kRow = jRow+number[iColumn]; sortOnOther(column,rowStart, order+jRow,other,number[iColumn],iColumn,0); // Now print etc if (iColumn<500000) { int nLook=0; for (int lRow =jRow;lRow<kRow;lRow++) { iRow = order[lRow]; CoinBigIndex start = rowStart[iRow]; if (model->logLevel()==63) { printf("row %d %g <= ",iRow,rowLower[iRow]); for (CoinBigIndex i=start;i<start+iColumn;i++) printf("( %d, %g) ",column[i],element[i]); printf("<= %g\n",rowUpper[iRow]); } int first = column[start]; double sum=0.0; for (CoinBigIndex i=start;i<start+iColumn;i++) { int jColumn = column[i]; double value = element[i]; jColumn -= first; assert (jColumn>=0); sum += value*randomColumn[jColumn]; } if (rowLower[iRow]>-1.0e30&&rowLower[iRow]) sum += rowLower[iRow]*randomLower; else if (!rowLower[iRow]) sum += 1.234567e-7*randomLower; if (rowUpper[iRow]<1.0e30&&rowUpper[iRow]) sum += rowUpper[iRow]*randomUpper; else if (!rowUpper[iRow]) sum += 1.234567e-7*randomUpper; sortRow[nLook]=iRow; randomRow[nLook++]=sum; // best way is to number unique elements and bounds and use if (fabs(sum)>1.0e4) sum *= 1.0e-6; weight[iRow]=sum; } assert (nLook<=numberRows); CoinSort_2(randomRow,randomRow+nLook,sortRow); randomRow[nLook]=COIN_DBL_MAX; double last=-COIN_DBL_MAX; int iLast=-1; for (int iLook=0;iLook<nLook+1;iLook++) { if (randomRow[iLook]>last) { if (iLast>=0) { int n=iLook-iLast; if (n>1) { //printf("%d rows possible?\n",n); } } iLast=iLook; last=randomRow[iLook]; } } } jRow =kRow; } } CoinPackedMatrix columnCopy = *matrix; const int * columnLength = columnCopy.getVectorLengths(); const int * row = columnCopy.getIndices(); const CoinBigIndex * columnStart = columnCopy.getVectorStarts(); const double * elementByColumn = columnCopy.getElements(); for (iColumn=0;iColumn<numberColumns;iColumn++) { int length=columnLength[iColumn]; CoinBigIndex start = columnStart[iColumn]; double sum = objective[iColumn]; if (columnLower[iColumn]>-1.0e30&&columnLower[iColumn]) sum += columnLower[iColumn]*randomLower; else if (!columnLower[iColumn]) sum += 1.234567e-7*randomLower; if (columnUpper[iColumn]<1.0e30&&columnUpper[iColumn]) sum += columnUpper[iColumn]*randomUpper; else if (!columnUpper[iColumn]) sum += 1.234567e-7*randomUpper; if (model->isInteger(iColumn)) sum += 9.87654321e-6*randomInteger; for (CoinBigIndex i=start;i<start+length;i++) { int iRow = row[i]; sum += elementByColumn[i]*weight[iRow]; } sortColumn[iColumn]=iColumn; randomColumn[iColumn]=sum; } { CoinSort_2(randomColumn,randomColumn+numberColumns,sortColumn); for (iColumn=0;iColumn<numberColumns;iColumn++) { int i=sortColumn[iColumn]; backColumn[i]=iColumn; } randomColumn[numberColumns]=COIN_DBL_MAX; double last=-COIN_DBL_MAX; int iLast=-1; for (int iLook=0;iLook<numberColumns+1;iLook++) { if (randomColumn[iLook]>last) { if (iLast>=0) { int n=iLook-iLast; if (n>1) { //printf("%d columns possible?\n",n); } for (int i=iLast;i<iLook;i++) { possibleColumn[sortColumn[i]]=n; } } iLast=iLook; last=randomColumn[iLook]; } } for (iRow =0;iRow<numberRows;iRow++) { CoinBigIndex start = rowStart[iRow]; double sum=0.0; int length=rowLength[iRow]; for (CoinBigIndex i=start;i<start+length;i++) { int jColumn = column[i]; double value = element[i]; jColumn=backColumn[jColumn]; sum += value*randomColumn[jColumn]; //if (iColumn==23089||iRow==23729) //printf("row %d cola %d colb %d value %g rand %g sum %g\n", // iRow,jColumn,column[i],value,randomColumn[jColumn],sum); } sortRow[iRow]=iRow; randomRow[iRow]=weight[iRow]; randomRow[iRow]=sum; } CoinSort_2(randomRow,randomRow+numberRows,sortRow); for (iRow=0;iRow<numberRows;iRow++) { int i=sortRow[iRow]; backRow[i]=iRow; } randomRow[numberRows]=COIN_DBL_MAX; last=-COIN_DBL_MAX; iLast=-1; // Do backward indices from order for (iRow=0;iRow<numberRows;iRow++) { other[order[iRow]]=iRow; } for (int iLook=0;iLook<numberRows+1;iLook++) { if (randomRow[iLook]>last) { if (iLast>=0) { int n=iLook-iLast; if (n>1) { //printf("%d rows possible?\n",n); // Within group sort as for original "order" for (int i=iLast;i<iLook;i++) { int jRow=sortRow[i]; order[i]=other[jRow]; } CoinSort_2(order+iLast,order+iLook,sortRow+iLast); } for (int i=iLast;i<iLook;i++) { possibleRow[sortRow[i]]=n; } } iLast=iLook; last=randomRow[iLook]; } } // Temp out for (int iLook=0;iLook<numberRows-1000000;iLook++) { iRow=sortRow[iLook]; CoinBigIndex start = rowStart[iRow]; int length=rowLength[iRow]; int numberPossible = possibleRow[iRow]; for (CoinBigIndex i=start;i<start+length;i++) { int jColumn = column[i]; if (possibleColumn[jColumn]!=numberPossible) numberPossible=-1; } int n=numberPossible; if (numberPossible>1) { //printf("pppppossible %d\n",numberPossible); for (int jLook=iLook+1;jLook<iLook+numberPossible;jLook++) { int jRow=sortRow[jLook]; CoinBigIndex start2 = rowStart[jRow]; assert (numberPossible==possibleRow[jRow]); assert(length==rowLength[jRow]); for (CoinBigIndex i=start2;i<start2+length;i++) { int jColumn = column[i]; if (possibleColumn[jColumn]!=numberPossible) numberPossible=-1; } } if (numberPossible<2) { // switch off for (int jLook=iLook;jLook<iLook+n;jLook++) possibleRow[sortRow[jLook]]=-1; } // skip rest iLook += n-1; } else { possibleRow[iRow]=-1; } } for (int iLook=0;iLook<numberRows;iLook++) { iRow=sortRow[iLook]; int numberPossible = possibleRow[iRow]; // Only if any integers int numberIntegers=0; CoinBigIndex start = rowStart[iRow]; int length=rowLength[iRow]; for (CoinBigIndex i=start;i<start+length;i++) { int jColumn = column[i]; if (model->isInteger(jColumn)) numberIntegers++; } if (numberPossible>1&&!numberIntegers) { //printf("possible %d - but no integers\n",numberPossible); } if (numberPossible>1&&(numberIntegers||true)) { // printf("possible %d - %d integers\n",numberPossible,numberIntegers); int lastLook=iLook; int nMapRow=-1; for (int jLook=iLook+1;jLook<iLook+numberPossible;jLook++) { // stop if too many failures if (jLook>iLook+10&&nMapRow<0) break; // Create identity mapping int i; for (i=0;i<numberRows;i++) mapRow[i]=i; for (i=0;i<numberColumns;i++) mapColumn[i]=i; int offset=jLook-iLook; int nStackC=0; // build up row and column mapping int nStackR=1; stackRow[0]=iLook; bool good=true; while (nStackR) { nStackR--; int look1 = stackRow[nStackR]; int look2 = look1 + offset; assert (randomRow[look1]==randomRow[look2]); int row1=sortRow[look1]; int row2=sortRow[look2]; assert (mapRow[row1]==row1); assert (mapRow[row2]==row2); mapRow[row1]=row2; mapRow[row2]=row1; CoinBigIndex start1 = rowStart[row1]; CoinBigIndex offset2 = rowStart[row2]-start1; int length=rowLength[row1]; assert( length==rowLength[row2]); for (CoinBigIndex i=start1;i<start1+length;i++) { int jColumn1 = column[i]; int jColumn2 = column[i+offset2]; if (randomColumn[backColumn[jColumn1]]!= randomColumn[backColumn[jColumn2]]) { good=false; break; } if (mapColumn[jColumn1]==jColumn1) { // not touched assert (mapColumn[jColumn2]==jColumn2); if (jColumn1!=jColumn2) { // Put on stack mapColumn[jColumn1]=jColumn2; mapColumn[jColumn2]=jColumn1; stackColumn[nStackC++]=jColumn1; } } else { if(mapColumn[jColumn1]!=jColumn2|| mapColumn[jColumn2]!=jColumn1) { // bad good=false; printf("bad col\n"); break; } } } if (!good) break; while (nStackC) { nStackC--; int iColumn = stackColumn[nStackC]; int iColumn2 = mapColumn[iColumn]; assert (iColumn!=iColumn2); int length=columnLength[iColumn]; assert (length==columnLength[iColumn2]); CoinBigIndex start = columnStart[iColumn]; CoinBigIndex offset2 = columnStart[iColumn2]-start; for (CoinBigIndex i=start;i<start+length;i++) { int iRow = row[i]; int iRow2 = row[i+offset2]; if (mapRow[iRow]==iRow) { // First (but be careful) if (iRow!=iRow2) { //mapRow[iRow]=iRow2; //mapRow[iRow2]=iRow; int iBack=backRow[iRow]; int iBack2=backRow[iRow2]; if (randomRow[iBack]==randomRow[iBack2]&& iBack2-iBack==offset) { stackRow[nStackR++]=iBack; } else { //printf("randomRow diff - weights %g %g\n", // weight[iRow],weight[iRow2]); // bad good=false; break; } } } else { if(mapRow[iRow]!=iRow2|| mapRow[iRow2]!=iRow) { // bad good=false; printf("bad row\n"); break; } } } if (!good) break; } } // then check OK if (good) { for (iRow =0;iRow<numberRows;iRow++) { CoinBigIndex start = rowStart[iRow]; int length=rowLength[iRow]; if (mapRow[iRow]==iRow) { for (CoinBigIndex i=start;i<start+length;i++) { int jColumn = column[i]; backColumn2[jColumn]=i-start; } for (CoinBigIndex i=start;i<start+length;i++) { int jColumn = column[i]; if (mapColumn[jColumn]!=jColumn) { int jColumn2 =mapColumn[jColumn]; CoinBigIndex i2 = backColumn2[jColumn2]; if (i2<0) { good=false; } else if (element[i]!=element[i2+start]) { good=false; } } } for (CoinBigIndex i=start;i<start+length;i++) { int jColumn = column[i]; backColumn2[jColumn]=-1; } } else { int row2 = mapRow[iRow]; assert (iRow = mapRow[row2]); if (rowLower[iRow]!=rowLower[row2]|| rowLower[row2]!=rowLower[iRow]) good=false; CoinBigIndex offset2 = rowStart[row2]-start; for (CoinBigIndex i=start;i<start+length;i++) { int jColumn = column[i]; double value = element[i]; int jColumn2 = column[i+offset2]; double value2 = element[i+offset2]; if (value!=value2||mapColumn[jColumn]!=jColumn2|| mapColumn[jColumn2]!=jColumn) good=false; } } } if (good) { // check rim for (iColumn=0;iColumn<numberColumns;iColumn++) { if (mapColumn[iColumn]!=iColumn) { int iColumn2 = mapColumn[iColumn]; if(objective[iColumn]!=objective[iColumn2]) good=false; if (columnLower[iColumn]!=columnLower[iColumn2]) good=false; if (columnUpper[iColumn]!=columnUpper[iColumn2]) good=false; if (model->isInteger(iColumn)!=model->isInteger(iColumn2)) good=false; } } } if (good) { // temp if (nMapRow<0) { //const double * solution = model->primalColumnSolution(); // find mapped int nMapColumn=0; for (int i=0;i<numberColumns;i++) { if (mapColumn[i]>i) nMapColumn++; } nMapRow=0; int kRow=-1; for (int i=0;i<numberRows;i++) { if (mapRow[i]>i) { nMapRow++; kRow=i; } } printf("%d columns, %d rows\n",nMapColumn,nMapRow); if (nMapRow==1) { CoinBigIndex start = rowStart[kRow]; int length=rowLength[kRow]; printf("%g <= ",rowLower[kRow]); for (CoinBigIndex i=start;i<start+length;i++) { int jColumn = column[i]; if (mapColumn[jColumn]!=jColumn) printf("* "); printf("%d,%g ",jColumn,element[i]); } printf("<= %g\n",rowUpper[kRow]); } } // temp int row1=sortRow[lastLook]; int row2=sortRow[jLook]; lastLook=jLook; CoinBigIndex start1 = rowStart[row1]; CoinBigIndex offset2 = rowStart[row2]-start1; int length=rowLength[row1]; assert( length==rowLength[row2]); CoinBigIndex put=startAdd[nAddRows]; double multiplier=length<11 ? 2.0 : 1.125; double value=1.0; for (CoinBigIndex i=start1;i<start1+length;i++) { int jColumn1 = column[i]; int jColumn2 = column[i+offset2]; columnAdd[put]=jColumn1; elementAdd[put++]=value; columnAdd[put]=jColumn2; elementAdd[put++]=-value; value *= multiplier; } nAddRows++; startAdd[nAddRows]=put; } else { printf("ouch - did not check out as good\n"); } } } // skip rest iLook += numberPossible-1; } } } if (nAddRows) { double * lower = new double [nAddRows]; double * upper = new double[nAddRows]; int i; //const double * solution = model->primalColumnSolution(); for (i=0;i<nAddRows;i++) { lower[i]=0.0; upper[i]=COIN_DBL_MAX; } printf("Adding %d rows with %d elements\n",nAddRows, startAdd[nAddRows]); //ClpSimplex newModel(*model); //newModel.addRows(nAddRows,lower,upper,startAdd,columnAdd,elementAdd); //newModel.writeMps("modified.mps"); delete [] lower; delete [] upper; } delete [] startAdd; delete [] columnAdd; delete [] elementAdd; delete [] order; delete [] other; delete [] randomColumn; delete [] weight; delete [] randomRow; delete [] sortRow; delete [] backRow; delete [] possibleRow; delete [] sortColumn; delete [] backColumn; delete [] backColumn2; delete [] possibleColumn; delete [] mapRow; delete [] mapColumn; delete [] stackRow; delete [] stackColumn; } delete [] number; // Now do breakdown of ranges breakdown("Elements",numberElements,elementByColumn); breakdown("RowLower",numberRows,rowLower); breakdown("RowUpper",numberRows,rowUpper); breakdown("ColumnLower",numberColumns,columnLower); breakdown("ColumnUpper",numberColumns,columnUpper); breakdown("Objective",numberColumns,objective); } static bool maskMatches(const int * starts, char ** masks, std::string & check) { // back to char as I am old fashioned const char * checkC = check.c_str(); int length = strlen(checkC); while (checkC[length-1]==' ') length--; for (int i=starts[length];i<starts[length+1];i++) { char * thisMask = masks[i]; int k; for ( k=0;k<length;k++) { if (thisMask[k]!='?'&&thisMask[k]!=checkC[k]) break; } if (k==length) return true; } return false; } static void clean(char * temp) { char * put = temp; while (*put>=' ') put++; *put='\0'; } static void generateCode(const char * fileName,int type) { FILE * fp = fopen(fileName,"r"); assert (fp); int numberLines=0; #define MAXLINES 500 #define MAXONELINE 200 char line[MAXLINES][MAXONELINE]; while (fgets(line[numberLines],MAXONELINE,fp)) { assert (numberLines<MAXLINES); clean(line[numberLines]); numberLines++; } fclose(fp); // add in actual solve strcpy(line[numberLines],"5 clpModel->initialSolve(clpSolve);"); numberLines++; fp = fopen(fileName,"w"); assert (fp); char apo='"'; char backslash = '\\'; fprintf(fp,"#include %cClpSimplex.hpp%c\n",apo,apo); fprintf(fp,"#include %cClpSolve.hpp%c\n",apo,apo); fprintf(fp,"\nint main (int argc, const char *argv[])\n{\n"); fprintf(fp," ClpSimplex model;\n"); fprintf(fp," int status=1;\n"); fprintf(fp," if (argc<2)\n"); fprintf(fp," fprintf(stderr,%cPlease give file name%cn%c);\n", apo,backslash,apo); fprintf(fp," else\n"); fprintf(fp," status=model.readMps(argv[1],true);\n"); fprintf(fp," if (status) {\n"); fprintf(fp," fprintf(stderr,%cBad readMps %%s%cn%c,argv[1]);\n", apo,backslash,apo); fprintf(fp," exit(1);\n"); fprintf(fp," }\n\n"); fprintf(fp," // Now do requested saves and modifications\n"); fprintf(fp," ClpSimplex * clpModel = & model;\n"); int wanted[9]; memset(wanted,0,sizeof(wanted)); wanted[0]=wanted[3]=wanted[5]=wanted[8]=1; if (type>0) wanted[1]=wanted[6]=1; if (type>1) wanted[2]=wanted[4]=wanted[7]=1; std::string header[9]= { "","Save values","Redundant save of default values","Set changed values", "Redundant set default values","Solve","Restore values","Redundant restore values","Add to model"}; for (int iType=0;iType<9;iType++) { if (!wanted[iType]) continue; int n=0; int iLine; for (iLine=0;iLine<numberLines;iLine++) { if (line[iLine][0]=='0'+iType) { if (!n) fprintf(fp,"\n // %s\n\n",header[iType].c_str()); n++; fprintf(fp,"%s\n",line[iLine]+1); } } } fprintf(fp,"\n // Now you would use solution etc etc\n\n"); fprintf(fp," return 0;\n}\n"); fclose(fp); printf("C++ file written to %s\n",fileName); } /* Version 1.00.00 October 13 2004. 1.00.01 October 18. Added basis handling helped/prodded by Thorsten Koch. Also modifications to make faster with sbb (I hope I haven't broken anything). 1.00.02 March 21 2005. Redid ClpNonLinearCost to save memory also redid createRim to try and improve cache characteristics. 1.00.03 April 8 2005. Added Volume algorithm as crash and made code more robust on testing. Also added "either" and "tune" algorithm. 1.01.01 April 12 2005. Decided to go to different numbering. Backups will be last 2 digits while middle 2 are for improvements. Still take a long time to get to 2.00.01 1.01.02 May 4 2005. Will be putting in many changes - so saving stable version 1.02.01 May 6 2005. Lots of changes to try and make faster and more stable in branch and cut. 1.02.02 May 19 2005. Stuff for strong branching and some improvements to simplex 1.03.01 May 24 2006. Lots done but I can't remember what! 1.03.03 June 13 2006. For clean up after dual perturbation 1.04.01 June 26 2007. Lots of changes but I got lazy 1.05.00 June 27 2007. This is trunk so when gets to stable will be 1.5 */
[ "YanivFais@users.noreply.github.com" ]
YanivFais@users.noreply.github.com
461353ba564dc624171c7bffaff524ef5834e14c
33392bbfbc4abd42b0c67843c7c6ba9e0692f845
/blas/L2/include/streamingKernel/hw/xf_blas/gemmKernel.hpp
6e9bb67c5b74eea5ad62b6b265b88b0a2fa5ead0
[ "Apache-2.0", "BSD-2-Clause", "OFL-1.1", "MIT", "BSD-3-Clause" ]
permissive
Xilinx/Vitis_Libraries
bad9474bf099ed288418430f695572418c87bc29
2e6c66f83ee6ad21a7c4f20d6456754c8e522995
refs/heads/main
2023-07-20T09:01:16.129113
2023-06-08T08:18:19
2023-06-08T08:18:19
210,433,135
785
371
Apache-2.0
2023-07-06T21:35:46
2019-09-23T19:13:46
C++
UTF-8
C++
false
false
12,294
hpp
/********** * Copyright 2019 Xilinx, Inc. * * 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. * **********/ /** * @brief GEMM header * */ #ifndef XF_BLAS_GEMM_KERNEL_HPP #define XF_BLAS_GEMM_KERNEL_HPP #include <cassert> #include <iostream> #include "xf_blas.hpp" #include "types.hpp" #include "transpose.hpp" #include "matrixBuffer.hpp" #include "gemm.hpp" namespace xf { namespace blas { // implement C = A*B+X // Gemm class. t_KparWords defines number of memwords in the columns of one row of buffer_A. Due to the reusability, // the height of buffer_A is only one memwords. For buffer_B, t_KparWords defines number of memwords in the rows of // one column in buffer_B, t_NparWords defines number of memwords in the cols of one row in buffer_B. t_MparWords // and t_NparWords define the height and width of buffer_C in terms of memwords. template <typename t_FloatType, // matrix A, B entry data type typename t_XDataType, // matrix X entry data type unsigned int t_DdrWidth, // number of matrix elements in one memory word unsigned int t_XDdrWidth, unsigned int t_KparWords = 1, // number of memory words in one row of the matrix A buffer unsigned int t_MparWords = 1, // number of memory words in one column of the matrix A buffer unsigned int t_NparWords = 1 // number of memory words in one row of the matrix B buffer > class GemmKernel { public: static const unsigned int t_aMH = t_DdrWidth * t_MparWords; static const unsigned int t_bKD = t_DdrWidth * t_KparWords; static const unsigned int t_DdrOverXDdr = t_DdrWidth / t_XDdrWidth; static const unsigned int t_xColMemWords = t_NparWords * t_DdrOverXDdr; typedef WideType<t_FloatType, t_DdrWidth> DdrWideType; typedef typename DdrWideType::t_TypeInt DdrIntType; typedef hls::stream<DdrIntType> DdrStream; typedef TaggedWideType<t_FloatType, t_DdrWidth> TaggedWideFloat; typedef hls::stream<typename TaggedWideType<t_FloatType, t_DdrWidth>::t_TypeInt> EdgeStream; typedef WideType<t_XDataType, t_XDdrWidth> XDdrWideType; typedef hls::stream<typename WideType<t_XDataType, t_XDdrWidth>::t_TypeInt> XDdrStream; typedef WideType<t_XDataType, t_DdrWidth> DdrWideTypeForX; // type definitions for enhanced MAC implementation, using 48-bits to store accumulation results. typedef t_FloatType MacBitType; typedef DdrWideType WideMacBitType; typedef DdrStream WideMacBitStream; private: static const unsigned int t_debug = 0; public: /////////////////////////////////////////////////////////////////////////// // GEMM C Buffering // /////////////////////////////////////////////////////////////////////////// void GemmCBuffer(WideMacBitStream& p_Cs, unsigned int p_aColBlocks, unsigned int p_cBlocks, WideMacBitStream& p_Cout) { WideMacBitType l_bufferC[t_aMH * t_NparWords]; for (int i = 0; i < t_aMH * t_NparWords; i++) #pragma HLS PIPELINE for (int j = 0; j < t_DdrWidth; j++) l_bufferC[i][j] = 0; for (int l_block = 0; l_block < p_cBlocks; ++l_block) { for (int m = 0; m < p_aColBlocks; ++m) { for (int i = 0; i < t_MparWords; ++i) { for (int j = 0; j < t_NparWords; ++j) { for (int l = 0; l < t_DdrWidth; ++l) { #pragma HLS DEPENDENCE variable = l_bufferC array inter RAW false #pragma HLS PIPELINE unsigned int l_arrIdx = (l + i * t_DdrWidth) * t_NparWords + j; WideMacBitType l_val = p_Cs.read(); for (int k = 0; k < t_DdrWidth; ++k) { l_bufferC[l_arrIdx][k] += l_val[k]; } } } } } for (int i = 0; i < t_NparWords * t_MparWords * t_DdrWidth; ++i) { #pragma HLS PIPELINE WideMacBitType l_val = l_bufferC[i]; p_Cout.write(l_val); for (int k = 0; k < t_DdrWidth; k++) l_bufferC[i][k] = 0; } } } /////////////////////////////////////////////////////////////////////////// // GEMM Add X // /////////////////////////////////////////////////////////////////////////// void GemmAddX( WideMacBitStream& p_Cs, XDdrStream& p_Xs, unsigned int p_cBlocks, int32_t p_postScale, DdrStream& p_Cout) { #if BLAS_XVEC DdrWideTypeForX l_bufferX[t_NparWords]; #else DdrWideTypeForX l_bufferX[t_aMH * t_NparWords]; #endif ap_uint<32> l_postScale = p_postScale; ap_uint<16> l_postScaleVal = l_postScale.range(23, 8); ap_uint<8> l_postScaleShift = l_postScale.range(7, 0); for (int l_block = 0; l_block < p_cBlocks; ++l_block) { // read #if BLAS_XVEC for (int xc = 0; xc < t_NparWords; ++xc) { DdrWideTypeForX l_wideWordX; for (int xw = 0; xw < t_DdrOverXDdr; ++xw) { // #pragma HLS PIPELINE XDdrWideType l_wordX = p_Xs.read(); for (int xi = 0; xi < t_XDdrWidth; ++xi) { l_wideWordX[xw * t_XDdrWidth + xi] = l_wordX[xi]; } } l_bufferX[xc] = l_wideWordX; } #else for (int xr = 0; xr < t_aMH; ++xr) { for (int xc = 0; xc < t_NparWords; ++xc) { DdrWideTypeForX l_wideWordX; for (int xw = 0; xw < t_DdrOverXDdr; ++xw) { #pragma HLS PIPELINE XDdrWideType l_wordX = p_Xs.read(); for (int xi = 0; xi < t_XDdrWidth; ++xi) { l_wideWordX[xw * t_XDdrWidth + xi] = l_wordX[xi]; } } l_bufferX[xr * t_NparWords + xc] = l_wideWordX; } } #endif for (int i = 0; i < t_MparWords * t_DdrWidth; ++i) { for (int j = 0; j < t_NparWords; ++j) { WideMacBitType l_val = p_Cs.read(); #if BLAS_XVEC DdrWideTypeForX l_xVal = l_bufferX[j]; #else DdrWideTypeForX l_xVal = l_bufferX[i * t_NparWords + j]; #endif DdrWideType l_cWord; #pragma HLS PIPELINE for (int w = 0; w < t_DdrWidth; ++w) { t_FloatType l_cEntry; l_cEntry = l_val[w] + l_xVal[w]; l_cWord[w] = l_cEntry; } p_Cout.write(l_cWord); } } } } void GemmBuffers( DdrStream& p_As, DdrStream& p_Bs, XDdrStream& p_Xs, DdrStream& p_Cs, typename SystolicArray<t_FloatType, t_bKD, t_DdrWidth, t_DdrWidth, t_FloatType>::TaggedWideStreamM& p_tagA, DdrStream& p_tagB, WideMacBitStream& p_CEdgeS, unsigned int p_aColBlocks, unsigned int p_aRowBlocks, unsigned int p_bColBlocks, unsigned int p_transpBlocks, int32_t p_postScale) { unsigned int l_cBlocks = p_aRowBlocks * p_bColBlocks; unsigned int l_abBlocks = l_cBlocks * p_aColBlocks; #pragma HLS DATAFLOW DdrStream p_Bs1, p_AoutS; WideMacBitStream p_COutS; Transpose<t_FloatType, t_KparWords, t_DdrWidth> l_transp(p_transpBlocks, t_NparWords); l_transp.process(p_As, p_AoutS); MatrixBuffer<typename DdrWideType::t_TypeInt, t_DdrWidth * t_KparWords, t_NparWords, true, false>().process( p_Bs, p_Bs1, l_abBlocks, t_MparWords); SystolicArray<t_FloatType, t_bKD, t_DdrWidth, t_DdrWidth, t_FloatType> l_sysArr(l_abBlocks * t_MparWords * t_NparWords); l_sysArr.tagAB(p_AoutS, p_Bs1, p_tagA, p_tagB); GemmCBuffer(p_CEdgeS, p_aColBlocks, l_cBlocks, p_COutS); GemmAddX(p_COutS, p_Xs, l_cBlocks, p_postScale, p_Cs); } void GemmTags(DdrStream& p_As, DdrStream& p_Bs, typename SystolicArray<t_FloatType, t_bKD, t_DdrWidth, t_DdrWidth, t_FloatType>::EdgeStreamM& p_aOut, hls::stream<ap_uint<2> >& p_tagOut, typename SystolicArray<t_FloatType, t_bKD, t_DdrWidth, t_DdrWidth, t_FloatType>::EdgeStreamN& p_tagB, unsigned int p_aColBlocks, unsigned int p_aRowBlocks, unsigned int p_bColBlocks, unsigned int p_transpBlocks, int32_t p_postScale) { unsigned int l_cBlocks = p_aRowBlocks * p_bColBlocks; unsigned int l_abBlocks = l_cBlocks * p_aColBlocks; #pragma HLS DATAFLOW DdrStream p_Bs1, p_AoutS; WideMacBitStream p_COutS; Transpose<t_FloatType, t_KparWords, t_DdrWidth> l_transp(p_transpBlocks, t_NparWords); l_transp.process(p_As, p_AoutS); MatrixBuffer<typename DdrWideType::t_TypeInt, t_DdrWidth * t_KparWords, t_NparWords, true, false>().process( p_Bs, p_Bs1, l_abBlocks, t_MparWords); SystolicArray<t_FloatType, t_bKD, t_DdrWidth, t_DdrWidth, t_FloatType> l_sysArr(l_abBlocks * t_MparWords * t_NparWords); l_sysArr.tagAB(p_AoutS, p_Bs1, p_aOut, p_tagOut, p_tagB); } void GemmCPlusX(WideMacBitStream& p_CEdgeS, DdrStream& p_Xs, DdrStream& p_Cs, unsigned int p_aColBlocks, unsigned int p_aRowBlocks, unsigned int p_bColBlocks, int32_t p_postScale) { unsigned int l_cBlocks = p_aRowBlocks * p_bColBlocks; unsigned int l_abBlocks = l_cBlocks * p_aColBlocks; #pragma HLS DATAFLOW WideMacBitStream p_COutS; GemmCBuffer(p_CEdgeS, p_aColBlocks, l_cBlocks, p_COutS); GemmAddX(p_COutS, p_Xs, l_cBlocks, p_postScale, p_Cs); } void GemmBlockStream(DdrStream& p_As, DdrStream& p_Bs, XDdrStream& p_Xs, DdrStream& p_Cs, unsigned int p_aColBlocks, unsigned int p_aRowBlocks, unsigned int p_bColBlocks, unsigned int p_transpBlocks, int32_t p_postScale) { unsigned int l_cBlocks = p_aRowBlocks * p_bColBlocks; unsigned int l_abBlocks = l_cBlocks * p_aColBlocks; #pragma HLS DATAFLOW DdrStream p_Bs1, p_AoutS, p_CBufferS; EdgeStream p_AEdgeS0, p_BEdgeS0; WideMacBitStream p_CEdgeS, p_COutS; #pragma HLS STREAM variable = p_CEdgeS depth = t_DdrWidth * t_MparWords * t_NparWords #pragma HLS RESOURCE variable = p_CEdgeS core = fifo_uram /* Transp<t_FloatType, t_DdrWidth, t_KparWords, 1> l_transp; l_transp.processWithReuse(p_As, p_AoutS, p_transpBlocks, t_NparWords); */ Transpose<t_FloatType, t_KparWords, t_DdrWidth> l_transp(p_transpBlocks, t_NparWords); l_transp.process(p_As, p_AoutS); MatrixBuffer<typename DdrWideType::t_TypeInt, t_DdrWidth * t_KparWords, t_NparWords, true, false>().process( p_Bs, p_Bs1, l_abBlocks, t_MparWords); Gemm<t_FloatType, t_bKD, t_DdrWidth>::gemm(p_AoutS, p_Bs1, p_CEdgeS, l_abBlocks * t_MparWords * t_NparWords); GemmCBuffer(p_CEdgeS, p_aColBlocks, l_cBlocks, p_COutS); GemmAddX(p_COutS, p_Xs, l_cBlocks, p_postScale, p_Cs); } }; } } // namespace #endif
[ "sdausr@xilinx.com" ]
sdausr@xilinx.com
c704f31c677d7ac1a20d993669978b5fd96169e2
b496e8cdea3b34448155c636ace8ee5412e5f394
/Date.cpp
8ed7ca71e52533181a5ebbcea722adfe9b7fd4d7
[]
no_license
Shravan40/CppDateParser
881b1ec798a288d30b3a1041faa7cdacc8fed48a
98e2ca89755c80733e1e5c6cda1a971d74f8ffcc
refs/heads/master
2020-07-20T18:50:31.340337
2016-08-18T07:59:16
2016-08-18T07:59:16
65,976,840
0
0
null
null
null
null
WINDOWS-1258
C++
false
false
27,115
cpp
#include <iostream> #include <exception> #include <string.h> #include <stdlib.h> #include <cstdlib> #include <stdio.h> #include <time.h> #include <stdexcept> #include <string> #include <algorithm> #include <iomanip> #include "Date.h" #include<sstream> using namespace std; //UTILITY functions //own to_string general function template <typename T> std::string to_string(T value) { //create an output string stream std::ostringstream os ; //throw the value into the string stream os << value ; //convert the string stream into a string and return return os.str() ; } //own string duplication function with dynamic memory location char* mystrdup(const char* s) { char *p; if(s==0) { p=NULL; } else { p = new char[strlen(s)+1]; strcpy(p, s); } return p; } //using rata die system to calculate difference between dates int rdn(Date date) { /* Rata Die day one is 0001-01-01 */ int d=static_cast<int>(date.getDay()); int m=static_cast<int>(date.getMonth()); int y=(date.getYear()); if (m < 3) y--, m += 12; return 365*y + y/4 - y/100 + y/400 + (153*m - 457)/5 + d - 306; } //using inbuilt C++ libraries to add days void DatePlusDays( struct tm* date, int days ) { const time_t ONE_DAY = 24 * 60 * 60 ; time_t date_seconds = mktime( date ) + (days * ONE_DAY) ; *date = *localtime( &date_seconds ) ; ; } //function that returns number of days in a month, given the month and its year int numDays(int m, int y) { switch(m) { case 1: return 31; break; case 2: //Special case of february if(y/100==0) return 28+(y%4==0&&y!=0); else return 28+(y%4==0&&y%100!=0); break; case 3: return 31; break; case 4: return 30; break; case 5: return 31; break; case 6: return 30; break; case 7: return 31; break; case 8: return 31; break; case 9: return 30; break; case 10: return 31; break; case 11: return 30; break; case 12: return 31; break; default: throw invalid_argument("Unknown exception."); } } DateFormat::DateFormat(const char* dateFormat, const char* monthFormat, const char* yearFormat) { //using mystrdup to duplicate strings if(dateFormat==0||strcmp(dateFormat,"d")==0||strcmp(dateFormat,"dd")==0) this->dateFormat=mystrdup(dateFormat); else throw invalid_argument("Wrong date format."); if(monthFormat==0||strcmp(monthFormat,"m")==0||strcmp(monthFormat,"mm")==0||strcmp(monthFormat,"mmm")==0) this->monthFormat=mystrdup(monthFormat); else throw invalid_argument("Wrong month format."); if(yearFormat==0||strcmp(yearFormat,"yy")==0||strcmp(yearFormat,"yyyy")==0) this->yearFormat=mystrdup(yearFormat); else throw invalid_argument("Wrong year format."); } DateFormat::DateFormat(const char* format) { //Parsing the input string, and using '-' to find different parts of input string int i=0; while(format[i]!='-'&&format[i]) i++; if(format[i]=='\0') throw invalid_argument("Wrong date format."); dateFormat=new char[i+1]; copy(format,format+i,dateFormat); if(i==0) dateFormat=NULL; else dateFormat[i]='\0'; int j=i+1; while(format[j]!='-'&&format[j]) j++; if(format[j]=='\0') throw invalid_argument("Wrong date format."); monthFormat=new char[j-i+1]; copy(format+i+1,format+j,monthFormat); if(j-i-1==0) monthFormat=NULL; else monthFormat[j-i-1]='\0'; i=j+1; if(format[i]) { while(format[i]) i++; yearFormat=new char[i-j+1]; copy(format+j+1,format+i+1,yearFormat); } else yearFormat=NULL; if(dateFormat!=0&&strcmp(dateFormat,"dd")&&strcmp(dateFormat,"d")) throw invalid_argument("Wrong date format."); if(monthFormat!=0&&strcmp(monthFormat,"m")&&strcmp(monthFormat,"mm")&&strcmp(monthFormat,"mmm")) throw invalid_argument("Wrong month format."); if(yearFormat!=0&&strcmp(yearFormat,"yy")&&strcmp(yearFormat,"yyyy")) throw invalid_argument("Wrong year format."); } DateFormat::DateFormat(DateFormat& d) { dateFormat=mystrdup(d.dateFormat); monthFormat=mystrdup(d.monthFormat); yearFormat=mystrdup(d.yearFormat); } DateFormat::DateFormat() { dateFormat=mystrdup("dd"); monthFormat=mystrdup("mmm"); yearFormat=mystrdup("yy"); } DateFormat::~DateFormat() { delete[] dateFormat; delete[] monthFormat; delete[] yearFormat; } //Getter functions const char* DateFormat::getDateFormat() { return dateFormat; } const char* DateFormat::getMonthFormat() { return monthFormat; } const char* DateFormat::getYearFormat() { return yearFormat; } //Date Class Methods Date::Date(Day d, Month m, Year y) // Construct a Date from (d, m, y) throw(invalid_argument, // One or more of the arguments d or m is/are invalid (27, 13, 13) domain_error, // (d, m, y) as a triplet does not define a valid date (30, 2, 61) out_of_range) // Date is out of range (4, 7, 2053) { if(d>numDays(m,y)||d<1) throw domain_error("Incorrect date."); if(d==29 && m==2 && (y%4!=0||y%100==0)) throw domain_error("Incorrect date."); this->day=d; month=m; if((y/100)!=0) { if(y>2049||y<1950) throw out_of_range("Date out of range..."); year=y; } else { year=(y>=50?1900+y:2000+y); } } Date::Date(const char* date) // date in string format -- to be parsed as static format member throw(invalid_argument, domain_error, out_of_range) // "13-03-77" for "dd-mm-yy" // "2-7-2018" for "d-m-yyyy" { char *tempdate=mystrdup(date); for(int i=0;tempdate[i];i++) if(tempdate[i]=='-') tempdate[i]=' '; char *inpdate,*inpmonth,*inpyear; inpdate=new char(10); inpmonth=new char(10); inpyear=new char(10); if(sscanf(tempdate,"%s %s %s",inpdate,inpmonth,inpyear)!=3) throw invalid_argument("Wrong date format."); const char *d=mystrdup(Date::format.getDateFormat()); const char *m=mystrdup(Date::format.getMonthFormat()); const char *y=mystrdup(Date::format.getYearFormat()); if(strcmp(inpmonth,"Jan")==0 or strcmp(inpmonth,"Feb")==0 or strcmp(inpmonth,"Mar")==0 or strcmp(inpmonth,"Apr")==0 or strcmp(inpmonth,"May")==0 or strcmp(inpmonth,"Jun")==0 or strcmp(inpmonth,"Jul")==0 or strcmp(inpmonth,"Aug")==0 or strcmp(inpmonth,"Sep")==0 or strcmp(inpmonth,"Oct")==0 or strcmp(inpmonth,"Nov")==0 or strcmp(inpmonth,"Dec")==0 ) throw invalid_argument("This date format is valid only for output."); for(unsigned int i=0;i<strlen(inpdate);i++) if(!isdigit(inpdate[i])) throw invalid_argument("Not a date, has non-digits."); for(unsigned int i=0;i<strlen(inpmonth);i++) if(!isdigit(inpmonth[i])) throw invalid_argument("Not a month, has non-digits."); for(unsigned int i=0;i<strlen(inpyear);i++) if(!isdigit(inpyear[i])) throw invalid_argument("Not a year, has non-digits."); if(strcmp(d,"d")==0) { if(inpdate[0]=='0') throw invalid_argument("Date not in correct format."); } if(strcmp(d,"dd")==0) { if(strlen(inpdate)!=2) throw invalid_argument("Date not in correct format."); } if(strcmp(m,"m")==0) { if(inpmonth[0]=='0') throw invalid_argument("Month not in correct format."); } if(strcmp(m,"mm")==0) { if(strlen(inpmonth)!=2) throw invalid_argument("Month not in correct format."); } if(strcmp(y,"yy")==0) if(strlen(inpyear)!=2) throw invalid_argument("Year not in correct format."); if(strcmp(y,"yyyy")==0) if(strlen(inpyear)!=4) throw invalid_argument("Year not in correct format."); day=static_cast<Day>(atoi(inpdate)); month=static_cast<Month>(atoi(inpmonth)); year=atoi(inpyear); if(day<1 || day>numDays(month,year)) throw domain_error("Incorrect date."); if(strcmp(y,"yyyy")==0) { if(year>2049||year<1950) { throw out_of_range("Date out of range..."); } } else { year=(year>=50?1900+year:2000+year); } delete[] inpdate; delete[] inpmonth; delete[] inpyear; delete[] tempdate; delete[] d; delete[] m; delete[] y; } Date::Date() // Default Constructor - construct ’today’ (get from system) throw(domain_error, out_of_range) { //using inbuilt time functions to get current time //using strfttime() to get date,month and year out of tstruct char *buf; time_t now = time(0); struct tm tstruct; tstruct = *localtime(&now); buf=new char[3]; strftime(buf,3,"%d",&tstruct); day=static_cast<Day>(atoi(buf)); delete[] buf; buf=new char[3]; strftime(buf,3,"%m",&tstruct); month=static_cast<Month>(atoi(buf)); delete[] buf; buf=new char[5]; strftime(buf,5,"%Y",&tstruct); year=atoi(buf); if(year>2049||year<1950) throw out_of_range("Date out of range..."); delete[] buf; } //Copy Constructor Date::Date(const Date& obj) // Copy Constructor { day=obj.getDay(); month=obj.getMonth(); year=obj.getYear(); } // DESTRUCTOR Date::~Date(){} // No virtual destructor needed // BASIC ASSIGNMENT OPERATOR Date& Date::operator=(const Date& d) { this->day=d.day; this->month=d.month; this->year=d.year; return *this; } // UNARY ARITHMETIC OPERATORS //Prefix increment Date& Date::operator++() // Next day { //increment date by one considering different cases where month or year increment may be required if(day<numDays(month,year)) day=static_cast<Day>(static_cast<int>(day)+1); else { if(month<12) { month=static_cast<Month>(static_cast<int>(month)+1); day=D01; } else { month=Jan; day=D01; year++; if(year==2050) throw out_of_range("Next date out of range."); } } return *this; } //Postfix increment Date& Date::operator++(int) // Same day next week { //increment date by seven considering different cases where month or year increment may be required if(day<=numDays(month,year)-7) day=static_cast<Day>(static_cast<int>(day)+7); else { if(month<12) { day=static_cast<Day>((static_cast<int>(day)+7)%numDays(month,year)); month=static_cast<Month>(static_cast<int>(month)+1); } else { day=static_cast<Day>((static_cast<int>(day)+7)%numDays(month,year)); month=Jan; year++; if(year==2050) throw out_of_range("Next date out of range."); } } return *this; } Date& Date::operator--() // Previous day { //decrement date by one considering different cases where month or year decrement may be required if(day>1) day=static_cast<Day>(static_cast<int>(day)-1); else { if(month>1) { month=static_cast<Month>(static_cast<int>(month)-1); day=static_cast<Day>(numDays(month,year)); } else { month=Dec; day=static_cast<Day>(numDays(month,year)); year--; if(year==1949) throw out_of_range("Previous date out of range."); } } return *this; } Date& Date::operator--(int) // Same day previous week { //decrement date by seven considering different cases where month or year decrement may be required if(day>7) day=static_cast<Day>(static_cast<int>(day)-7); else { if(month>1) { month=static_cast<Month>(static_cast<int>(month)-1); day=static_cast<Day>(numDays(month,year)+static_cast<int>(day)-7); } else { month=Dec; day=static_cast<Day>(numDays(month,year)+static_cast<int>(day)-7); year--; if(year==1949) throw out_of_range("Previous date out of range."); } } return *this; } // BINARY ARITHMETIC OPERATORS unsigned int Date::operator-(const Date& otherDate) // Number of days between otherDate and current date { //using Rata Die Calendar return abs(rdn(*this)-rdn(otherDate)); } Date Date::operator+(int noOfDays) // Day noOfDays after (before) the current date // (sign of noOfDays decides ahead or behind) throw(domain_error, out_of_range) { //using inbuilt functions of C++ Date d1(D01,Jan,1950),d2(D31,Dec,2049); if((*this)-d1<(unsigned)(abs(noOfDays))&&noOfDays<0) throw out_of_range("Requested date out of range..."); if((*this)-d2<(unsigned)(abs(noOfDays))&&noOfDays>0) throw out_of_range("Requested date out of range..."); tm date={0,0,12}; //arbitrary date.tm_year=year-1900; date.tm_mon=static_cast<int>(month)-1; date.tm_mday=static_cast<int>(day); DatePlusDays( &date, noOfDays ) ; Date summed((to_string(date.tm_mday)+"-"+to_string(date.tm_mon+1)+"-"+to_string(date.tm_year+1900)).c_str()); return summed; } // CAST OPERATORS Date::operator WeekNumber() const // Cast to the week number of the year in which the current date falls { //using inbuilt C++ feature to get ISO 8601 week number //%V does not work for strftime() in Windows tm timeStruct = {0,0,12}; timeStruct.tm_year = year-1900; timeStruct.tm_mon=static_cast<int>(month)-1; timeStruct.tm_mday=static_cast<int>(day); mktime( &timeStruct ); //assigns other fields of timeStruct their values char buf[3]; strftime(buf,3,"%V",&timeStruct); //C++11, otherwise use %W for normal week number return static_cast<WeekNumber>(atoi(buf)); //finally cating to WeekNumber enum } Date::operator Month() const // Cast to the month of the year in which the current date falls { return static_cast<Month>(this->month); //casting month to Month enum } Date::operator WeekDay() const // Cast to the day of the week of the current date { tm timeStruct = {0,0,12}; timeStruct.tm_year = year-1900; timeStruct.tm_mon=static_cast<int>(month)-1; timeStruct.tm_mday=static_cast<int>(day); mktime( &timeStruct ); //assigns other fields of timeStruct their values //tm_wday gives number of days elapsed since Sunday int weekday=(timeStruct.tm_wday?timeStruct.tm_wday:7); //Sunday is not considered 0, but 7 return static_cast<WeekDay>(weekday); } bool Date::leapYear() const // True if the year of the current date is a leap year { return year%4==0&&year%100!=0; //Typical leap year conditions } // BINARY RELATIONAL OPERATORS bool Date::operator==(const Date& otherDate) { return day==otherDate.day && month== otherDate.month && year==otherDate.year; } bool Date::operator!=(const Date& otherDate) { return day!=otherDate.day || month != otherDate.month || year!=otherDate.year; } //Using Rata Die values to compare dates bool Date::operator<(const Date& otherDate) { return (rdn(*this)<rdn(otherDate)); } bool Date::operator<=(const Date& otherDate) { return (rdn(*this)<=rdn(otherDate)); } bool Date::operator>(const Date& otherDate) { return (rdn(*this)>rdn(otherDate)); } bool Date::operator>=(const Date& otherDate) { return (rdn(*this)>=rdn(otherDate)); } // BASIC I/O using FRIEND FUNCTIONS // These functions use Date::format to write or read ostream& operator<<(ostream& o, const Date& date) { //Consider dateformat in terms of length of dateformat, monthformat and yearformat DateFormat df=date.getFormat(); char *dateFormat=mystrdup(df.getDateFormat()); char *monthFormat=mystrdup(df.getMonthFormat()); char *yearFormat=mystrdup(df.getYearFormat()); int d,m,y; if(dateFormat==0) d=0; else d=strlen(dateFormat); if(monthFormat==0) m=0; else m=strlen(monthFormat); if(yearFormat==0) y=0; else y=strlen(yearFormat); if(d>2||d<0) throw domain_error("Wrong date format n4."); if(d==2) { o << setfill('0') << setw(2) << static_cast<int>(date.getDay()) ; o<<'-'; } else if(d==1) { o<<static_cast<int>(date.getDay())<<'-'; } else o<<" -"; if(m>3||m<0) throw domain_error("Wrong date format n7."); //if m is 3, print Month name if(m==3) { switch(static_cast<int>(date.getMonth())) { case 1: o<<"Jan"; break; case 2: o<<"Feb"; break; case 3: o<<"Mar"; break; case 4: o<<"Apr"; break; case 5: o<<"May"; break; case 6: o<<"Jun"; break; case 7: o<<"Jul"; break; case 8: o<<"Aug"; break; case 9: o<<"Sep"; break; case 10: o<<"Oct"; break; case 11: o<<"Nov"; break; case 12: o<<"Dec"; break; } o<<'-'; } else if(m==2) { o<< setfill('0') << setw(2) << static_cast<int>(date.getMonth()) ; o<<'-'; } else if(m==1) { o<<static_cast<int>(date.getMonth())<<'-'; } else o<<" -"; if(y!=0&&y!=2&&y!=4) throw domain_error("Wrong date format n0."); if(y==2) { o << date.getYear()%100 ; } else if(y==4) { o<<date.getYear(); } delete[] dateFormat; delete[] monthFormat; delete[] yearFormat; return o; } //Similar to << operator istream& operator>>(istream& i, Date& date) { DateFormat df=date.getFormat(); char *dateFormat=mystrdup(df.getDateFormat()); char *monthFormat=mystrdup(df.getMonthFormat()); char *yearFormat=mystrdup(df.getYearFormat()); int d,m,y; if(dateFormat==0) d=0; else d=strlen(dateFormat); if(monthFormat==0) m=0; else m=strlen(monthFormat); if(yearFormat==0) y=0; else y=strlen(yearFormat); //Considering all cases of d,m,y values independently if(d>2||d<0) throw domain_error("Wrong date format 1."); if(d==2) { char *s=new char[3]; i.get(s,3); if(strlen(s)!=2) throw domain_error("Wrong date format 2."); if(!isdigit(s[0])||!isdigit(s[1])) throw domain_error("Wrong date value."); date.day=static_cast<Day>(atoi(s)); i.get(); delete[] s; } else if(d==1) { char *s=new char[3]; i.get(s,3,'-'); if(strlen(s)==2) { if(!isdigit(s[0])||!isdigit(s[1])) throw domain_error("Wrong date value."); if(s[0]=='0') throw domain_error("Date entered in wrong format"); } else if(strlen(s)==1) { if(s[0]<'1'||s[0]>'9') throw domain_error("Wrong date value."); } else throw domain_error("Wrong date format 3."); date.day=static_cast<Day>(atoi(s)); i.get(); delete[] s; } else throw domain_error("Invalid date format for input."); if(m>3||m<0) throw domain_error("Wrong date format 4."); if(m==3||m==0) { throw domain_error("Invalid month format for input."); } else if(m==2) { char *s=new char[3]; i.get(s,3); if(strlen(s)!=2) throw domain_error("Wrong date format. 5"); if(!isdigit(s[0])||!isdigit(s[1])) throw domain_error("Wrong date value."); date.month=static_cast<Month>(atoi(s)); if(date.day<1||date.day>numDays(date.month,date.year)) throw invalid_argument("Invalid date."); i.get(); delete[] s; } else if(m==1) { char *s=new char[3]; i.get(s,3,'-'); if(strlen(s)==2) { if(!isdigit(s[0])||!isdigit(s[1])) throw domain_error("Wrong month value."); if(s[0]=='0') throw domain_error("Month entered in wrong format"); } else if(strlen(s)==1) { if(s[0]<'1'||s[0]>'9') throw domain_error("Wrong month value."); } else throw domain_error("Wrong month format."); date.month=static_cast<Month>(atoi(s)); if(date.day<1||date.day>numDays(date.month,date.year)) throw invalid_argument("Invalid date."); i.get(); delete[] s; } if(y!=0&&y!=2&&y!=4) throw domain_error("Wrong date format. 6"); if(y==2) { char *s=new char[3]; i.get(s,3); if(strlen(s)!=2) throw domain_error("Wrong date format. 7"); if(!isdigit(s[0])||!isdigit(s[1])) throw domain_error("Wrong date value."); int inpyear=atoi(s); date.year=(inpyear>=50?1900+inpyear:2000+inpyear);; i.get(); delete[] s; } else if(y==4) { char *s=new char[5]; i.get(s,5); if(strlen(s)!=4) throw domain_error("Wrong date format. 8"); if(!isdigit(s[0])||!isdigit(s[1])||!isdigit(s[2])||!isdigit(s[3])) throw domain_error("Wrong date value."); date.year=atoi(s); i.get(); delete[] s; } delete[] dateFormat; delete[] monthFormat; delete[] yearFormat; return i; } // Format Function void Date::setFormat(DateFormat& d) { format=d; //Using copy constructor } DateFormat& Date::getFormat() { return format; } Day Date::getDay() const { return day; } Month Date::getMonth() const { return month; } Year Date::getYear() const { return year; } DateFormat Date::format; //Use default constructor
[ "shravan.ma.iitkgp@gmail.com" ]
shravan.ma.iitkgp@gmail.com
591605c44b6a614cd2c35487006dd75cf24cc6b4
28eeca435f398e2162f907fbdd4d5f3b37cbdcec
/src/caffe/test/test_net.cpp
459d7250c3e93780bd8715499da7bd6a17dbeedd
[ "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
kmisimn76/CAFFE_INT8
6a0dc344f80dcb2976c3221735fbd089eb843206
132eeb742e68c4152089219bf8b20d9f1f43de03
refs/heads/master
2022-05-13T23:48:41.585265
2020-03-20T13:32:16
2020-03-20T13:32:16
217,015,632
0
0
null
null
null
null
UTF-8
C++
false
false
81,487
cpp
#include <string> #include <utility> #include <vector> #include "google/protobuf/text_format.h" #include "gtest/gtest.h" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/net.hpp" #include "caffe/util/io.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/test/test_caffe_main.hpp" #include "caffe/test/test_gradient_check_util.hpp" namespace caffe { template <typename TypeParam> class NetTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: NetTest() : seed_(1701) {} virtual void InitNetFromProtoString(const string& proto) { NetParameter param; CHECK(google::protobuf::TextFormat::ParseFromString(proto, &param)); net_.reset(new Net<Dtype>(param)); } virtual void InitNetFromProtoFileWithState(const string& proto, Phase phase = caffe::TRAIN, const int level = 0, const vector<string>* stages = NULL) { NetParameter param; CHECK(google::protobuf::TextFormat::ParseFromString(proto, &param)); string param_file; MakeTempFilename(&param_file); WriteProtoToTextFile(param, param_file); net_.reset(new Net<Dtype>(param_file, phase, level, stages)); } virtual void CopyNetBlobs(const bool copy_diff, vector<shared_ptr<Blob<Dtype> > >* blobs_copy) { CHECK(net_); const vector<shared_ptr<Blob<Dtype> > >& net_blobs = net_->blobs(); blobs_copy->clear(); blobs_copy->resize(net_blobs.size()); const bool kReshape = true; for (int i = 0; i < net_blobs.size(); ++i) { (*blobs_copy)[i].reset(new Blob<Dtype>()); (*blobs_copy)[i]->CopyFrom(*net_blobs[i], copy_diff, kReshape); } } virtual void CopyNetParams(const bool copy_diff, vector<shared_ptr<Blob<Dtype> > >* params_copy) { CHECK(net_); const vector<shared_ptr<Blob<Dtype> > >& net_params = net_->params(); params_copy->clear(); params_copy->resize(net_params.size()); const bool kReshape = true; for (int i = 0; i < net_params.size(); ++i) { (*params_copy)[i].reset(new Blob<Dtype>()); (*params_copy)[i]->CopyFrom(*net_params[i], copy_diff, kReshape); } } virtual void InitTinyNet(const bool force_backward = false, const bool accuracy_layer = false) { string proto = "name: 'TinyTestNetwork' " "layer { " " name: 'data' " " type: 'DummyData' " " dummy_data_param { " " shape { " " dim: 5 " " dim: 2 " " dim: 3 " " dim: 4 " " } " " data_filler { " " type: 'gaussian' " " std: 0.01 " " } " " shape { " " dim: 5 " " } " " data_filler { " " type: 'constant' " " value: 0 " " } " " } " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerproduct' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 1000 " " weight_filler { " " type: 'gaussian' " " std: 0.01 " " } " " bias_filler { " " type: 'constant' " " value: 0 " " } " " } " " param { " " lr_mult: 1 " " decay_mult: 1 " " } " " param { " " lr_mult: 2 " " decay_mult: 0 " " } " " bottom: 'data' " " top: 'innerproduct' " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerproduct' " " bottom: 'label' " " top: 'top_loss' " "} "; if (accuracy_layer) { proto += "layer { " " name: 'loss' " " type: 'Accuracy' " " bottom: 'innerproduct' " " bottom: 'label' " " top: 'accuracy' " "} "; } if (force_backward) { proto += "force_backward: true "; } InitNetFromProtoString(proto); } virtual void InitTinyNetEuclidean(const bool force_backward = false) { string proto = "name: 'TinyTestEuclidLossNetwork' " "layer { " " name: 'data' " " type: 'DummyData' " " dummy_data_param { " " num: 5 " " channels: 2 " " height: 3 " " width: 4 " " num: 5 " " channels: 1 " " height: 1 " " width: 1 " " data_filler { " " type: 'gaussian' " " std: 0.01 " " } " " } " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerproduct' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 1 " " weight_filler { " " type: 'gaussian' " " std: 0.01 " " } " " bias_filler { " " type: 'constant' " " value: 0 " " } " " } " " param { " " lr_mult: 1 " " decay_mult: 1 " " } " " param { " " lr_mult: 2 " " decay_mult: 0 " " } " " bottom: 'data' " " top: 'innerproduct' " "} " "layer { " " name: 'loss' " " type: 'EuclideanLoss' " " bottom: 'innerproduct' " " bottom: 'label' " "} "; if (force_backward) { proto += "force_backward: true "; } InitNetFromProtoString(proto); } virtual void InitTrickyNet(Dtype* loss_weight = NULL) { ostringstream loss_weight_stream; if (loss_weight) { loss_weight_stream << " loss_weight: " << *loss_weight << " "; } const string& proto = "name: 'TrickyTestNetwork' " "layer { " " name: 'data' " " type: 'DummyData' " " dummy_data_param { " " num: 5 " " channels: 2 " " height: 3 " " width: 4 " " num: 5 " " channels: 1 " " height: 1 " " width: 1 " " data_filler { " " type: 'gaussian' " " std: 0.01 " " } " " } " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerproduct' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 1000 " " weight_filler { " " type: 'gaussian' " " std: 0.01 " " } " " bias_filler { " " type: 'constant' " " value: 0 " " } " " } " " param { " " lr_mult: 1 " " decay_mult: 1 " " } " " param { " " lr_mult: 2 " " decay_mult: 0 " " } " " bottom: 'data' " " top: 'transformed_data' " "} " "layer { " " name: 'innerproduct' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 1 " " weight_filler { " " type: 'gaussian' " " std: 0.01 " " } " " bias_filler { " " type: 'constant' " " value: 0 " " } " " } " " param { " " lr_mult: 1 " " decay_mult: 1 " " } " " param { " " lr_mult: 2 " " decay_mult: 0 " " } " " bottom: 'label' " " top: 'transformed_label' " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " + loss_weight_stream.str() + " bottom: 'transformed_data' " " bottom: 'transformed_label' " "} "; InitNetFromProtoString(proto); } // loss_weight is the loss weight for the 'EuclideanLoss' layer output. // midnet_loss_weight is the loss weight for the first 'InnerProduct' layer // output. Should both default to 0.0 if unspecified (i.e., if NULL is // passed to this function). virtual void InitUnsharedWeightsNet(const Dtype* loss_weight = NULL, const Dtype* midnet_loss_weight = NULL, const bool force_backward = false, const bool bias_term = false, const Dtype blobs_lr_w1 = 1, const Dtype blobs_lr_b1 = 2, const Dtype blobs_lr_w2 = 1, const Dtype blobs_lr_b2 = 2) { string bias_str = bias_term ? "true ":"false "; ostringstream proto; proto << "name: 'UnsharedWeightsNetwork' "; if (force_backward) { proto << "force_backward: true "; } proto << "layer { " " name: 'data' " " type: 'DummyData' " " dummy_data_param { " " num: 5 " " channels: 2 " " height: 3 " " width: 4 " " data_filler { " " type: 'gaussian' " " std: 0.01 " " } " " } " " top: 'data' " "} " "layer { " " name: 'innerproduct1' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 10 " " bias_term: " << bias_str << " weight_filler { " " type: 'gaussian' " " std: 10 " " } " " } " " param { " " name: 'unsharedweights1' " " lr_mult: " << blobs_lr_w1 << " } "; if (bias_term) { proto << " param { lr_mult: " << blobs_lr_b1 << " } "; } proto << " bottom: 'data' " " top: 'innerproduct1' "; if (midnet_loss_weight) { proto << " loss_weight: " << *midnet_loss_weight << " "; } proto << "} " "layer { " " name: 'innerproduct2' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 10 " " bias_term: " << bias_str << " weight_filler { " " type: 'gaussian' " " std: 10 " " } " " } " " param { " " name: 'unsharedweights2' " " lr_mult: " << blobs_lr_w2 << " } "; if (bias_term) { proto << " param { lr_mult: " << blobs_lr_b2 << " } "; } proto << " bottom: 'data' " " top: 'innerproduct2' " "} " "layer { " " name: 'loss' " " type: 'EuclideanLoss' "; if (loss_weight) { proto << " loss_weight: " << *loss_weight << " "; } proto << " bottom: 'innerproduct1' " " bottom: 'innerproduct2' " "} "; InitNetFromProtoString(proto.str()); } virtual void InitSharedWeightsNet() { const string& proto = "name: 'SharedWeightsNetwork' " "layer { " " name: 'data' " " type: 'DummyData' " " dummy_data_param { " " num: 5 " " channels: 2 " " height: 3 " " width: 4 " " data_filler { " " type: 'gaussian' " " std: 0.01 " " } " " } " " top: 'data' " "} " "layer { " " name: 'innerproduct1' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 10 " " bias_term: false " " weight_filler { " " type: 'gaussian' " " std: 10 " " } " " } " " param { name: 'sharedweights' } " " bottom: 'data' " " top: 'innerproduct1' " "} " "layer { " " name: 'innerproduct2' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 10 " " bias_term: false " " weight_filler { " " type: 'gaussian' " " std: 10 " " } " " } " " param { name: 'sharedweights' } " " bottom: 'data' " " top: 'innerproduct2' " "} " "layer { " " name: 'loss' " " type: 'EuclideanLoss' " " bottom: 'innerproduct1' " " bottom: 'innerproduct2' " "} "; InitNetFromProtoString(proto); } virtual void InitDiffDataUnsharedWeightsNet() { const string& proto = "name: 'DiffDataUnsharedWeightsNetwork' " "layer { " " name: 'data' " " type: 'DummyData' " " dummy_data_param { " " num: 10 " " channels: 10 " " height: 1 " " width: 1 " " num: 10 " " channels: 10 " " height: 1 " " width: 1 " " data_filler { " " type: 'gaussian' " " std: 10 " " } " " } " " top: 'data1' " " top: 'data2' " "} " "layer { " " name: 'innerproduct1' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 10 " " bias_term: false " " weight_filler { " " type: 'constant' " " value: 0.5 " " } " " } " " param { name: 'unsharedweights1' } " " bottom: 'data1' " " top: 'innerproduct1' " "} " "layer { " " name: 'innerproduct2' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 10 " " bias_term: false " " weight_filler { " " type: 'constant' " " value: 0.5 " " } " " } " " param { name: 'unsharedweights2' } " " bottom: 'innerproduct1' " " top: 'innerproduct2' " "} " "layer { " " name: 'loss' " " type: 'EuclideanLoss' " " bottom: 'data2' " " bottom: 'innerproduct2' " "} "; InitNetFromProtoString(proto); } virtual void InitDiffDataSharedWeightsNet() { const string& proto = "name: 'DiffDataSharedWeightsNetwork' " "layer { " " name: 'data' " " type: 'DummyData' " " dummy_data_param { " " num: 10 " " channels: 10 " " height: 1 " " width: 1 " " num: 10 " " channels: 10 " " height: 1 " " width: 1 " " data_filler { " " type: 'gaussian' " " std: 10 " " } " " } " " top: 'data1' " " top: 'data2' " "} " "layer { " " name: 'innerproduct1' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 10 " " bias_term: false " " weight_filler { " " type: 'constant' " " value: 0.5 " " } " " } " " param { name: 'sharedweights' } " " bottom: 'data1' " " top: 'innerproduct1' " "} " "layer { " " name: 'innerproduct2' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 10 " " bias_term: false " " weight_filler { " " type: 'constant' " " value: 0.5 " " } " " } " " param { name: 'sharedweights' } " " bottom: 'innerproduct1' " " top: 'innerproduct2' " "} " "layer { " " name: 'loss' " " type: 'EuclideanLoss' " " bottom: 'data2' " " bottom: 'innerproduct2' " "} "; InitNetFromProtoString(proto); } virtual void InitReshapableNet() { const string& proto = "name: 'ReshapableNetwork' " "layer { " " name: 'data' " " type: 'Input' " " top: 'data' " " input_param { " " shape: { dim: 1 dim: 3 dim: 100 dim: 100 } " " } " "} " "layer { " " name: 'conv1' " " type: 'Convolution' " " bottom: 'data' " " top: 'conv1' " " convolution_param { " " num_output: 5 " " kernel_size: 3 " " stride: 2 " " weight_filler { " " type: 'gaussian' " " std: 0.01 " " } " " bias_filler { " " type: 'constant' " " value: 0.2 " " } " " } " "} " "layer { " " name: 'relu1' " " type: 'ReLU' " " bottom: 'conv1' " " top: 'conv1' " "} " "layer { " " name: 'pool1' " " type: 'Pooling' " " bottom: 'conv1' " " top: 'pool1' " " pooling_param { " " pool: MAX " " kernel_size: 2 " " stride: 2 " " } " "} " "layer { " " name: 'norm1' " " type: 'LRN' " " bottom: 'pool1' " " top: 'norm1' " " lrn_param { " " local_size: 3 " " } " "} " "layer { " " name: 'softmax' " " type: 'Softmax' " " bottom: 'norm1' " " top: 'softmax' " "} "; InitNetFromProtoString(proto); } virtual void InitSkipPropNet(bool test_skip_true) { string proto = "name: 'SkipPropTestNetwork' " "layer { " " name: 'data' " " type: 'DummyData' " " dummy_data_param { " " shape { " " dim: 5 " " dim: 2 " " dim: 3 " " dim: 4 " " } " " data_filler { " " type: 'gaussian' " " std: 0.01 " " } " " shape { " " dim: 5 " " } " " data_filler { " " type: 'constant' " " value: 0 " " } " " } " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'silence' " " bottom: 'label' " " type: 'Silence' " "} " "layer { " " name: 'innerproduct' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 1 " " weight_filler { " " type: 'gaussian' " " std: 0.01 " " } " " bias_filler { " " type: 'constant' " " value: 0 " " } " " } " " param { " " lr_mult: 1 " " decay_mult: 1 " " } " " param { " " lr_mult: 2 " " decay_mult: 0 " " } " " bottom: 'data' " " top: 'innerproduct' " "} " "layer { " " name: 'ip_fake_labels' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 1 " " weight_filler { " " type: 'gaussian' " " std: 0.01 " " } " " bias_filler { " " type: 'constant' " " value: 0 " " } " " } " " bottom: 'data' " " top: 'fake_labels' " "} " "layer { " " name: 'argmax' " " bottom: 'fake_labels' " " top: 'label_argmax' " " type: 'ArgMax' " "} " "layer { " " name: 'loss' " " bottom: 'innerproduct' " " bottom: 'label_argmax' "; if (test_skip_true) proto += " propagate_down: true " " propagate_down: false "; else proto += " propagate_down: true " " propagate_down: true "; proto += " top: 'cross_entropy_loss' " " type: 'SigmoidCrossEntropyLoss' " " loss_weight: 0.1 " "} "; InitNetFromProtoString(proto); } virtual void InitForcePropNet(bool test_force_true) { string proto = "name: 'ForcePropTestNetwork' " "layer { " " name: 'data' " " type: 'DummyData' " " dummy_data_param { " " shape { " " dim: 5 " " dim: 2 " " dim: 3 " " dim: 4 " " } " " data_filler { " " type: 'gaussian' " " std: 0.01 " " } " " shape { " " dim: 5 " " } " " data_filler { " " type: 'constant' " " value: 0 " " } " " } " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerproduct' " " type: 'InnerProduct' " " inner_product_param { " " num_output: 1 " " weight_filler { " " type: 'gaussian' " " std: 0.01 " " } " " } " " bottom: 'data' " " top: 'innerproduct' "; if (test_force_true) { proto += " propagate_down: true "; } proto += "} " "layer { " " name: 'loss' " " bottom: 'innerproduct' " " bottom: 'label' " " top: 'cross_entropy_loss' " " type: 'SigmoidCrossEntropyLoss' " "} "; InitNetFromProtoString(proto); } virtual void InitAllInOneNet(Phase phase = caffe::TRAIN, const int level = 0, const vector<string>* stages = NULL) { string proto = "name: 'All-in-one Network'" "layer { " " name: 'train-data' " " type: 'DummyData' " " top: 'data' " " top: 'label' " " dummy_data_param { " " shape { dim: 1 dim: 10 } " " shape { dim: 1 dim: 1 } " " } " " include { phase: TRAIN stage: 'train' } " "} " "layer { " " name: 'val-data' " " type: 'DummyData' " " top: 'data' " " top: 'label' " " dummy_data_param { " " shape { dim: 1 dim: 10 } " " shape { dim: 1 dim: 1 } " " } " " include { phase: TEST stage: 'val' } " "} " "layer { " " name: 'deploy-data' " " type: 'Input' " " top: 'data' " " input_param { " " shape { dim: 1 dim: 10 } " " } " " include { phase: TEST stage: 'deploy' } " "} " "layer { " " name: 'ip' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'ip' " " inner_product_param { " " num_output: 2 " " } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'ip' " " bottom: 'label' " " top: 'loss' " " include { phase: TRAIN stage: 'train' } " " include { phase: TEST stage: 'val' } " "} "; InitNetFromProtoFileWithState(proto, phase, level, stages); } int seed_; shared_ptr<Net<Dtype> > net_; }; TYPED_TEST_CASE(NetTest, TestDtypesAndDevices); TYPED_TEST(NetTest, TestHasBlob) { this->InitTinyNet(); EXPECT_TRUE(this->net_->has_blob("data")); EXPECT_TRUE(this->net_->has_blob("label")); EXPECT_TRUE(this->net_->has_blob("innerproduct")); EXPECT_FALSE(this->net_->has_blob("loss")); EXPECT_TRUE(this->net_->has_blob("top_loss")); } TYPED_TEST(NetTest, TestGetBlob) { this->InitTinyNet(); EXPECT_EQ(this->net_->blob_by_name("data"), this->net_->blobs()[0]); EXPECT_EQ(this->net_->blob_by_name("label"), this->net_->blobs()[1]); EXPECT_EQ(this->net_->blob_by_name("innerproduct"), this->net_->blobs()[2]); EXPECT_FALSE(this->net_->blob_by_name("loss")); EXPECT_EQ(this->net_->blob_by_name("top_loss"), this->net_->blobs()[3]); } TYPED_TEST(NetTest, TestHasLayer) { this->InitTinyNet(); EXPECT_TRUE(this->net_->has_layer("data")); EXPECT_TRUE(this->net_->has_layer("innerproduct")); EXPECT_TRUE(this->net_->has_layer("loss")); EXPECT_FALSE(this->net_->has_layer("label")); } TYPED_TEST(NetTest, TestGetLayerByName) { this->InitTinyNet(); EXPECT_EQ(this->net_->layer_by_name("data"), this->net_->layers()[0]); EXPECT_EQ(this->net_->layer_by_name("innerproduct"), this->net_->layers()[1]); EXPECT_EQ(this->net_->layer_by_name("loss"), this->net_->layers()[2]); EXPECT_FALSE(this->net_->layer_by_name("label")); } TYPED_TEST(NetTest, TestBottomNeedBackward) { this->InitTinyNet(); const vector<vector<bool> >& bottom_need_backward = this->net_->bottom_need_backward(); EXPECT_EQ(3, bottom_need_backward.size()); EXPECT_EQ(0, bottom_need_backward[0].size()); EXPECT_EQ(1, bottom_need_backward[1].size()); EXPECT_EQ(false, bottom_need_backward[1][0]); EXPECT_EQ(2, bottom_need_backward[2].size()); EXPECT_EQ(true, bottom_need_backward[2][0]); EXPECT_EQ(false, bottom_need_backward[2][1]); } TYPED_TEST(NetTest, TestBottomNeedBackwardForce) { const bool force_backward = true; this->InitTinyNet(force_backward); const vector<vector<bool> >& bottom_need_backward = this->net_->bottom_need_backward(); EXPECT_EQ(3, bottom_need_backward.size()); EXPECT_EQ(0, bottom_need_backward[0].size()); EXPECT_EQ(1, bottom_need_backward[1].size()); EXPECT_EQ(true, bottom_need_backward[1][0]); EXPECT_EQ(2, bottom_need_backward[2].size()); EXPECT_EQ(true, bottom_need_backward[2][0]); EXPECT_EQ(false, bottom_need_backward[2][1]); } TYPED_TEST(NetTest, TestBottomNeedBackwardEuclideanForce) { const bool force_backward = true; this->InitTinyNetEuclidean(force_backward); const vector<vector<bool> >& bottom_need_backward = this->net_->bottom_need_backward(); EXPECT_EQ(3, bottom_need_backward.size()); EXPECT_EQ(0, bottom_need_backward[0].size()); EXPECT_EQ(1, bottom_need_backward[1].size()); EXPECT_EQ(true, bottom_need_backward[1][0]); EXPECT_EQ(2, bottom_need_backward[2].size()); EXPECT_EQ(true, bottom_need_backward[2][0]); EXPECT_EQ(true, bottom_need_backward[2][1]); } TYPED_TEST(NetTest, TestBottomNeedBackwardTricky) { this->InitTrickyNet(); const vector<vector<bool> >& bottom_need_backward = this->net_->bottom_need_backward(); EXPECT_EQ(4, bottom_need_backward.size()); EXPECT_EQ(0, bottom_need_backward[0].size()); EXPECT_EQ(1, bottom_need_backward[1].size()); EXPECT_EQ(false, bottom_need_backward[1][0]); EXPECT_EQ(1, bottom_need_backward[2].size()); EXPECT_EQ(false, bottom_need_backward[2][0]); EXPECT_EQ(2, bottom_need_backward[3].size()); EXPECT_EQ(true, bottom_need_backward[3][0]); // The label input to the SoftmaxLossLayer should say it "needs backward" // since it has weights under it, even though we expect this to cause a crash // at training/test time. EXPECT_EQ(true, bottom_need_backward[3][1]); } TYPED_TEST(NetTest, TestLossWeight) { typedef typename TypeParam::Dtype Dtype; // First, compute the loss and gradients with no loss_weight specified. // In this case, the loss weight for the 'EuclideanLoss' layer should default // to 1. vector<Blob<Dtype>*> bottom; Caffe::set_random_seed(this->seed_); const bool kForceBackward = true; this->InitUnsharedWeightsNet(NULL, NULL, kForceBackward); const Dtype loss = this->net_->ForwardBackward(); const bool kCopyDiff = true; vector<shared_ptr<Blob<Dtype> > > blob_grads; this->CopyNetBlobs(kCopyDiff, &blob_grads); vector<shared_ptr<Blob<Dtype> > > param_grads; this->CopyNetParams(kCopyDiff, &param_grads); // Check that the loss is non-trivial, otherwise the test doesn't prove much. const Dtype kMinLossAbsValue = 1e-2; ASSERT_GE(fabs(loss), kMinLossAbsValue); const Dtype kErrorMargin = 1e-4; const int kNumLossWeights = 6; Dtype kLossWeights[kNumLossWeights] = {2, 0, 1, -1, -2.5, 3.7}; for (int i = 0; i < kNumLossWeights; ++i) { Caffe::set_random_seed(this->seed_); this->InitUnsharedWeightsNet(&kLossWeights[i], NULL, kForceBackward); const Dtype weighted_loss = this->net_->ForwardBackward(); const Dtype error_margin = kErrorMargin * fabs(kLossWeights[i]); EXPECT_NEAR(loss * kLossWeights[i], weighted_loss, error_margin) << "loss weight = " << kLossWeights[i]; const vector<shared_ptr<Blob<Dtype> > >& weighted_blobs = this->net_->blobs(); ASSERT_EQ(blob_grads.size(), weighted_blobs.size()); for (int j = 0; j < blob_grads.size(); ++j) { ASSERT_EQ(blob_grads[j]->count(), weighted_blobs[j]->count()); for (int k = 0; k < blob_grads[j]->count(); ++k) { EXPECT_NEAR(blob_grads[j]->cpu_diff()[k] * kLossWeights[i], weighted_blobs[j]->cpu_diff()[k], error_margin); } } const vector<shared_ptr<Blob<Dtype> > >& weighted_params = this->net_->params(); ASSERT_EQ(param_grads.size(), weighted_params.size()); for (int j = 0; j < param_grads.size(); ++j) { ASSERT_EQ(param_grads[j]->count(), weighted_params[j]->count()); for (int k = 0; k < param_grads[j]->count(); ++k) { EXPECT_NEAR(param_grads[j]->cpu_diff()[k] * kLossWeights[i], weighted_params[j]->cpu_diff()[k], error_margin); } } } } TYPED_TEST(NetTest, TestLossWeightMidNet) { typedef typename TypeParam::Dtype Dtype; Caffe::set_random_seed(this->seed_); const bool kForceBackward = true; Dtype loss_weight = 0; Dtype midnet_loss_weight = 1; this->InitUnsharedWeightsNet(&loss_weight, &midnet_loss_weight, kForceBackward); const Dtype loss = this->net_->ForwardBackward(); const bool kCopyDiff = true; const bool kReshape = true; Blob<Dtype> data_grad; data_grad.CopyFrom(*this->net_->blob_by_name("data"), kCopyDiff, kReshape); // Check that the loss is non-trivial, otherwise the test doesn't prove much. const Dtype kMinLossAbsValue = 1e-2; ASSERT_GE(fabs(loss), kMinLossAbsValue); const Dtype kErrorMargin = 1e-4; const int kNumLossWeights = 6; Dtype kLossWeights[kNumLossWeights] = {2, 0, 1, -1, -2.5, 3.7}; for (int i = 0; i < kNumLossWeights; ++i) { Caffe::set_random_seed(this->seed_); this->InitUnsharedWeightsNet(&loss_weight, &kLossWeights[i], kForceBackward); const Dtype weighted_loss = this->net_->ForwardBackward(); const Dtype error_margin = kErrorMargin * fabs(kLossWeights[i]); EXPECT_NEAR(loss * kLossWeights[i], weighted_loss, error_margin) << "loss weight = " << kLossWeights[i]; const shared_ptr<Blob<Dtype> >& weighted_blob = this->net_->blob_by_name("data"); ASSERT_EQ(data_grad.count(), weighted_blob->count()); for (int j = 0; j < data_grad.count(); ++j) { EXPECT_NEAR(data_grad.cpu_diff()[j] * kLossWeights[i], weighted_blob->cpu_diff()[j], error_margin); } } } TYPED_TEST(NetTest, TestComboLossWeight) { typedef typename TypeParam::Dtype Dtype; Dtype loss_weight; Dtype midnet_loss_weight; const bool kForceBackward = true; const Dtype kErrorMargin = 1e-4; // Get the loss and gradients with 'EuclideanLoss' weight 1, // 'InnerProduct' weight 1. loss_weight = 1; midnet_loss_weight = 1; Caffe::set_random_seed(this->seed_); this->InitUnsharedWeightsNet(&loss_weight, &midnet_loss_weight, kForceBackward); const Dtype loss = this->net_->ForwardBackward(); const bool kCopyDiff = true; vector<shared_ptr<Blob<Dtype> > > blob_grads; this->CopyNetBlobs(kCopyDiff, &blob_grads); vector<shared_ptr<Blob<Dtype> > > param_grads; this->CopyNetParams(kCopyDiff, &param_grads); loss_weight = 2; midnet_loss_weight = 1; Caffe::set_random_seed(this->seed_); this->InitUnsharedWeightsNet(&loss_weight, &midnet_loss_weight, kForceBackward); const Dtype loss_main_2 = this->net_->ForwardBackward(); vector<shared_ptr<Blob<Dtype> > > blob_grads_loss_2; this->CopyNetBlobs(kCopyDiff, &blob_grads_loss_2); vector<shared_ptr<Blob<Dtype> > > param_grads_loss_2; this->CopyNetParams(kCopyDiff, &param_grads_loss_2); loss_weight = 3; midnet_loss_weight = 1; Caffe::set_random_seed(this->seed_); this->InitUnsharedWeightsNet(&loss_weight, &midnet_loss_weight, kForceBackward); const Dtype loss_main_3 = this->net_->ForwardBackward(); const vector<shared_ptr<Blob<Dtype> > >& blob_grads_loss_3 = this->net_->blobs(); ASSERT_EQ(blob_grads.size(), blob_grads_loss_3.size()); ASSERT_EQ(blob_grads_loss_2.size(), blob_grads_loss_3.size()); for (int j = 0; j < blob_grads.size(); ++j) { const string& blob_name = this->net_->blob_names()[j]; bool grad_should_change = true; if (blob_name == "innerproduct1_innerproduct1_0_split_0") { grad_should_change = false; } ASSERT_EQ(blob_grads[j]->count(), blob_grads_loss_3[j]->count()); ASSERT_EQ(blob_grads_loss_2[j]->count(), blob_grads_loss_3[j]->count()); for (int k = 0; k < blob_grads[j]->count(); ++k) { const Dtype grad_diff_2 = blob_grads_loss_2[j]->cpu_diff()[k] - blob_grads[j]->cpu_diff()[k]; const Dtype grad_diff_3 = blob_grads_loss_3[j]->cpu_diff()[k] - blob_grads[j]->cpu_diff()[k]; if (grad_should_change) { // Test non-triviality. const Dtype kMinGradDiffAbsValue = 1e-4; EXPECT_GT(fabs(grad_diff_2), kMinGradDiffAbsValue) << blob_name; EXPECT_NEAR(2 * grad_diff_2, grad_diff_3, kErrorMargin) << blob_name; } else { EXPECT_EQ(0, grad_diff_2) << blob_name; EXPECT_EQ(0, grad_diff_3) << blob_name; } } } loss_weight = 1; midnet_loss_weight = 2; Caffe::set_random_seed(this->seed_); this->InitUnsharedWeightsNet(&loss_weight, &midnet_loss_weight, kForceBackward); const Dtype loss_midnet_2 = this->net_->ForwardBackward(); this->CopyNetBlobs(kCopyDiff, &blob_grads_loss_2); this->CopyNetParams(kCopyDiff, &param_grads_loss_2); loss_weight = 1; midnet_loss_weight = 3; Caffe::set_random_seed(this->seed_); this->InitUnsharedWeightsNet(&loss_weight, &midnet_loss_weight, kForceBackward); const Dtype loss_midnet_3 = this->net_->ForwardBackward(); const vector<shared_ptr<Blob<Dtype> > >& blob_grads_midnet_loss_3 = this->net_->blobs(); ASSERT_EQ(blob_grads.size(), blob_grads_midnet_loss_3.size()); ASSERT_EQ(blob_grads_loss_2.size(), blob_grads_midnet_loss_3.size()); const vector<string>& blob_names = this->net_->blob_names(); for (int j = 0; j < blob_grads.size(); ++j) { const string& blob_name = blob_names[j]; bool grad_should_change = false; if (blob_name == "innerproduct1" || blob_name == "innerproduct1_innerproduct1_0_split_0" || blob_name == "data_data_0_split_0" || blob_name == "data") { grad_should_change = true; } ASSERT_EQ(blob_grads[j]->count(), blob_grads_midnet_loss_3[j]->count()); ASSERT_EQ(blob_grads[j]->count(), blob_grads_loss_2[j]->count()); for (int k = 0; k < blob_grads[j]->count(); ++k) { const Dtype grad_diff_2 = blob_grads_loss_2[j]->cpu_diff()[k] - blob_grads[j]->cpu_diff()[k]; const Dtype grad_diff_3 = blob_grads_midnet_loss_3[j]->cpu_diff()[k] - blob_grads[j]->cpu_diff()[k]; if (grad_should_change) { // Test non-triviality. const Dtype kMinGradDiffAbsValue = 1e-4; EXPECT_GT(fabs(grad_diff_2), kMinGradDiffAbsValue) << blob_name; EXPECT_NEAR(2 * grad_diff_2, grad_diff_3, kErrorMargin) << blob_name; } else { EXPECT_EQ(0, grad_diff_2) << blob_name; EXPECT_EQ(0, grad_diff_3) << blob_name; } } } const Dtype kMinLossDiffAbsValue = 1e-4; Dtype loss_diff_2 = loss_main_2 - loss; // Test non-triviality. EXPECT_GT(fabs(loss_diff_2), kMinLossDiffAbsValue); Dtype loss_diff_3 = loss_main_3 - loss; EXPECT_NEAR(2 * loss_diff_2, loss_diff_3, kErrorMargin); loss_diff_2 = loss_midnet_2 - loss; // Test non-triviality. EXPECT_GT(fabs(loss_diff_2), kMinLossDiffAbsValue); loss_diff_3 = loss_midnet_3 - loss; EXPECT_NEAR(2 * loss_diff_2, loss_diff_3, kErrorMargin); } TYPED_TEST(NetTest, TestBackwardWithAccuracyLayer) { const bool kForceBackward = false; const bool kAccuracyLayer = true; this->InitTinyNet(kForceBackward, kAccuracyLayer); EXPECT_TRUE(this->net_->has_blob("accuracy")); // Test that we can do Backward even though we have an 'Accuracy' layer. this->net_->ForwardBackward(); } TYPED_TEST(NetTest, TestUnsharedWeightsDataNet) { typedef typename TypeParam::Dtype Dtype; this->InitUnsharedWeightsNet(); Dtype loss; this->net_->Forward(&loss); EXPECT_GT(loss, 0); } TYPED_TEST(NetTest, TestSharedWeightsDataNet) { typedef typename TypeParam::Dtype Dtype; this->InitSharedWeightsNet(); Dtype loss; this->net_->Forward(&loss); EXPECT_FLOAT_EQ(loss, 0); } TYPED_TEST(NetTest, TestUnsharedWeightsDiffNet) { typedef typename TypeParam::Dtype Dtype; this->InitUnsharedWeightsNet(); Net<Dtype>* net = this->net_.get(); net->Forward(); net->Backward(); Layer<Dtype>* ip1_layer = net->layer_by_name("innerproduct1").get(); Layer<Dtype>* ip2_layer = net->layer_by_name("innerproduct2").get(); const int count = ip1_layer->blobs()[0]->count(); const Dtype* grad1 = ip1_layer->blobs()[0]->cpu_diff(); const Dtype* grad2 = ip2_layer->blobs()[0]->cpu_diff(); for (int i = 0; i < count; ++i) { EXPECT_GT(fabs(grad1[i]), 0); EXPECT_FLOAT_EQ(-1 * grad1[i], grad2[i]); } } TYPED_TEST(NetTest, TestSharedWeightsDiffNet) { typedef typename TypeParam::Dtype Dtype; this->InitSharedWeightsNet(); Net<Dtype>* net = this->net_.get(); Dtype loss; net->Forward(&loss); net->Backward(); EXPECT_FLOAT_EQ(loss, 0); Layer<Dtype>* ip1_layer = net->layer_by_name("innerproduct1").get(); Layer<Dtype>* ip2_layer = net->layer_by_name("innerproduct2").get(); const int count = ip1_layer->blobs()[0]->count(); const Dtype* grad1 = ip1_layer->blobs()[0]->cpu_diff(); const Dtype* grad2 = ip2_layer->blobs()[0]->cpu_diff(); for (int i = 0; i < count; ++i) { EXPECT_FLOAT_EQ(0, grad1[i]); EXPECT_FLOAT_EQ(0, grad2[i]); } } TYPED_TEST(NetTest, TestSharedWeightsUpdate) { typedef typename TypeParam::Dtype Dtype; Caffe::set_random_seed(this->seed_); this->InitDiffDataSharedWeightsNet(); EXPECT_EQ(this->net_->layer_names()[1], "innerproduct1"); EXPECT_EQ(this->net_->layer_names()[2], "innerproduct2"); Blob<Dtype>* ip1_weights = this->net_->layers()[1]->blobs()[0].get(); Blob<Dtype>* ip2_weights = this->net_->layers()[2]->blobs()[0].get(); // Check that data and diff blobs of shared weights share the same memory // locations. EXPECT_EQ(ip1_weights->cpu_data(), ip2_weights->cpu_data()); EXPECT_EQ(ip1_weights->cpu_diff(), ip2_weights->cpu_diff()); this->net_->Forward(); this->net_->Backward(); // Compute the expected update as the data minus the two diffs. Blob<Dtype> shared_params; const bool reshape = true; const bool copy_diff = false; shared_params.CopyFrom(*ip1_weights, copy_diff, reshape); shared_params.CopyFrom(*ip1_weights, !copy_diff, reshape); const int count = ip1_weights->count(); // Make sure the diffs are non-trivial. for (int i = 0; i < count; ++i) { EXPECT_NE(0, ip1_weights->cpu_diff()[i]); } caffe_axpy(count, Dtype(-1), shared_params.cpu_diff(), shared_params.mutable_cpu_data()); const Dtype* expected_updated_params = shared_params.cpu_data(); this->net_->Update(); const Dtype* actual_updated_params = ip1_weights->cpu_data(); for (int i = 0; i < count; ++i) { EXPECT_EQ(expected_updated_params[i], actual_updated_params[i]); } // Check that data blobs of shared weights STILL point to the same memory // location (because ... who knows). EXPECT_EQ(ip1_weights->cpu_data(), ip2_weights->cpu_data()); Caffe::set_random_seed(this->seed_); this->InitDiffDataUnsharedWeightsNet(); EXPECT_EQ(this->net_->layer_names()[1], "innerproduct1"); EXPECT_EQ(this->net_->layer_names()[2], "innerproduct2"); ip1_weights = this->net_->layers()[1]->blobs()[0].get(); ip2_weights = this->net_->layers()[2]->blobs()[0].get(); // Check that data and diff blobs of unshared weights are at different // locations in memory. EXPECT_NE(ip1_weights->cpu_data(), ip2_weights->cpu_data()); EXPECT_NE(ip1_weights->cpu_diff(), ip2_weights->cpu_diff()); this->net_->Forward(); this->net_->Backward(); // Compute the expected update. Blob<Dtype> unshared_params1; unshared_params1.CopyFrom(*ip1_weights, copy_diff, reshape); unshared_params1.CopyFrom(*ip1_weights, !copy_diff, reshape); Blob<Dtype> unshared_params2; unshared_params2.CopyFrom(*ip2_weights, copy_diff, reshape); unshared_params2.CopyFrom(*ip2_weights, !copy_diff, reshape); // Make sure the diffs are non-trivial and sum to the diff in the shared net. for (int i = 0; i < count; ++i) { EXPECT_NE(0, ip1_weights->cpu_diff()[i]); EXPECT_NE(0, ip2_weights->cpu_diff()[i]); EXPECT_NE(ip1_weights->cpu_diff()[i], ip2_weights->cpu_diff()[i]); EXPECT_FLOAT_EQ(ip1_weights->cpu_diff()[i] + ip2_weights->cpu_diff()[i], shared_params.cpu_diff()[i]); } caffe_axpy(count, Dtype(-1), ip1_weights->cpu_diff(), unshared_params1.mutable_cpu_data()); caffe_axpy(count, Dtype(-1), ip2_weights->cpu_diff(), unshared_params2.mutable_cpu_data()); const Dtype* expected_updated_params1 = unshared_params1.cpu_data(); const Dtype* expected_updated_params2 = unshared_params2.cpu_data(); this->net_->Update(); const Dtype* actual_updated_params1 = ip1_weights->cpu_data(); const Dtype* actual_updated_params2 = ip2_weights->cpu_data(); for (int i = 0; i < count; ++i) { EXPECT_EQ(expected_updated_params1[i], actual_updated_params1[i]); EXPECT_EQ(expected_updated_params2[i], actual_updated_params2[i]); EXPECT_NE(actual_updated_params1[i], actual_updated_params2[i]); EXPECT_NE(expected_updated_params, expected_updated_params1); } } TYPED_TEST(NetTest, TestSharedWeightsResume) { typedef typename TypeParam::Dtype Dtype; // Create a net with weight sharing; Update it once. Caffe::set_random_seed(this->seed_); this->InitDiffDataSharedWeightsNet(); EXPECT_EQ(this->net_->layer_names()[1], "innerproduct1"); EXPECT_EQ(this->net_->layer_names()[2], "innerproduct2"); Blob<Dtype>* ip1_weights = this->net_->layers()[1]->blobs()[0].get(); Blob<Dtype>* ip2_weights = this->net_->layers()[2]->blobs()[0].get(); // Check that data and diff blobs of shared weights share the same memory // locations. EXPECT_EQ(ip1_weights->cpu_data(), ip2_weights->cpu_data()); EXPECT_EQ(ip1_weights->cpu_diff(), ip2_weights->cpu_diff()); this->net_->ForwardBackward(); this->net_->Update(); Blob<Dtype> shared_params; const bool kReshape = true; const bool kCopyDiff = false; shared_params.CopyFrom(*ip1_weights, kCopyDiff, kReshape); const int count = ip1_weights->count(); // Write the net to a NetParameter, as in Solver::Snapshot. NetParameter net_param; this->net_->ToProto(&net_param); // Reinitialize the net and copy parameters from net_param, as in // Solver::Restore. Caffe::set_random_seed(this->seed_); this->InitDiffDataSharedWeightsNet(); this->net_->CopyTrainedLayersFrom(net_param); ip1_weights = this->net_->layers()[1]->blobs()[0].get(); ip2_weights = this->net_->layers()[2]->blobs()[0].get(); ASSERT_FALSE(NULL == ip1_weights); ASSERT_FALSE(NULL == ip2_weights); EXPECT_NE(ip1_weights, ip2_weights); // Check that data and diff blobs of shared weights share the same memory // locations. EXPECT_EQ(ip1_weights->cpu_data(), ip2_weights->cpu_data()); EXPECT_EQ(ip1_weights->cpu_diff(), ip2_weights->cpu_diff()); for (int i = 0; i < count; ++i) { EXPECT_FLOAT_EQ(shared_params.cpu_data()[i], ip1_weights->cpu_data()[i]); } } TYPED_TEST(NetTest, TestParamPropagateDown) { typedef typename TypeParam::Dtype Dtype; const bool kBiasTerm = true, kForceBackward = false; const Dtype* kLossWeight1 = NULL; const Dtype* kLossWeight2 = NULL; // Run the net with all params learned; check that gradients are non-zero. Caffe::set_random_seed(this->seed_); Dtype blobs_lr_w1 = 1, blobs_lr_w2 = 1, blobs_lr_b1 = 2, blobs_lr_b2 = 2; this->InitUnsharedWeightsNet(kLossWeight1, kLossWeight2, kForceBackward, kBiasTerm, blobs_lr_w1, blobs_lr_w2, blobs_lr_b1, blobs_lr_b2); this->net_->Forward(); this->net_->Backward(); const vector<shared_ptr<Blob<Dtype> > >& params = this->net_->params(); const int num_params = params.size(); ASSERT_EQ(4, num_params); const Dtype kNonZeroTestMin = 1e-3; vector<Dtype> param_asums(params.size()); for (int i = 0; i < num_params; ++i) { const Dtype param_asum = caffe_cpu_asum(params[i]->count(), params[i]->cpu_diff()); param_asums[i] = param_asum; EXPECT_GT(param_asum, kNonZeroTestMin); } // Change the learning rates to different non-zero values; should see same // gradients. Caffe::set_random_seed(this->seed_); blobs_lr_w1 *= 2, blobs_lr_w2 *= 2, blobs_lr_b1 *= 2, blobs_lr_b2 *= 2; this->InitUnsharedWeightsNet(kLossWeight1, kLossWeight2, kForceBackward, kBiasTerm, blobs_lr_w1, blobs_lr_w2, blobs_lr_b1, blobs_lr_b2); this->net_->Forward(); this->net_->Backward(); const vector<shared_ptr<Blob<Dtype> > >& params2 = this->net_->params(); ASSERT_EQ(num_params, params2.size()); for (int i = 0; i < num_params; ++i) { const Dtype param_asum = caffe_cpu_asum(params2[i]->count(), params2[i]->cpu_diff()); EXPECT_FLOAT_EQ(param_asum, param_asums[i]); } // Change a subset of the learning rates to zero; check that we see zero // gradients for those. Caffe::set_random_seed(this->seed_); blobs_lr_w1 = 1, blobs_lr_w2 = 0, blobs_lr_b1 = 0, blobs_lr_b2 = 1; this->InitUnsharedWeightsNet(kLossWeight1, kLossWeight2, kForceBackward, kBiasTerm, blobs_lr_w1, blobs_lr_w2, blobs_lr_b1, blobs_lr_b2); this->net_->Forward(); this->net_->Backward(); const vector<shared_ptr<Blob<Dtype> > >& params3 = this->net_->params(); ASSERT_EQ(num_params, params3.size()); for (int i = 0; i < num_params; ++i) { const Dtype param_asum = caffe_cpu_asum(params3[i]->count(), params3[i]->cpu_diff()); if (i == 1 || i == 2) { EXPECT_FLOAT_EQ(0, param_asum); } else { EXPECT_FLOAT_EQ(param_asum, param_asums[i]); } } // Change the opposite subset of the learning rates to zero. Caffe::set_random_seed(this->seed_); blobs_lr_w1 = 0, blobs_lr_w2 = 1, blobs_lr_b1 = 1, blobs_lr_b2 = 0; this->InitUnsharedWeightsNet(kLossWeight1, kLossWeight2, kForceBackward, kBiasTerm, blobs_lr_w1, blobs_lr_w2, blobs_lr_b1, blobs_lr_b2); this->net_->Forward(); this->net_->Backward(); const vector<shared_ptr<Blob<Dtype> > >& params4 = this->net_->params(); ASSERT_EQ(num_params, params4.size()); for (int i = 0; i < num_params; ++i) { const Dtype param_asum = caffe_cpu_asum(params4[i]->count(), params4[i]->cpu_diff()); if (i == 0 || i == 3) { EXPECT_FLOAT_EQ(0, param_asum); } else { EXPECT_FLOAT_EQ(param_asum, param_asums[i]); } } } TYPED_TEST(NetTest, TestFromTo) { typedef typename TypeParam::Dtype Dtype; this->InitTinyNet(); // Run Forward and Backward, recording the data diff and loss. Blob<Dtype> data; data.ReshapeLike(*this->net_->blob_by_name("data")); this->net_->Forward(); this->net_->Backward(); data.CopyFrom(*this->net_->blob_by_name("data"), true, true); const Dtype *loss_ptr = this->net_->output_blobs()[0]->cpu_data(); Dtype loss = *loss_ptr; // Check that combining partial Forwards gives the same loss. for (int i = 1; i < this->net_->layers().size(); ++i) { // Note that we skip layer zero to keep the same data. this->net_->ForwardFromTo(1, 1); if (i < this->net_->layers().size() - 1) { this->net_->ForwardFrom(i + 1); } EXPECT_EQ(loss, *loss_ptr); } // Check that combining partial Backwards gives the same data diff. for (int i = 1; i < this->net_->layers().size(); ++i) { this->net_->BackwardTo(i); this->net_->BackwardFrom(i - 1); for (int j = 0; j < data.count(); ++j) { EXPECT_EQ(data.cpu_diff()[j], this->net_->blob_by_name("data")->cpu_diff()[j]); } } } class FilterNetTest : public ::testing::Test { protected: void RunFilterNetTest( const string& input_param_string, const string& filtered_param_string) { NetParameter input_param; CHECK(google::protobuf::TextFormat::ParseFromString( input_param_string, &input_param)); NetParameter expected_filtered_param; CHECK(google::protobuf::TextFormat::ParseFromString( filtered_param_string, &expected_filtered_param)); NetParameter actual_filtered_param; Net<float>::FilterNet(input_param, &actual_filtered_param); EXPECT_EQ(expected_filtered_param.DebugString(), actual_filtered_param.DebugString()); // Also test idempotence. NetParameter double_filtered_param; Net<float>::FilterNet(actual_filtered_param, &double_filtered_param); EXPECT_EQ(actual_filtered_param.DebugString(), double_filtered_param.DebugString()); } }; TEST_F(FilterNetTest, TestNoFilter) { const string& input_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; this->RunFilterNetTest(input_proto, input_proto); } TEST_F(FilterNetTest, TestFilterLeNetTrainTest) { const string& input_proto = "name: 'LeNet' " "layer { " " name: 'mnist' " " type: 'Data' " " top: 'data' " " top: 'label' " " data_param { " " source: 'mnist-train-leveldb' " " batch_size: 64 " " } " " transform_param { " " scale: 0.00390625 " " } " " include: { phase: TRAIN } " "} " "layer { " " name: 'mnist' " " type: 'Data' " " top: 'data' " " top: 'label' " " data_param { " " source: 'mnist-test-leveldb' " " batch_size: 100 " " } " " transform_param { " " scale: 0.00390625 " " } " " include: { phase: TEST } " "} " "layer { " " name: 'conv1' " " type: 'Convolution' " " bottom: 'data' " " top: 'conv1' " " param { " " lr_mult: 1 " " } " " param { " " lr_mult: 2 " " } " " convolution_param { " " num_output: 20 " " kernel_size: 5 " " stride: 1 " " weight_filler { " " type: 'xavier' " " } " " bias_filler { " " type: 'constant' " " } " " } " "} " "layer { " " name: 'ip1' " " type: 'InnerProduct' " " bottom: 'conv1' " " top: 'ip1' " " param { " " lr_mult: 1 " " } " " param { " " lr_mult: 2 " " } " " inner_product_param { " " num_output: 10 " " weight_filler { " " type: 'xavier' " " } " " bias_filler { " " type: 'constant' " " } " " } " "} " "layer { " " name: 'accuracy' " " type: 'Accuracy' " " bottom: 'ip1' " " bottom: 'label' " " top: 'accuracy' " " include: { phase: TEST } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'ip2' " " bottom: 'label' " " top: 'loss' " "} "; const string input_proto_train = "state: { phase: TRAIN } " + input_proto; const string input_proto_test = "state: { phase: TEST } " + input_proto; const string output_proto_train = "name: 'LeNet' " "layer { " " name: 'mnist' " " type: 'Data' " " top: 'data' " " top: 'label' " " data_param { " " source: 'mnist-train-leveldb' " " batch_size: 64 " " } " " transform_param { " " scale: 0.00390625 " " } " " include: { phase: TRAIN } " "} " "layer { " " name: 'conv1' " " type: 'Convolution' " " bottom: 'data' " " top: 'conv1' " " param { " " lr_mult: 1 " " } " " param { " " lr_mult: 2 " " } " " convolution_param { " " num_output: 20 " " kernel_size: 5 " " stride: 1 " " weight_filler { " " type: 'xavier' " " } " " bias_filler { " " type: 'constant' " " } " " } " "} " "layer { " " name: 'ip1' " " type: 'InnerProduct' " " bottom: 'conv1' " " top: 'ip1' " " param { " " lr_mult: 1 " " } " " param { " " lr_mult: 2 " " } " " inner_product_param { " " num_output: 10 " " weight_filler { " " type: 'xavier' " " } " " bias_filler { " " type: 'constant' " " } " " } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'ip2' " " bottom: 'label' " " top: 'loss' " "} "; const string& output_proto_test = "name: 'LeNet' " "layer { " " name: 'mnist' " " type: 'Data' " " top: 'data' " " top: 'label' " " data_param { " " source: 'mnist-test-leveldb' " " batch_size: 100 " " } " " transform_param { " " scale: 0.00390625 " " } " " include: { phase: TEST } " "} " "layer { " " name: 'conv1' " " type: 'Convolution' " " bottom: 'data' " " top: 'conv1' " " param { " " lr_mult: 1 " " } " " param { " " lr_mult: 2 " " } " " convolution_param { " " num_output: 20 " " kernel_size: 5 " " stride: 1 " " weight_filler { " " type: 'xavier' " " } " " bias_filler { " " type: 'constant' " " } " " } " "} " "layer { " " name: 'ip1' " " type: 'InnerProduct' " " bottom: 'conv1' " " top: 'ip1' " " param { " " lr_mult: 1 " " } " " param { " " lr_mult: 2 " " } " " inner_product_param { " " num_output: 10 " " weight_filler { " " type: 'xavier' " " } " " bias_filler { " " type: 'constant' " " } " " } " "} " "layer { " " name: 'accuracy' " " type: 'Accuracy' " " bottom: 'ip1' " " bottom: 'label' " " top: 'accuracy' " " include: { phase: TEST } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'ip2' " " bottom: 'label' " " top: 'loss' " "} "; const string output_proto_train_explicit = output_proto_train + " state: { phase: TRAIN } "; const string output_proto_test_explicit = output_proto_test + " state: { phase: TEST } "; this->RunFilterNetTest(input_proto_train, output_proto_train_explicit); this->RunFilterNetTest(input_proto_test, output_proto_test_explicit); } TEST_F(FilterNetTest, TestFilterOutByStage) { const string& input_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " " include: { stage: 'mystage' } " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; const string& output_proto = "name: 'TestNetwork' " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; this->RunFilterNetTest(input_proto, output_proto); } TEST_F(FilterNetTest, TestFilterOutByStage2) { const string& input_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { stage: 'mystage' } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; const string& output_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; this->RunFilterNetTest(input_proto, output_proto); } TEST_F(FilterNetTest, TestFilterInByStage) { const string& input_proto = "state: { stage: 'mystage' } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { stage: 'mystage' } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; this->RunFilterNetTest(input_proto, input_proto); } TEST_F(FilterNetTest, TestFilterInByStage2) { const string& input_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " exclude: { stage: 'mystage' } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; this->RunFilterNetTest(input_proto, input_proto); } TEST_F(FilterNetTest, TestFilterOutByMultipleStage) { const string& input_proto = "state: { stage: 'mystage' } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { stage: 'mystage' stage: 'myotherstage' } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " " include: { stage: 'mystage' } " "} "; const string& output_proto = "state: { stage: 'mystage' } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " " include: { stage: 'mystage' } " "} "; this->RunFilterNetTest(input_proto, output_proto); } TEST_F(FilterNetTest, TestFilterInByMultipleStage) { const string& input_proto = "state: { stage: 'mystage' } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { stage: 'myotherstage' } " " include: { stage: 'mystage' } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " " include: { stage: 'mystage' } " "} "; this->RunFilterNetTest(input_proto, input_proto); } TEST_F(FilterNetTest, TestFilterInByMultipleStage2) { const string& input_proto = "state: { stage: 'mystage' stage: 'myotherstage' } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { stage: 'mystage' stage: 'myotherstage' } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " " include: { stage: 'mystage' } " "} "; this->RunFilterNetTest(input_proto, input_proto); } TEST_F(FilterNetTest, TestFilterInByNotStage) { const string& input_proto = "state: { stage: 'mystage' } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { not_stage: 'myotherstage' } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " " include: { not_stage: 'myotherstage' } " "} "; this->RunFilterNetTest(input_proto, input_proto); } TEST_F(FilterNetTest, TestFilterOutByNotStage) { const string& input_proto = "state: { stage: 'mystage' } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { not_stage: 'mystage' } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " " include: { not_stage: 'mystage' } " "} "; const string& output_proto = "state: { stage: 'mystage' } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} "; this->RunFilterNetTest(input_proto, output_proto); } TEST_F(FilterNetTest, TestFilterOutByMinLevel) { const string& input_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { min_level: 3 } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; const string& output_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; this->RunFilterNetTest(input_proto, output_proto); } TEST_F(FilterNetTest, TestFilterOutByMaxLevel) { const string& input_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { max_level: -3 } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; const string& output_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; this->RunFilterNetTest(input_proto, output_proto); } TEST_F(FilterNetTest, TestFilterInByMinLevel) { const string& input_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { min_level: 0 } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; this->RunFilterNetTest(input_proto, input_proto); } TEST_F(FilterNetTest, TestFilterInByMinLevel2) { const string& input_proto = "state: { level: 7 } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { min_level: 3 } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; this->RunFilterNetTest(input_proto, input_proto); } TEST_F(FilterNetTest, TestFilterInByMaxLevel) { const string& input_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { max_level: 0 } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; this->RunFilterNetTest(input_proto, input_proto); } TEST_F(FilterNetTest, TestFilterInByMaxLevel2) { const string& input_proto = "state: { level: -7 } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { max_level: -3 } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " "} "; this->RunFilterNetTest(input_proto, input_proto); } TEST_F(FilterNetTest, TestFilterInOutByIncludeMultiRule) { const string& input_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { min_level: 2 phase: TRAIN } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " " include: { min_level: 2 phase: TEST } " "} "; const string& input_proto_train = "state: { level: 4 phase: TRAIN } " + input_proto; const string& input_proto_test = "state: { level: 4 phase: TEST } " + input_proto; const string& output_proto_train = "state: { level: 4 phase: TRAIN } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { min_level: 2 phase: TRAIN } " "} "; const string& output_proto_test = "state: { level: 4 phase: TEST } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " " include: { min_level: 2 phase: TEST } " "} "; this->RunFilterNetTest(input_proto_train, output_proto_train); this->RunFilterNetTest(input_proto_test, output_proto_test); } TEST_F(FilterNetTest, TestFilterInByIncludeMultiRule) { const string& input_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " include: { min_level: 2 phase: TRAIN } " " include: { phase: TEST } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " " include: { min_level: 2 phase: TEST } " " include: { phase: TRAIN } " "} "; const string& input_proto_train = "state: { level: 2 phase: TRAIN } " + input_proto; const string& input_proto_test = "state: { level: 2 phase: TEST } " + input_proto; this->RunFilterNetTest(input_proto_train, input_proto_train); this->RunFilterNetTest(input_proto_test, input_proto_test); } TEST_F(FilterNetTest, TestFilterInOutByExcludeMultiRule) { const string& input_proto = "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " exclude: { min_level: 2 phase: TRAIN } " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " " exclude: { min_level: 2 phase: TEST } " "} "; const string& input_proto_train = "state: { level: 4 phase: TRAIN } " + input_proto; const string& input_proto_test = "state: { level: 4 phase: TEST } " + input_proto; const string& output_proto_train = "state: { level: 4 phase: TRAIN } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'loss' " " type: 'SoftmaxWithLoss' " " bottom: 'innerprod' " " bottom: 'label' " " exclude: { min_level: 2 phase: TEST } " "} "; const string& output_proto_test = "state: { level: 4 phase: TEST } " "name: 'TestNetwork' " "layer { " " name: 'data' " " type: 'Data' " " top: 'data' " " top: 'label' " "} " "layer { " " name: 'innerprod' " " type: 'InnerProduct' " " bottom: 'data' " " top: 'innerprod' " " exclude: { min_level: 2 phase: TRAIN } " "} "; this->RunFilterNetTest(input_proto_train, output_proto_train); this->RunFilterNetTest(input_proto_test, output_proto_test); } TYPED_TEST(NetTest, TestReshape) { typedef typename TypeParam::Dtype Dtype; // We set up bottom blobs of two different sizes, switch between // them, check that forward and backward both run and the results // are the same, and check that the output shapes change. Caffe::set_random_seed(this->seed_); Caffe::set_mode(Caffe::CPU); FillerParameter filler_param; filler_param.set_std(1); GaussianFiller<Dtype> filler(filler_param); // Check smaller shape first as larger first could hide realloc failures. Blob<Dtype> blob1(2, 3, 12, 10); Blob<Dtype> blob2(4, 3, 9, 11); ASSERT_LT(blob1.count(), blob2.count()); filler.Fill(&blob1); filler.Fill(&blob2); this->InitReshapableNet(); shared_ptr<Blob<Dtype> > input_blob = this->net_->blob_by_name("data"); Blob<Dtype>* output_blob = this->net_->output_blobs()[0]; input_blob->Reshape(blob1.num(), blob1.channels(), blob1.height(), blob1.width()); caffe_copy(blob1.count(), blob1.cpu_data(), input_blob->mutable_cpu_data()); this->net_->Forward(); // call backward just to make sure it runs this->net_->Backward(); Blob<Dtype> output1(output_blob->num(), output_blob->channels(), output_blob->height(), output_blob->width()); caffe_copy(output1.count(), output_blob->cpu_data(), output1.mutable_cpu_data()); input_blob->Reshape(blob2.num(), blob2.channels(), blob2.height(), blob2.width()); caffe_copy(blob2.count(), blob2.cpu_data(), input_blob->mutable_cpu_data()); this->net_->Forward(); this->net_->Backward(); Blob<Dtype> output2(output_blob->num(), output_blob->channels(), output_blob->height(), output_blob->width()); caffe_copy(output2.count(), output_blob->cpu_data(), output2.mutable_cpu_data()); input_blob->Reshape(blob1.num(), blob1.channels(), blob1.height(), blob1.width()); caffe_copy(blob1.count(), blob1.cpu_data(), input_blob->mutable_cpu_data()); this->net_->Forward(); this->net_->Backward(); for (int i = 0; i < output1.count(); ++i) { EXPECT_FLOAT_EQ(*(output1.cpu_data() + i), *(output_blob->cpu_data() + i)); } input_blob->Reshape(blob2.num(), blob2.channels(), blob2.height(), blob2.width()); caffe_copy(blob2.count(), blob2.cpu_data(), input_blob->mutable_cpu_data()); this->net_->Forward(); this->net_->Backward(); for (int i = 0; i < output2.count(); ++i) { EXPECT_FLOAT_EQ(*(output2.cpu_data() + i), *(output_blob->cpu_data() + i)); } EXPECT_EQ(output1.num(), blob1.num()); EXPECT_EQ(output2.num(), blob2.num()); bool same_spatial_shape = true; const int kFirstSpatialAxis = 2; for (int i = kFirstSpatialAxis; i < output1.num_axes(); ++i) { if (output1.shape(i) != output2.shape(i)) { same_spatial_shape = false; break; } } EXPECT_FALSE(same_spatial_shape); } TYPED_TEST(NetTest, TestSkipPropagateDown) { // check bottom_need_backward if propagate_down is true this->InitSkipPropNet(false); vector<bool> vec_layer_need_backward = this->net_->layer_need_backward(); for (int layer_id = 0; layer_id < this->net_->layers().size(); ++layer_id) { string layer_name = this->net_->layer_names()[layer_id]; if (layer_name == "loss") { // access to bottom_need_backward coresponding to label's blob bool need_back = this->net_->bottom_need_backward()[layer_id][1]; // if propagate_down is true, the loss layer will try to // backpropagate on labels EXPECT_TRUE(need_back) << "bottom_need_backward should be True"; } // layer_need_backward should be True except for data and silence layers if (layer_name.find("data") != std::string::npos || layer_name == "silence") { EXPECT_FALSE(vec_layer_need_backward[layer_id]) << "layer_need_backward for " << layer_name << " should be False"; } else { EXPECT_TRUE(vec_layer_need_backward[layer_id]) << "layer_need_backward for " << layer_name << " should be True"; } } // check bottom_need_backward if propagat_down is false this->InitSkipPropNet(true); vec_layer_need_backward.clear(); vec_layer_need_backward = this->net_->layer_need_backward(); for (int layer_id = 0; layer_id < this->net_->layers().size(); ++layer_id) { string layer_name = this->net_->layer_names()[layer_id]; if (layer_name == "loss") { // access to bottom_need_backward coresponding to label's blob bool need_back = this->net_->bottom_need_backward()[layer_id][1]; // if propagate_down is false, the loss layer will not try to // backpropagate on labels EXPECT_FALSE(need_back) << "bottom_need_backward should be False"; } // layer_need_backward should be False except for innerproduct and // loss layers if (layer_name == "innerproduct" || layer_name == "loss") { EXPECT_TRUE(vec_layer_need_backward[layer_id]) << "layer_need_backward for " << layer_name << " should be True"; } else { EXPECT_FALSE(vec_layer_need_backward[layer_id]) << "layer_need_backward for " << layer_name << " should be False"; } } } TYPED_TEST(NetTest, TestForcePropagateDown) { this->InitForcePropNet(false); vector<bool> layer_need_backward = this->net_->layer_need_backward(); for (int layer_id = 0; layer_id < this->net_->layers().size(); ++layer_id) { const string& layer_name = this->net_->layer_names()[layer_id]; const vector<bool> need_backward = this->net_->bottom_need_backward()[layer_id]; if (layer_name == "data") { ASSERT_EQ(need_backward.size(), 0); EXPECT_FALSE(layer_need_backward[layer_id]); } else if (layer_name == "innerproduct") { ASSERT_EQ(need_backward.size(), 1); EXPECT_FALSE(need_backward[0]); // data EXPECT_TRUE(layer_need_backward[layer_id]); } else if (layer_name == "loss") { ASSERT_EQ(need_backward.size(), 2); EXPECT_TRUE(need_backward[0]); // innerproduct EXPECT_FALSE(need_backward[1]); // label EXPECT_TRUE(layer_need_backward[layer_id]); } else { LOG(FATAL) << "Unknown layer: " << layer_name; } } this->InitForcePropNet(true); layer_need_backward = this->net_->layer_need_backward(); for (int layer_id = 0; layer_id < this->net_->layers().size(); ++layer_id) { const string& layer_name = this->net_->layer_names()[layer_id]; const vector<bool> need_backward = this->net_->bottom_need_backward()[layer_id]; if (layer_name == "data") { ASSERT_EQ(need_backward.size(), 0); EXPECT_FALSE(layer_need_backward[layer_id]); } else if (layer_name == "innerproduct") { ASSERT_EQ(need_backward.size(), 1); EXPECT_TRUE(need_backward[0]); // data EXPECT_TRUE(layer_need_backward[layer_id]); } else if (layer_name == "loss") { ASSERT_EQ(need_backward.size(), 2); EXPECT_TRUE(need_backward[0]); // innerproduct EXPECT_FALSE(need_backward[1]); // label EXPECT_TRUE(layer_need_backward[layer_id]); } else { LOG(FATAL) << "Unknown layer: " << layer_name; } } } TYPED_TEST(NetTest, TestAllInOneNetTrain) { vector<string> stages; stages.push_back("train"); this->InitAllInOneNet(caffe::TRAIN, 0, &stages); bool found_data = false; bool found_loss = false; for (int i = 0; i < this->net_->layers().size(); ++i) { const string& layer_name = this->net_->layer_names()[i]; if (layer_name == "train-data") { found_data = true; } else if (layer_name == "loss") { found_loss = true; } else { ASSERT_NE(layer_name, "val-data"); ASSERT_NE(layer_name, "deploy-data"); } } ASSERT_TRUE(found_data); ASSERT_TRUE(found_loss); } TYPED_TEST(NetTest, TestAllInOneNetVal) { vector<string> stages; stages.push_back("val"); this->InitAllInOneNet(caffe::TEST, 0, &stages); bool found_data = false; bool found_loss = false; for (int i = 0; i < this->net_->layers().size(); ++i) { const string& layer_name = this->net_->layer_names()[i]; if (layer_name == "val-data") { found_data = true; } else if (layer_name == "loss") { found_loss = true; } else { ASSERT_NE(layer_name, "train-data"); ASSERT_NE(layer_name, "deploy-data"); } } ASSERT_TRUE(found_data); ASSERT_TRUE(found_loss); } TYPED_TEST(NetTest, TestAllInOneNetDeploy) { vector<string> stages; stages.push_back("deploy"); this->InitAllInOneNet(caffe::TEST, 0, &stages); bool found_data = false; for (int i = 0; i < this->net_->layers().size(); ++i) { const string& layer_name = this->net_->layer_names()[i]; if (layer_name == "deploy-data") { found_data = true; } else { ASSERT_NE(layer_name, "train-data"); ASSERT_NE(layer_name, "val-data"); ASSERT_NE(layer_name, "loss"); } } ASSERT_TRUE(found_data); } /* //INT8 Edited TYPED_TEST(NetTest, TestInt8BinaryProtoRead) { float activation_scale_factor = 0.7; float weight_scale_factor[4] = {10.2, 7.5, 254.2, 785.2}; int output_num = 4; NetParameter net_in; net_in.clear_layer(); LayerParameter& layer_in = net_in.add_layer(); layer_in.clear_blobs(); BlobProto& weight_blob_in = layer_in.add_blobs(); BlobProto& bias_blob_in = layer_in.add_blobs(); layer_in.set_int8_inference(true); layer_in.set_activation_scale_factor(activation_scale_factor); layer_in.clear_weight_scale_factor(); for(int i=0;i<output_num;i++){ layer_in.add_weight_scale_factor(weight_scale_factor[i]); } WriteProtoToBinaryFile(net_in, "dump.caffemodel"); NetParameter net_out; ReadProtoFromBinaryFile("dump.caffemodel", &net_out); ; */ } // namespace caffe
[ "gmlakd4u@naver.com" ]
gmlakd4u@naver.com
9a1bae8c86179dc5ae50026dffc4cb860720c3ef
46b545e71a559686107cc397d9ba2c77e958db09
/src/io.cpp
2d80933ceb52f6ce8e53d6ed56564c76af6bec6d
[]
no_license
ZhitingHu/DITREE
c50195e5e49a2bcb8922d84bac3f16e9bfc1b96c
0e01b3b7093ec5c40e035150fc018a54a681f804
refs/heads/master
2021-01-10T21:11:59.192884
2017-03-15T17:13:16
2017-03-15T17:13:16
28,940,605
3
0
null
null
null
null
UTF-8
C++
false
false
2,594
cpp
#include <fcntl.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #include <stdint.h> #include <algorithm> #include <fstream> // NOLINT(readability/streams) #include <string> #include <vector> #include "common.hpp" #include "datum.hpp" #include "proto/ditree.pb.h" #include "io.hpp" namespace ditree { using google::protobuf::io::FileInputStream; using google::protobuf::io::FileOutputStream; using google::protobuf::io::ZeroCopyInputStream; using google::protobuf::io::CodedInputStream; using google::protobuf::io::ZeroCopyOutputStream; using google::protobuf::io::CodedOutputStream; using google::protobuf::Message; bool CheckFileExistence(const char* filename) { int fd = open(filename, O_RDONLY); bool exist = (fd == -1 ? false : true); if (exist) { close(fd); } return exist; } //bool ReadStringIntMap(const char* filename, map<string, int>& st_int_map) { // ifstream input(filename, ios::in); // CHECK(input.is_open()) << "File not found: " << filename; // string st; // int value; // while (input >> st >> value) { //#ifdef DEBUG // CHECK(st_int_map.find(st) != st_int_map.end()); //#endif // st_int_map[st] = value; // } // input.close(); // return true; //} bool ReadProtoFromTextFile(const char* filename, Message* proto) { int fd = open(filename, O_RDONLY); CHECK_NE(fd, -1) << "File not found: " << filename; FileInputStream* input = new FileInputStream(fd); bool success = google::protobuf::TextFormat::Parse(input, proto); delete input; close(fd); return success; } void WriteProtoToTextFile(const Message& proto, const char* filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644); FileOutputStream* output = new FileOutputStream(fd); CHECK(google::protobuf::TextFormat::Print(proto, output)); delete output; close(fd); } bool ReadProtoFromBinaryFile(const char* filename, Message* proto) { int fd = open(filename, O_RDONLY); CHECK_NE(fd, -1) << "File not found: " << filename; ZeroCopyInputStream* raw_input = new FileInputStream(fd); CodedInputStream* coded_input = new CodedInputStream(raw_input); coded_input->SetTotalBytesLimit(1073741824, 536870912); bool success = proto->ParseFromCodedStream(coded_input); delete coded_input; delete raw_input; close(fd); return success; } void WriteProtoToBinaryFile(const Message& proto, const char* filename) { fstream output(filename, ios::out | ios::trunc | ios::binary); CHECK(proto.SerializeToOstream(&output)); } } // namespace ditree
[ "zhitingh@cogito.ml.cmu.edu" ]
zhitingh@cogito.ml.cmu.edu
bdaa451a1af4e09df9ffdc9326ec47d3413b1f66
56bcffceb734a9de899362391b2e44916d6ff7c0
/DesignPattern/DecoratorLib/DecoratorLib/FileStream.cpp
5ff46a80b71f5a9d8fc2b4530b6d94ebe33c1d79
[]
no_license
deeplin/CppProjects
f136a8111dc74b49621369b843d6ec2d1f02c9c4
935b31c7b3dd83c85a3b59432bd70a69de0a3635
refs/heads/master
2023-03-19T05:21:14.240646
2021-03-11T07:51:22
2021-03-11T07:51:22
341,447,276
0
0
null
null
null
null
UTF-8
C++
false
false
76
cpp
#include "FileStream.h" string FileStream::operation() { return "file"; }
[ "10525677@qq.com" ]
10525677@qq.com
addd4ec28ba80310e4df1ee972c642348b626523
fbbc663c607c9687452fa3192b02933b9eb3656d
/tags/1.22.01.00/mptrack/Globals.cpp
70bf9192b1187556930c3496ee92fb79efb20fe2
[ "BSD-3-Clause" ]
permissive
svn2github/OpenMPT
594837f3adcb28ba92a324e51c6172a8c1e8ea9c
a2943f028d334a8751b9f16b0512a5e0b905596a
refs/heads/master
2021-07-10T05:07:18.298407
2019-01-19T10:27:21
2019-01-19T10:27:21
106,434,952
2
1
null
null
null
null
UTF-8
C++
false
false
18,837
cpp
/* * globals.cpp * ----------- * Purpose: Implementation of various views of the tracker interface. * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "mptrack.h" #include "mainfrm.h" #include "moddoc.h" #include "childfrm.h" #include "globals.h" #include "ctrl_gen.h" #include "ctrl_pat.h" #include "ctrl_smp.h" #include "ctrl_ins.h" #include "ctrl_com.h" //#include "ctrl_graph.h" //rewbs.graph #include "globals.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CModControlDlg BEGIN_MESSAGE_MAP(CModControlDlg, CDialog) //{{AFX_MSG_MAP(CModControlDlg) ON_WM_SIZE() ON_MESSAGE(WM_MOD_UNLOCKCONTROLS, OnUnlockControls) ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnToolTipText) ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnToolTipText) //}}AFX_MSG_MAP END_MESSAGE_MAP() CModControlDlg::CModControlDlg() //------------------------------ { m_pParent = NULL; m_pModDoc = NULL; m_pSndFile = NULL; m_bInitialized = FALSE; m_hWndView = NULL; m_nLockCount = 0; } CModControlDlg::~CModControlDlg() //------------------------------- { ASSERT(m_hWnd == NULL); } BOOL CModControlDlg::OnInitDialog() //--------------------------------- { CDialog::OnInitDialog(); EnableToolTips(TRUE); return TRUE; } void CModControlDlg::OnSize(UINT nType, int cx, int cy) //----------------------------------------------------- { CDialog::OnSize(nType, cx, cy); if (((nType == SIZE_RESTORED) || (nType == SIZE_MAXIMIZED)) && (cx > 0) && (cy > 0)) { RecalcLayout(); } } LRESULT CModControlDlg::OnModCtrlMsg(WPARAM wParam, LPARAM lParam) //---------------------------------------------------------------- { switch(wParam) { case CTRLMSG_SETVIEWWND: m_hWndView = (HWND)lParam; break; case CTRLMSG_ACTIVATEPAGE: OnActivatePage(lParam); break; case CTRLMSG_DEACTIVATEPAGE: OnDeactivatePage(); break; } return 0; } LRESULT CModControlDlg::SendViewMessage(UINT uMsg, LPARAM lParam) const //--------------------------------------------------------------------- { if (m_hWndView) return ::SendMessage(m_hWndView, WM_MOD_VIEWMSG, uMsg, lParam); return 0; } BOOL CModControlDlg::PostViewMessage(UINT uMsg, LPARAM lParam) const //------------------------------------------------------------------ { if (m_hWndView) return ::PostMessage(m_hWndView, WM_MOD_VIEWMSG, uMsg, lParam); return FALSE; } int CModControlDlg::OnToolHitTest(CPoint point, TOOLINFO* pTI) const //------------------------------------------------------------------ { int nHit = CDialog::OnToolHitTest(point, pTI); if ((nHit >= 0) && (pTI)) { if ((pTI->lpszText == LPSTR_TEXTCALLBACK) && (pTI->hwnd == m_hWnd)) { CFrameWnd *pMDIParent = GetParentFrame(); if (pMDIParent) pTI->hwnd = pMDIParent->m_hWnd; } } return nHit; } BOOL CModControlDlg::OnToolTipText(UINT nID, NMHDR* pNMHDR, LRESULT* pResult) //--------------------------------------------------------------------------- { CChildFrame *pChildFrm = (CChildFrame *)GetParentFrame(); if (pChildFrm) return pChildFrm->OnToolTipText(nID, pNMHDR, pResult); if (pResult) *pResult = 0; return FALSE; } ///////////////////////////////////////////////////////////////////////////// // CModControlView BOOL CModTabCtrl::Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID) //----------------------------------------------------------------------------------- { CMainFrame *pMainFrm = CMainFrame::GetMainFrame(); if (!pMainFrm) return FALSE; if (!CTabCtrl::Create(dwStyle, rect, pParentWnd, nID)) return FALSE; SendMessage(WM_SETFONT, (WPARAM)pMainFrm->GetGUIFont()); SetImageList(pMainFrm->GetImageList()); return TRUE; } BOOL CModTabCtrl::InsertItem(int nIndex, LPSTR pszText, LPARAM lParam, int iImage) //-------------------------------------------------------------------------------- { TC_ITEM tci; tci.mask = TCIF_TEXT | TCIF_PARAM | TCIF_IMAGE; tci.pszText = pszText; tci.lParam = lParam; tci.iImage = iImage; return CTabCtrl::InsertItem(nIndex, &tci); } UINT CModTabCtrl::GetItemData(int nIndex) //--------------------------------------- { TC_ITEM tci; tci.mask = TCIF_PARAM; tci.lParam = 0; if (!GetItem(nIndex, &tci)) return 0; return tci.lParam; } ///////////////////////////////////////////////////////////////////////////////// // CModControlView IMPLEMENT_DYNCREATE(CModControlView, CView) BEGIN_MESSAGE_MAP(CModControlView, CView) //{{AFX_MSG_MAP(CModControlView) ON_WM_SIZE() ON_WM_DESTROY() ON_WM_ERASEBKGND() ON_NOTIFY(TCN_SELCHANGE, IDC_TABCTRL1, OnTabSelchange) ON_MESSAGE(WM_MOD_ACTIVATEVIEW, OnActivateModView) ON_MESSAGE(WM_MOD_CTRLMSG, OnModCtrlMsg) ON_MESSAGE(WM_MOD_GETTOOLTIPTEXT, OnGetToolTipText) ON_COMMAND(ID_EDIT_CUT, OnEditCut) ON_COMMAND(ID_EDIT_COPY, OnEditCopy) ON_COMMAND(ID_EDIT_PASTE, OnEditPaste) ON_COMMAND(ID_EDIT_MIXPASTE, OnEditMixPaste) ON_COMMAND(ID_EDIT_MIXPASTE_ITSTYLE, OnEditMixPasteITStyle) ON_COMMAND(ID_EDIT_FIND, OnEditFind) ON_COMMAND(ID_EDIT_FINDNEXT, OnEditFindNext) ON_COMMAND(ID_CONTROLTAB, OnSwitchToView) //}}AFX_MSG_MAP END_MESSAGE_MAP() CModControlView::CModControlView() //-------------------------------- { MemsetZero(m_Pages); m_nActiveDlg = -1; m_nInstrumentChanged = -1; m_hWndView = NULL; m_hWndMDI = NULL; } BOOL CModControlView::PreCreateWindow(CREATESTRUCT& cs) //----------------------------------------------------- { return CView::PreCreateWindow(cs); } void CModControlView::OnInitialUpdate() // called first time after construct //------------------------------------- { CRect rect; CChildFrame *pParentFrame = (CChildFrame *)GetParentFrame(); if (pParentFrame) m_hWndView = pParentFrame->GetHwndView(); GetClientRect(&rect); m_TabCtrl.Create(WS_CHILD|WS_VISIBLE|TCS_FOCUSNEVER|TCS_FORCELABELLEFT, rect, this, IDC_TABCTRL1); UpdateView(HINT_MODTYPE); SetActivePage(0); } void CModControlView::OnSize(UINT nType, int cx, int cy) //------------------------------------------------------ { CView::OnSize(nType, cx, cy); if (((nType == SIZE_RESTORED) || (nType == SIZE_MAXIMIZED)) && (cx > 0) && (cy > 0)) { RecalcLayout(); } } void CModControlView::RecalcLayout() //---------------------------------- { CRect rcClient; if (m_TabCtrl.m_hWnd == NULL) return; GetClientRect(&rcClient); if ((m_nActiveDlg >= 0) && (m_nActiveDlg < MAX_PAGES) && (m_Pages[m_nActiveDlg])) { CWnd *pDlg = m_Pages[m_nActiveDlg]; CRect rect = rcClient; m_TabCtrl.AdjustRect(FALSE, &rect); HDWP hdwp = BeginDeferWindowPos(2); DeferWindowPos(hdwp, m_TabCtrl.m_hWnd, NULL, rcClient.left, rcClient.top, rcClient.Width(), rcClient.Height(), SWP_NOZORDER); DeferWindowPos(hdwp, pDlg->m_hWnd, NULL, rect.left, rect.top, rect.Width(), rect.Height(), SWP_NOZORDER); EndDeferWindowPos(hdwp); } else { m_TabCtrl.MoveWindow(&rcClient); } } void CModControlView::OnUpdate(CView*, LPARAM lHint, CObject*pHint) //----------------------------------------------------------------- { UpdateView(lHint, pHint); } void CModControlView::ForceRefresh() //--------------------------------- { SetActivePage(GetActivePage()); } int CModControlView::GetActivePage() //----------------------------------- { return m_nActiveDlg; } BOOL CModControlView::SetActivePage(int nIndex, LPARAM lParam) //------------------------------------------------------------ { CMainFrame *pMainFrm = CMainFrame::GetMainFrame(); CModControlDlg *pDlg = NULL; if (nIndex == -1) nIndex = m_TabCtrl.GetCurSel(); const UINT nID = m_TabCtrl.GetItemData(nIndex); if(nID == 0) return FALSE; switch(nID) { //rewbs.graph case IDD_CONTROL_GRAPH: nIndex = 5; break; //end rewbs.graph case IDD_CONTROL_COMMENTS: nIndex = 4; break; case IDD_CONTROL_GLOBALS: nIndex = 0; break; case IDD_CONTROL_PATTERNS: nIndex = 1; break; case IDD_CONTROL_SAMPLES: nIndex = 2; break; case IDD_CONTROL_INSTRUMENTS: nIndex = 3; break; default: return FALSE; } if ((nIndex < 0) || (nIndex >= MAX_PAGES) || (!pMainFrm)) return FALSE; //rewbs.varWindowSize if (m_Pages[m_nActiveDlg]) *(m_Pages[m_nActiveDlg]->GetSplitPosRef()) = ((CChildFrame *)GetParentFrame())->GetSplitterHeight(); if (nIndex == m_nActiveDlg) { pDlg = m_Pages[m_nActiveDlg]; PostMessage(WM_MOD_CTRLMSG, CTRLMSG_ACTIVATEPAGE, lParam); return TRUE; } if ((m_nActiveDlg >= 0) && (m_nActiveDlg < MAX_PAGES)) { if (m_Pages[m_nActiveDlg]) { OnModCtrlMsg(CTRLMSG_DEACTIVATEPAGE, 0); m_Pages[m_nActiveDlg]->ShowWindow(SW_HIDE); } m_nActiveDlg = -1; } if (m_Pages[nIndex]) //Ctrl window already created? { m_nActiveDlg = nIndex; pDlg = m_Pages[nIndex]; } else //Ctrl window is not created yet - creating one. { switch(nID) { //rewbs.graph case IDD_CONTROL_GRAPH: //pDlg = new CCtrlGraph(); break; //end rewbs.graph case IDD_CONTROL_COMMENTS: pDlg = new CCtrlComments(); break; case IDD_CONTROL_GLOBALS: pDlg = new CCtrlGeneral(); break; case IDD_CONTROL_PATTERNS: pDlg = new CCtrlPatterns(); break; case IDD_CONTROL_SAMPLES: pDlg = new CCtrlSamples(); break; case IDD_CONTROL_INSTRUMENTS: pDlg = new CCtrlInstruments(); break; default: return FALSE; } if (!pDlg) return FALSE; pDlg->SetDocument(GetDocument(), this); pDlg->SetViewWnd(m_hWndView); BOOL bStatus = pDlg->Create(nID, this); if(bStatus == 0) // Creation failed. { delete pDlg; return FALSE; } m_nActiveDlg = nIndex; m_Pages[nIndex] = pDlg; } RecalcLayout(); pMainFrm->SetUserText(""); pMainFrm->SetInfoText(""); pMainFrm->SetXInfoText(""); //rewbs.xinfo pDlg->ShowWindow(SW_SHOW); ((CChildFrame *)GetParentFrame())->SetSplitterHeight(*(pDlg->GetSplitPosRef())); //rewbs.varWindowSize if (m_hWndMDI) ::PostMessage(m_hWndMDI, WM_MOD_CHANGEVIEWCLASS, (WPARAM)lParam, (LPARAM)pDlg); return TRUE; } void CModControlView::OnDestroy() //------------------------------- { m_nActiveDlg = -1; for (UINT nIndex=0; nIndex<MAX_PAGES; nIndex++) { CModControlDlg *pDlg = m_Pages[nIndex]; if (pDlg) { m_Pages[nIndex] = NULL; pDlg->DestroyWindow(); delete pDlg; } } CView::OnDestroy(); } void CModControlView::UpdateView(DWORD lHint, CObject *pObject) //------------------------------------------------------------- { CWnd *pActiveDlg = NULL; CModDoc *pDoc = GetDocument(); if (!pDoc) return; // Module type changed: update tabs if (lHint & HINT_MODTYPE) { CSoundFile *pSndFile = pDoc->GetSoundFile(); UINT nCount = 4; UINT nType = pSndFile->GetType(); UINT mask = 1 | 2 | 4 | 16; if (nType & (MOD_TYPE_XM|MOD_TYPE_IT|MOD_TYPE_MPT)) { mask |= 8; //mask |= 32; //rewbs.graph nCount ++; } if (nCount != (UINT)m_TabCtrl.GetItemCount()) { UINT count = 0; if ((m_nActiveDlg >= 0) && (m_nActiveDlg < MAX_PAGES)) { pActiveDlg = m_Pages[m_nActiveDlg]; if (pActiveDlg) pActiveDlg->ShowWindow(SW_HIDE); } m_TabCtrl.DeleteAllItems(); if (mask & 1) m_TabCtrl.InsertItem(count++, "General", IDD_CONTROL_GLOBALS, IMAGE_GENERAL); if (mask & 2) m_TabCtrl.InsertItem(count++, "Patterns", IDD_CONTROL_PATTERNS, IMAGE_PATTERNS); if (mask & 4) m_TabCtrl.InsertItem(count++, "Samples", IDD_CONTROL_SAMPLES, IMAGE_SAMPLES); if (mask & 8) m_TabCtrl.InsertItem(count++, "Instruments", IDD_CONTROL_INSTRUMENTS, IMAGE_INSTRUMENTS); if (mask & 32) m_TabCtrl.InsertItem(count++, "Graph", IDD_CONTROL_GRAPH, IMAGE_GRAPH); //rewbs.graph if (mask & 16) m_TabCtrl.InsertItem(count++, "Comments", IDD_CONTROL_COMMENTS, IMAGE_COMMENTS); } } // Update child dialogs for (UINT nIndex=0; nIndex<MAX_PAGES; nIndex++) { CModControlDlg *pDlg = m_Pages[nIndex]; if ((pDlg) && (pObject != pDlg)) pDlg->UpdateView(lHint, pObject); } // Restore the displayed child dialog if (pActiveDlg) pActiveDlg->ShowWindow(SW_SHOW); } void CModControlView::OnTabSelchange(NMHDR*, LRESULT* pResult) //------------------------------------------------------------ { SetActivePage(m_TabCtrl.GetCurSel()); if (pResult) *pResult = 0; } LRESULT CModControlView::OnActivateModView(WPARAM nIndex, LPARAM lParam) //---------------------------------------------------------------------- { if (m_TabCtrl.m_hWnd) { if (nIndex < 100) { m_TabCtrl.SetCurSel(nIndex); SetActivePage(nIndex, lParam); } else // Might be a dialog id IDD_XXXX { int nItems = m_TabCtrl.GetItemCount(); for (int i=0; i<nItems; i++) { if (m_TabCtrl.GetItemData(i) == nIndex) { m_TabCtrl.SetCurSel(i); SetActivePage(i, lParam); break; } } } } return 0; } LRESULT CModControlView::OnModCtrlMsg(WPARAM wParam, LPARAM lParam) //----------------------------------------------------------------- { if ((m_nActiveDlg >= 0) && (m_nActiveDlg < MAX_PAGES)) { CModControlDlg *pActiveDlg = m_Pages[m_nActiveDlg]; if (pActiveDlg) { switch(wParam) { case CTRLMSG_SETVIEWWND: { m_hWndView = (HWND)lParam; for (UINT i=0; i<MAX_PAGES; i++) { if (m_Pages[i]) m_Pages[i]->SetViewWnd(m_hWndView); } } break; } return pActiveDlg->OnModCtrlMsg(wParam, lParam); } } return 0; } LRESULT CModControlView::OnGetToolTipText(WPARAM uId, LPARAM pszText) //------------------------------------------------------------------- { if ((m_nActiveDlg >= 0) && (m_nActiveDlg < MAX_PAGES)) { CModControlDlg *pActiveDlg = m_Pages[m_nActiveDlg]; if (pActiveDlg) return (LRESULT)pActiveDlg->GetToolTipText(uId, (LPSTR)pszText); } return 0; } ////////////////////////////////////////////////////////////////// // CModScrollView IMPLEMENT_SERIAL(CModScrollView, CScrollView, 0) BEGIN_MESSAGE_MAP(CModScrollView, CScrollView) //{{AFX_MSG_MAP(CModScrollView) ON_WM_DESTROY() ON_WM_MOUSEWHEEL() ON_MESSAGE(WM_MOD_VIEWMSG, OnReceiveModViewMsg) ON_MESSAGE(WM_MOD_DRAGONDROPPING, OnDragonDropping) ON_MESSAGE(WM_MOD_UPDATEPOSITION, OnUpdatePosition) //}}AFX_MSG_MAP END_MESSAGE_MAP() LRESULT CModScrollView::SendCtrlMessage(UINT uMsg, LPARAM lParam) const //--------------------------------------------------------------------- { if (m_hWndCtrl) return ::SendMessage(m_hWndCtrl, WM_MOD_CTRLMSG, uMsg, lParam); return 0; } BOOL CModScrollView::PostCtrlMessage(UINT uMsg, LPARAM lParam) const //------------------------------------------------------------------ { if (m_hWndCtrl) return ::PostMessage(m_hWndCtrl, WM_MOD_CTRLMSG, uMsg, lParam); return FALSE; } LRESULT CModScrollView::OnReceiveModViewMsg(WPARAM wParam, LPARAM lParam) //----------------------------------------------------------------------- { return OnModViewMsg(wParam, lParam); } void CModScrollView::OnUpdate(CView* pView, LPARAM lHint, CObject*pHint) //---------------------------------------------------------------------- { if (pView != this) UpdateView(lHint, pHint); } LRESULT CModScrollView::OnModViewMsg(WPARAM wParam, LPARAM lParam) //---------------------------------------------------------------- { switch(wParam) { case VIEWMSG_SETCTRLWND: m_hWndCtrl = (HWND)lParam; break; case VIEWMSG_SETFOCUS: case VIEWMSG_SETACTIVE: GetParentFrame()->SetActiveView(this); SetFocus(); break; } return 0; } void CModScrollView::UpdateIndicator(LPCSTR lpszText) //--------------------------------------------------- { CMainFrame *pMainFrm = CMainFrame::GetMainFrame(); if (pMainFrm) pMainFrm->SetUserText((lpszText) ? lpszText : ""); } BOOL CModScrollView::OnMouseWheel(UINT fFlags, short zDelta, CPoint point) //------------------------------------------------------------------------ { // we don't handle anything but scrolling just now if (fFlags & (MK_SHIFT | MK_CONTROL)) return FALSE; //if the parent is a splitter, it will handle the message //if (GetParentSplitter(this, TRUE)) return FALSE; // we can't get out of it--perform the scroll ourselves return DoMouseWheel(fFlags, zDelta, point); } void CModScrollView::OnDestroy() //------------------------------ { CModDoc *pModDoc = GetDocument(); CMainFrame *pMainFrm = CMainFrame::GetMainFrame(); if ((pMainFrm) && (pModDoc)) { if (pMainFrm->GetFollowSong(pModDoc) == m_hWnd) { pMainFrm->SetFollowSong(pModDoc, NULL, FALSE); pModDoc->SetFollowWnd(NULL, 0); } if (pMainFrm->GetMidiRecordWnd() == m_hWnd) { pMainFrm->SetMidiRecordWnd(NULL); } } CScrollView::OnDestroy(); } LRESULT CModScrollView::OnUpdatePosition(WPARAM, LPARAM lParam) //------------------------------------------------------------- { MPTNOTIFICATION *pnotify = (MPTNOTIFICATION *)lParam; if (pnotify) return OnPlayerNotify(pnotify); return 0; } //////////////////////////////////////////////////////////////////////////// // CModControlBar BEGIN_MESSAGE_MAP(CModControlBar, CToolBarCtrl) ON_MESSAGE(WM_HELPHITTEST, OnHelpHitTest) END_MESSAGE_MAP() CModControlBar::~CModControlBar() //------------------------------- { if (m_hBarBmp) { DeleteObject(m_hBarBmp); m_hBarBmp = NULL; } } BOOL CModControlBar::Init(UINT nId) //--------------------------------- { HINSTANCE hInstance = AfxGetInstanceHandle(); TBADDBITMAP tbab; SetButtonStructSize(sizeof(TBBUTTON)); SetBitmapSize(CSize(16, 15)); SetButtonSize(CSize(27, 24)); // Add bitmaps m_hBarBmp = AfxLoadSysColorBitmap( hInstance, ::FindResource(hInstance, MAKEINTRESOURCE(nId), RT_BITMAP)); tbab.hInst = NULL; tbab.nID = (UINT)m_hBarBmp; ::SendMessage(m_hWnd, TB_ADDBITMAP, 16, (LPARAM)&tbab); UpdateStyle(); return TRUE; } BOOL CModControlBar::AddButton(UINT nID, int iImage, UINT nStyle, UINT nState) //---------------------------------------------------------------------------- { TBBUTTON btn; btn.iBitmap = iImage; btn.idCommand = nID; btn.fsStyle = (BYTE)nStyle; btn.fsState = (BYTE)nState; btn.dwData = 0; btn.iString = 0; return AddButtons(1, &btn); } void CModControlBar::UpdateStyle() //-------------------------------- { if (m_hWnd) { LONG lStyleOld = GetWindowLong(m_hWnd, GWL_STYLE); if (TrackerSettings::Instance().m_dwPatternSetup & PATTERN_FLATBUTTONS) lStyleOld |= TBSTYLE_FLAT; else lStyleOld &= ~TBSTYLE_FLAT; lStyleOld |= CCS_NORESIZE | CCS_NOPARENTALIGN | CCS_NODIVIDER | TBSTYLE_TOOLTIPS; SetWindowLong(m_hWnd, GWL_STYLE, lStyleOld); Invalidate(); } } LRESULT CModControlBar::OnHelpHitTest(WPARAM, LPARAM lParam) //---------------------------------------------------------- { TBBUTTON tbbn; POINT point; point.x = (signed short)(LOWORD(lParam)); point.y = (signed short)(HIWORD(lParam)); int ndx = HitTest(&point); if ((ndx >= 0) && (GetButton(ndx, &tbbn))) { return HID_BASE_COMMAND + tbbn.idCommand; } return 0; }
[ "saga-games@56274372-70c3-4bfc-bfc3-4c3a0b034d27" ]
saga-games@56274372-70c3-4bfc-bfc3-4c3a0b034d27
86ce67638cd3567f45d5fe085568b4e5098d1f84
749b14133fb70f7424e494ca75dd45092ea99ead
/src/math/plane.cpp
652c09f2d2c158a6a9b8e6d9614e4d358c7d0643
[]
no_license
mhernando/MRCore
474036a049b99a99fd4f8bfe780dcfe5596b1efc
5a0aa0e0a80c3eafe3a40fac1bcae03ce5fa3534
refs/heads/master
2021-11-29T01:44:17.060973
2021-11-22T11:23:51
2021-11-22T11:23:51
53,126,147
2
0
null
null
null
null
ISO-8859-2
C++
false
false
4,784
cpp
/********************************************************************** * * This code is part of the MRcore project * Author: Miguel Hernando & Diego Rodríguez-Losada * * MRcore is licenced under the Common Creative License, * Attribution-NonCommercial-ShareAlike 3.0 * * You are free: * - to Share - to copy, distribute and transmit the work * - to Remix - to adapt the work * * Under the following conditions: * - Attribution. You must attribute the work in the manner specified * by the author or licensor (but not in any way that suggests that * they endorse you or your use of the work). * - Noncommercial. You may not use this work for commercial purposes. * - Share Alike. If you alter, transform, or build upon this work, * you may distribute the resulting work only under the same or * similar license to this one. * * Any of the above conditions can be waived if you get permission * from the copyright holder. Nothing in this license impairs or * restricts the author's moral rights. * * It 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. **********************************************************************/ #include "plane.h" #include "mrmath.h" #include "../math/angle.h" #include <math.h> #include "gl/gltools.h" namespace mr{ IMPLEMENT_MR_OBJECT(Plane) ostream& operator<<(ostream& os, const Plane& p) { os<<"Origin: "<<p.origin<<endl; os<<"Normal: "<<p.normal<<endl; return os; } Plane::Plane():normal(1,0,0) { } Plane::Plane(Vector3D cg, Vector3D nor):origin(cg),normal(nor) { normal.normalize(); } Plane::~Plane() { } Plane::Plane(Vector3D p1, Vector3D p2, Vector3D p3) { Vector3D v1=p1-p2; Vector3D v2=p3-p2; Vector3D norm=v1.cross(v2);//v1 x v2 normal=norm.normalize(); origin=(p1+p2+p3)/3.0; } void Plane::writeToStream(Stream& stream) { stream<<normal.x<<normal.y<<normal.z; stream<<origin.x<<origin.y<<origin.z; } void Plane::readFromStream(Stream& stream) { stream>>normal.x>>normal.y>>normal.z; stream>>origin.x>>origin.y>>origin.z; } double Plane::distance(const Vector3D& point) const { double a=normal.x; double b=normal.y; double c=normal.z; double d=-a*origin.x-b*origin.y-c*origin.z; double dist=a*point.x+b*point.y+c*point.z+d; //dist/=normal.Module();//The normal has to be Unitary return fabs(dist); } void Plane::LSQFit(const std::vector<Vector3D>& points, double* res) { /* float sx=0;float sy=0;float sz=0; float sx2=0;float sy2=0;float sz2=0; float sxy=0;float sxz=0;float syz=0; int num = points.size(); int i; for (i=0;i<num;i++) { sx+=points[i].x; sy+=points[i].y; sz+=points[i].z; } origin.x=sx/num; origin.y=sy/num; origin.z=sz/num; for (i=0; i<num;i++) { sx2+=(points[i].x-origin.x)*(points[i].x-origin.x); sy2+=(points[i].y-origin.y)*(points[i].y-origin.y); sz2+=(points[i].z-origin.z)*(points[i].z-origin.z); sxy+=(points[i].x-origin.x)*(points[i].y-origin.y); sxz+=(points[i].x-origin.x)*(points[i].z-origin.z); syz+=(points[i].y-origin.y)*(points[i].z-origin.z); } Matrix aux(3,3); SymmetricMatrix A; Real c1[3]={sx2,sxy,sxz}; Real c2[3]={sxy,sy2,syz}; Real c3[3]={sxz,syz,sz2}; aux.Column(1) << c1; aux.Column(2) << c2; aux.Column(3) << c3; A << aux; //find the eigenvalue closest to zero and its associated eigenvector etc DiagonalMatrix D; Matrix V; EigenValues(A,D,V); float min_eig=D(1,1); ColumnVector n(3); n<<V.Column(1); for (i=2;i<=3;i++) { if (D(i,i)<min_eig) { min_eig=D(i,i); n<<V.Column(i); } } normal=Vector3D(n(1),n(2),n(3)); float sense=origin*normal; if(sense>0) normal=Vector3D(-n(1),-n(2),-n(3)); float rs=0; float m=0; for (i=0;i<num;i++) { ColumnVector v1(3); Vector3D p1=points[i]-origin; Real v[3]={p1.x,p1.y,p1.z}; v1 << v; float dist=DotProduct(v1,n); if (dist > m) m=dist; rs+=dist*dist; } //max_res=m; *res=rs;*/ } void Plane::drawGL() { //compute Transformation // HTrans3D t(*this); glPushMatrix(); // t.Draw(); glTranslatef(origin.x,origin.y,origin.z); double roll = atan2(normal.y, normal.x); double pitch= acos(normal.z); glRotatef(roll*RAD2DEG,0,0,1); glRotatef(pitch*RAD2DEG,0,1,0); GLTools::DrawFrame(); glEnable(GL_BLEND); // Turn Blending On glDepthMask(GL_FALSE); glBlendFunc(GL_SRC_ALPHA, GL_ONE); // Set The Blending Function For Translucency GLTools::Color(CYAN,0.55f); glEnable(GL_LIGHTING); glNormal3f(0,0,1); glBegin(GL_POLYGON); glVertex3f(-4,-4,0); glVertex3f(-4,4,0); glVertex3f(4,4,0); glVertex3f(4,-4,0); glEnd(); glDisable(GL_BLEND); glDepthMask(GL_TRUE); glPopMatrix(); } } //mr
[ "miguel.hernando@upm.es" ]
miguel.hernando@upm.es
f313b4ced88a8094ff8364ae1caa1e38caff343f
0848ddb5f52c1648140e00f079f5d3efda5ab20e
/convet upper to lower case.cpp
6538856a305a7a29d9a56cfdc7b836fc866aab74
[]
no_license
striverGupta/C-Programming-Practice
0a6639475b34c39686024e5d3cdace462230d3c7
3b6bf644f768ea0fe43c98e86744264f609312cb
refs/heads/master
2023-08-13T21:45:33.887116
2021-10-03T13:07:05
2021-10-03T13:07:05
413,079,783
0
0
null
null
null
null
UTF-8
C++
false
false
361
cpp
#include <stdio.h> #include <conio.h> int main(){ char ch[100]; int i; printf("enter any character:"); scanf("%C",&ch); for(i=0;ch[i]='\0';i++){ if(ch[i] >='a' && ch[i]<='z'){ ch[i]=ch[i]-32; } } printf("lower into upper %c",ch); if(ch[i] >='a' && ch[i]<='z'){ ch[i]=ch[i]-32; } printf("upper into lower =%c",ch); return 0; }
[ "madhugupta25121@gmail.com" ]
madhugupta25121@gmail.com
0df1c2b45741215d6c91dc9e2de2e48f254997e6
a50f73f7ae45179544846eeec31aec7b5d57e98f
/src/muz/spacer/spacer_min_cut.cpp
22ff81a80ef54ac9e12db6276d193826c1b08ace
[ "MIT" ]
permissive
kenmcmil/z3
e68ba32ac1b35bcec3b8eec5dd45813c9cf451cd
30d3d9590a6ddbe7558a412bb00d432f7d4a275c
refs/heads/master
2023-06-24T01:31:27.495609
2022-12-07T23:19:00
2022-12-07T23:19:00
43,980,394
2
0
null
2015-10-09T21:13:06
2015-10-09T21:13:05
null
UTF-8
C++
false
false
7,517
cpp
/*++ Copyright (c) 2017 Arie Gurfinkel Module Name: spacer_min_cut.cpp Abstract: min cut solver Author: Bernhard Gleiss Revision History: --*/ #include "muz/spacer/spacer_min_cut.h" namespace spacer { spacer_min_cut::spacer_min_cut() { m_n = 2; // push back two empty vectors for source and sink m_edges.push_back(vector<std::pair<unsigned, unsigned>>()); m_edges.push_back(vector<std::pair<unsigned, unsigned>>()); } unsigned spacer_min_cut::new_node() { return m_n++; } void spacer_min_cut::add_edge(unsigned int i, unsigned int j, unsigned int capacity) { if (i >= m_edges.size()) { m_edges.resize(i + 1); } m_edges[i].insert(std::make_pair(j, 1)); STRACE("spacer.mincut", verbose_stream() << "adding edge (" << i << "," << j << ")\n"; ); } void spacer_min_cut::compute_min_cut(vector<unsigned>& cut_nodes) { if (m_n == 2) { return; } m_d.resize(m_n); m_pred.resize(m_n); // compute initial distances and number of nodes compute_initial_distances(); unsigned i = 0; while (m_d[0] < m_n) { unsigned j = get_admissible_edge(i); if (j < m_n) { // advance(i) m_pred[j] = i; i = j; // if i is the sink, augment path if (i == 1) { augment_path(); i = 0; } } else { // retreat compute_distance(i); if (i != 0) { i = m_pred[i]; } } } // split nodes into reachable and unreachable ones vector<bool> reachable(m_n); compute_reachable_nodes(reachable); // find all edges between reachable and unreachable nodes and for each such edge, add corresponding lemma to unsat-core compute_cut_and_add_lemmas(reachable, cut_nodes); } void spacer_min_cut::compute_initial_distances() { vector<unsigned> todo; vector<bool> visited(m_n); todo.push_back(0); // start at the source, since we do postorder traversel while (!todo.empty()) { unsigned current = todo.back(); // if we haven't already visited current if (!visited[current]) { bool existsUnvisitedParent = false; // add unprocessed parents to stack for DFS. If there is at least one unprocessed parent, don't compute the result // for current now, but wait until those unprocessed parents are processed. for (unsigned i = 0, sz = m_edges[current].size(); i < sz; ++i) { unsigned parent = m_edges[current][i].first; // if we haven't visited the current parent yet if(!visited[parent]) { // add it to the stack todo.push_back(parent); existsUnvisitedParent = true; } } // if we already visited all parents, we can visit current too if (!existsUnvisitedParent) { visited[current] = true; todo.pop_back(); compute_distance(current); // I.H. all parent distances are already computed } } else { todo.pop_back(); } } } unsigned spacer_min_cut::get_admissible_edge(unsigned i) { for (const auto& pair : m_edges[i]) { if (pair.second > 0 && m_d[i] == m_d[pair.first] + 1) { return pair.first; } } return m_n; // no element found } void spacer_min_cut::augment_path() { // find bottleneck capacity unsigned max = std::numeric_limits<unsigned int>::max(); unsigned k = 1; while (k != 0) { unsigned l = m_pred[k]; for (const auto& pair : m_edges[l]) { if (pair.first == k) { if (max > pair.second) { max = pair.second; } } } k = l; } k = 1; while (k != 0) { unsigned l = m_pred[k]; // decrease capacity for (auto& pair : m_edges[l]) { if (pair.first == k) { pair.second -= max; } } // increase reverse flow bool already_exists = false; for (auto& pair : m_edges[k]) { if (pair.first == l) { already_exists = true; pair.second += max; } } if (!already_exists) { m_edges[k].insert(std::make_pair(l, max)); } k = l; } } void spacer_min_cut::compute_distance(unsigned i) { if (i == 1) // sink node { m_d[1] = 0; } else { unsigned min = std::numeric_limits<unsigned int>::max(); // find edge (i,j) with positive residual capacity and smallest distance for (const auto& pair : m_edges[i]) { if (pair.second > 0) { unsigned tmp = m_d[pair.first] + 1; if (tmp < min) { min = tmp; } } } m_d[i] = min; } } void spacer_min_cut::compute_reachable_nodes(vector<bool>& reachable) { vector<unsigned> todo; todo.push_back(0); while (!todo.empty()) { unsigned current = todo.back(); todo.pop_back(); if (!reachable[current]) { reachable[current] = true; for (const auto& pair : m_edges[current]) { if (pair.second > 0) { todo.push_back(pair.first); } } } } } void spacer_min_cut::compute_cut_and_add_lemmas(vector<bool>& reachable, vector<unsigned>& cut_nodes) { vector<unsigned> todo; vector<bool> visited(m_n); todo.push_back(0); while (!todo.empty()) { unsigned current = todo.back(); todo.pop_back(); if (!visited[current]) { visited[current] = true; for (const auto& pair : m_edges[current]) { unsigned successor = pair.first; if (reachable[successor]) { todo.push_back(successor); } else { cut_nodes.push_back(successor); } } } } } }
[ "arie.gurfinkel@uwaterloo.ca" ]
arie.gurfinkel@uwaterloo.ca
58ebe0a1d6bb50a694b8b0496108b413297a96a7
dc0246248061c858e69a6b18af8fd6a49411d91c
/src/qt/sendcoinsdialog.cpp
64c1a46f79f3fa3e923d7641388aebb7df10bbd8
[ "MIT" ]
permissive
GGCash-Official/GGCash-Core
f930c47ed75ad1e9c4dd4a949a6adddb8a2b8b16
3525ab9fa53857dacbdb8558ce58fb844068e4a5
refs/heads/main
2023-04-10T16:30:38.314872
2021-04-14T23:43:50
2021-04-14T23:43:50
316,496,612
1
1
null
null
null
null
UTF-8
C++
false
false
39,569
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2019 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "addresstablemodel.h" #include "askpassphrasedialog.h" #include "bitcoinunits.h" #include "clientmodel.h" #include "coincontroldialog.h" #include "guiutil.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "walletmodel.h" #include "base58.h" #include "coincontrol.h" #include "guiinterface.h" #include "utilmoneystr.h" #include "wallet/wallet.h" #include <QMessageBox> #include <QScrollBar> #include <QSettings> #include <QTextDocument> SendCoinsDialog::SendCoinsDialog(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), ui(new Ui::SendCoinsDialog), clientModel(0), model(0), fNewRecipientAllowed(true), fFeeMinimized(true) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this); addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString&)), this, SLOT(coinControlChangeEdited(const QString&))); // UTXO Splitter connect(ui->splitBlockCheckBox, SIGNAL(stateChanged(int)), this, SLOT(splitBlockChecked(int))); connect(ui->splitBlockLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(splitBlockLineEditChanged(const QString&))); // GGCash specific QSettings settings; if (!settings.contains("bUseObfuScation")) settings.setValue("bUseObfuScation", false); if (!settings.contains("bUseSwiftTX")) settings.setValue("bUseSwiftTX", false); bool useSwiftTX = settings.value("bUseSwiftTX").toBool(); if (fLiteMode) { ui->checkSwiftTX->setVisible(false); CoinControlDialog::coinControl->useObfuScation = false; CoinControlDialog::coinControl->useSwiftTX = false; } else { ui->checkSwiftTX->setChecked(useSwiftTX); CoinControlDialog::coinControl->useSwiftTX = useSwiftTX; } connect(ui->checkSwiftTX, SIGNAL(stateChanged(int)), this, SLOT(updateSwiftTX())); // Coin Control: clipboard actions QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction* clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction* clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction* clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction* clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction* clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction* clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // init transaction fee section if (!settings.contains("fFeeSectionMinimized")) settings.setValue("fFeeSectionMinimized", true); if (!settings.contains("nFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility settings.setValue("nFeeRadio", 1); // custom if (!settings.contains("nFeeRadio")) settings.setValue("nFeeRadio", 0); // recommended if (!settings.contains("nCustomFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility settings.setValue("nCustomFeeRadio", 1); // total at least if (!settings.contains("nCustomFeeRadio")) settings.setValue("nCustomFeeRadio", 0); // per kilobyte if (!settings.contains("nSmartFeeSliderPosition")) settings.setValue("nSmartFeeSliderPosition", 0); if (!settings.contains("nTransactionFee")) settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE); if (!settings.contains("fPayOnlyMinFee")) settings.setValue("fPayOnlyMinFee", false); if (!settings.contains("fSendFreeTransactions")) settings.setValue("fSendFreeTransactions", false); ui->groupFee->setId(ui->radioSmartFee, 0); ui->groupFee->setId(ui->radioCustomFee, 1); ui->groupFee->button((int)std::max(0, std::min(1, settings.value("nFeeRadio").toInt())))->setChecked(true); ui->groupCustomFee->setId(ui->radioCustomPerKilobyte, 0); ui->groupCustomFee->setId(ui->radioCustomAtLeast, 1); ui->groupCustomFee->button((int)std::max(0, std::min(1, settings.value("nCustomFeeRadio").toInt())))->setChecked(true); ui->sliderSmartFee->setValue(settings.value("nSmartFeeSliderPosition").toInt()); ui->customFee->setValue(settings.value("nTransactionFee").toLongLong()); ui->checkBoxMinimumFee->setChecked(settings.value("fPayOnlyMinFee").toBool()); ui->checkBoxFreeTx->setChecked(settings.value("fSendFreeTransactions").toBool()); ui->checkzGGH->hide(); minimizeFeeSection(settings.value("fFeeSectionMinimized").toBool()); // If SwiftX activated hide button 'Choose'. Show otherwise. ui->buttonChooseFee->setVisible(!useSwiftTX); } void SendCoinsDialog::setClientModel(ClientModel* clientModel) { this->clientModel = clientModel; if (clientModel) { connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(updateSmartFeeLabel())); } } void SendCoinsDialog::setModel(WalletModel* model) { this->model = model; if (model && model->getOptionsModel()) { for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (entry) { entry->setModel(model); } } setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getZerocoinBalance (), model->getUnconfirmedZerocoinBalance (), model->getImmatureZerocoinBalance (), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateDisplayUnit(); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); // fee section connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(updateSmartFeeLabel())); connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateFeeSectionControls())); connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->groupCustomFee, SIGNAL(buttonClicked(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->groupCustomFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(updateGlobalFeeVariables())); connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(coinControlUpdateLabels())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(setMinimumFee())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateFeeSectionControls())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->checkBoxFreeTx, SIGNAL(stateChanged(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->checkBoxFreeTx, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels())); ui->customFee->setSingleStep(CWallet::minTxFee.GetFeePerK()); updateFeeSectionControls(); updateMinFeeLabel(); updateSmartFeeLabel(); updateGlobalFeeVariables(); } } SendCoinsDialog::~SendCoinsDialog() { QSettings settings; settings.setValue("fFeeSectionMinimized", fFeeMinimized); settings.setValue("nFeeRadio", ui->groupFee->checkedId()); settings.setValue("nCustomFeeRadio", ui->groupCustomFee->checkedId()); settings.setValue("nSmartFeeSliderPosition", ui->sliderSmartFee->value()); settings.setValue("nTransactionFee", (qint64)ui->customFee->value()); settings.setValue("fPayOnlyMinFee", ui->checkBoxMinimumFee->isChecked()); settings.setValue("fSendFreeTransactions", ui->checkBoxFreeTx->isChecked()); delete ui; } void SendCoinsDialog::on_sendButton_clicked() { if (!model || !model->getOptionsModel()) return; QList<SendCoinsRecipient> recipients; bool valid = true; for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); //UTXO splitter - address should be our own CBitcoinAddress address = entry->getValue().address.toStdString(); if (!model->isMine(address) && ui->splitBlockCheckBox->checkState() == Qt::Checked) { CoinControlDialog::coinControl->fSplitBlock = false; ui->splitBlockCheckBox->setCheckState(Qt::Unchecked); QMessageBox::warning(this, tr("Send Coins"), tr("The split block tool does not work when sending to outside addresses. Try again."), QMessageBox::Ok, QMessageBox::Ok); return; } if (entry) { if (entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if (!valid || recipients.isEmpty()) { return; } //set split block in model CoinControlDialog::coinControl->fSplitBlock = ui->splitBlockCheckBox->checkState() == Qt::Checked; if (ui->entries->count() > 1 && ui->splitBlockCheckBox->checkState() == Qt::Checked) { CoinControlDialog::coinControl->fSplitBlock = false; ui->splitBlockCheckBox->setCheckState(Qt::Unchecked); QMessageBox::warning(this, tr("Send Coins"), tr("The split block tool does not work with multiple addresses. Try again."), QMessageBox::Ok, QMessageBox::Ok); return; } if (CoinControlDialog::coinControl->fSplitBlock) CoinControlDialog::coinControl->nSplitBlock = int(ui->splitBlockLineEdit->text().toInt()); QString strFunds = ""; QString strFee = ""; recipients[0].inputType = ALL_COINS; if (ui->checkSwiftTX->isChecked()) { recipients[0].useSwiftTX = true; strFunds += " "; strFunds += tr("using SwiftX"); } else { recipients[0].useSwiftTX = false; } // Format confirmation message QStringList formatted; foreach (const SendCoinsRecipient& rcp, recipients) { // generate bold amount string QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount); amount.append("</b> ").append(strFunds); // generate monospace address string QString address = "<span style='font-family: monospace;'>" + rcp.address; address.append("</span>"); QString recipientElement; if (!rcp.paymentRequest.IsInitialized()) // normal payment { if (rcp.label.length() > 0) // label with address { recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label)); recipientElement.append(QString(" (%1)").arg(address)); } else // just address { recipientElement = tr("%1 to %2").arg(amount, address); } } else if (!rcp.authenticatedMerchant.isEmpty()) // secure payment request { recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant)); } else // insecure payment request { recipientElement = tr("%1 to %2").arg(amount, address); } if (CoinControlDialog::coinControl->fSplitBlock) { recipientElement.append(tr(" split into %1 outputs using the UTXO splitter.").arg(CoinControlDialog::coinControl->nSplitBlock)); } formatted.append(recipientElement); } fNewRecipientAllowed = false; // request unlock only if was locked or unlocked for mixing: // this way we let users unlock by walletpassphrase or by menu // and make many transactions while unlocking through this dialog // will call relock WalletModel::EncryptionStatus encStatus = model->getEncryptionStatus(); if (encStatus == model->Locked || encStatus == model->UnlockedForAnonymizationOnly) { WalletModel::UnlockContext ctx(model->requestUnlock(AskPassphraseDialog::Context::Send_GGH, true)); if (!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } send(recipients, strFee, formatted); return; } // already unlocked or not encrypted at all send(recipients, strFee, formatted); } void SendCoinsDialog::send(QList<SendCoinsRecipient> recipients, QString strFee, QStringList formatted) { // prepare transaction for getting txFee earlier WalletModelTransaction currentTransaction(recipients); WalletModel::SendCoinsReturn prepareStatus; if (model->getOptionsModel()->getCoinControlFeatures()) // coin control enabled prepareStatus = model->prepareTransaction(currentTransaction, CoinControlDialog::coinControl); else prepareStatus = model->prepareTransaction(currentTransaction); // process prepareStatus and on error generate message shown to user processSendCoinsReturn(prepareStatus, BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()), true); if (prepareStatus.status != WalletModel::OK) { fNewRecipientAllowed = true; return; } CAmount txFee = currentTransaction.getTransactionFee(); QString questionString = tr("Are you sure you want to send?"); questionString.append("<br /><br />%1"); if (txFee > 0) { // append fee string if a fee is required questionString.append("<hr /><span style='color:#aa0000;'>"); questionString.append(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), txFee)); questionString.append("</span> "); questionString.append(tr("are added as transaction fee")); questionString.append(" "); questionString.append(strFee); // append transaction size questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB)"); } // add total amount in all subdivision units questionString.append("<hr />"); CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee; QStringList alternativeUnits; foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) { if (u != model->getOptionsModel()->getDisplayUnit()) alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount)); } // Show total amount + all alternative units questionString.append(tr("Total Amount = <b>%1</b><br />= %2") .arg(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), totalAmount)) .arg(alternativeUnits.join("<br />= "))); // Limit number of displayed entries int messageEntries = formatted.size(); int displayedEntries = 0; for (int i = 0; i < formatted.size(); i++) { if (i >= MAX_SEND_POPUP_ENTRIES) { formatted.removeLast(); i--; } else { displayedEntries = i + 1; } } questionString.append("<hr />"); questionString.append(tr("<b>(%1 of %2 entries displayed)</b>").arg(displayedEntries).arg(messageEntries)); // Display message box QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), questionString.arg(formatted.join("<br />")), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } // now send the prepared transaction WalletModel::SendCoinsReturn sendStatus = model->sendCoins(currentTransaction); // process sendStatus and on error generate message shown to user processSendCoinsReturn(sendStatus); if (sendStatus.status == WalletModel::OK) { accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while (ui->entries->count()) { ui->entries->takeAt(0)->widget()->deleteLater(); } addEntry(); updateTabsAndLabels(); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry* SendCoinsDialog::addEntry() { SendCoinsEntry* entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateTabsAndLabels(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); qApp->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if (bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateTabsAndLabels() { setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { entry->hide(); // If the last entry is about to be removed add an empty one if (ui->entries->count() == 1) addEntry(); entry->deleteLater(); updateTabsAndLabels(); } QWidget* SendCoinsDialog::setupTabChain(QWidget* prev) { for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->sendButton); QWidget::setTabOrder(ui->sendButton, ui->clearButton); QWidget::setTabOrder(ui->clearButton, ui->addButton); return ui->addButton; } void SendCoinsDialog::setAddress(const QString& address) { SendCoinsEntry* entry = 0; // Replace the first entry if it is still unused if (ui->entries->count() == 1) { SendCoinsEntry* first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if (first->isClear()) { entry = first; } } if (!entry) { entry = addEntry(); } entry->setAddress(address); } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient& rv) { if (!fNewRecipientAllowed) return; SendCoinsEntry* entry = 0; // Replace the first entry if it is still unused if (ui->entries->count() == 1) { SendCoinsEntry* first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if (first->isClear()) { entry = first; } } if (!entry) { entry = addEntry(); } entry->setValue(rv); updateTabsAndLabels(); } bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient& rv) { // Just paste the entry, all pre-checks // are done in paymentserver.cpp. pasteEntry(rv); return true; } void SendCoinsDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance, const CAmount& watchBalance, const CAmount& watchUnconfirmedBalance, const CAmount& watchImmatureBalance) { Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); Q_UNUSED(zerocoinBalance); Q_UNUSED(unconfirmedZerocoinBalance); Q_UNUSED(immatureZerocoinBalance); Q_UNUSED(watchBalance); Q_UNUSED(watchUnconfirmedBalance); Q_UNUSED(watchImmatureBalance); if (model && model->getOptionsModel()) { uint64_t bal = 0; bal = balance; ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), bal)); } } void SendCoinsDialog::updateDisplayUnit() { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getZerocoinBalance (), model->getUnconfirmedZerocoinBalance (), model->getImmatureZerocoinBalance (), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); coinControlUpdateLabels(); ui->customFee->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); updateMinFeeLabel(); updateSmartFeeLabel(); } void SendCoinsDialog::updateSwiftTX() { bool useSwiftTX = ui->checkSwiftTX->isChecked(); QSettings settings; settings.setValue("bUseSwiftTX", useSwiftTX); CoinControlDialog::coinControl->useSwiftTX = useSwiftTX; // If SwiftX activated if (useSwiftTX) { // minimize the Fee Section (if open) minimizeFeeSection(true); // set the slider to the max ui->sliderSmartFee->setValue(24); } // If SwiftX activated hide button 'Choose'. Show otherwise. ui->buttonChooseFee->setVisible(!useSwiftTX); // Update labels and controls updateFeeSectionControls(); updateSmartFeeLabel(); coinControlUpdateLabels(); } void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn& sendCoinsReturn, const QString& msgArg, bool fPrepare) { bool fAskForUnlock = false; QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams; // Default to a warning message, override if error message is needed msgParams.second = CClientUIInterface::MSG_WARNING; // This comment is specific to SendCoinsDialog usage of WalletModel::SendCoinsReturn. // WalletModel::TransactionCommitFailed is used only in WalletModel::sendCoins() // all others are used only in WalletModel::prepareTransaction() switch (sendCoinsReturn.status) { case WalletModel::InvalidAddress: msgParams.first = tr("The recipient address is not valid, please recheck."); break; case WalletModel::InvalidAmount: msgParams.first = tr("The amount to pay must be larger than 0."); break; case WalletModel::AmountExceedsBalance: msgParams.first = tr("The amount exceeds your balance."); break; case WalletModel::AmountWithFeeExceedsBalance: msgParams.first = tr("The total exceeds your balance when the %1 transaction fee is included.").arg(msgArg); break; case WalletModel::DuplicateAddress: msgParams.first = tr("Duplicate address found, can only send to each address once per send operation."); break; case WalletModel::TransactionCreationFailed: msgParams.first = tr("Transaction creation failed!"); msgParams.second = CClientUIInterface::MSG_ERROR; break; case WalletModel::TransactionCommitFailed: msgParams.first = tr("The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); msgParams.second = CClientUIInterface::MSG_ERROR; break; case WalletModel::AnonymizeOnlyUnlocked: // Unlock is only need when the coins are send if(!fPrepare) fAskForUnlock = true; else msgParams.first = tr("Error: The wallet was unlocked only to anonymize coins."); break; case WalletModel::InsaneFee: msgParams.first = tr("A fee %1 times higher than %2 per kB is considered an insanely high fee.").arg(10000).arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ::minRelayTxFee.GetFeePerK())); break; // included to prevent a compiler warning. case WalletModel::OK: default: return; } // Unlock wallet if it wasn't fully unlocked already if(fAskForUnlock) { model->requestUnlock(AskPassphraseDialog::Context::Unlock_Full, false); if(model->getEncryptionStatus () != WalletModel::Unlocked) { msgParams.first = tr("Error: The wallet was unlocked only to anonymize coins. Unlock canceled."); } else { // Wallet unlocked return; } } emit message(tr("Send Coins"), msgParams.first, msgParams.second); } void SendCoinsDialog::minimizeFeeSection(bool fMinimize) { ui->labelFeeMinimized->setVisible(fMinimize); ui->buttonChooseFee->setVisible(fMinimize); ui->buttonMinimizeFee->setVisible(!fMinimize); ui->frameFeeSelection->setVisible(!fMinimize); ui->horizontalLayoutSmartFee->setContentsMargins(0, (fMinimize ? 0 : 6), 0, 0); fFeeMinimized = fMinimize; } void SendCoinsDialog::on_buttonChooseFee_clicked() { minimizeFeeSection(false); } void SendCoinsDialog::on_buttonMinimizeFee_clicked() { updateFeeMinimizedLabel(); minimizeFeeSection(true); } void SendCoinsDialog::setMinimumFee() { ui->radioCustomPerKilobyte->setChecked(true); ui->customFee->setValue(CWallet::minTxFee.GetFeePerK()); } void SendCoinsDialog::updateFeeSectionControls() { ui->sliderSmartFee->setEnabled(ui->radioSmartFee->isChecked() && !ui->checkSwiftTX->isChecked()); ui->labelSmartFee->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFee2->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFee3->setEnabled(ui->radioSmartFee->isChecked()); ui->labelFeeEstimation->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFeeNormal->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFeeFast->setEnabled(ui->radioSmartFee->isChecked()); ui->checkBoxMinimumFee->setEnabled(ui->radioCustomFee->isChecked()); ui->labelMinFeeWarning->setEnabled(ui->radioCustomFee->isChecked()); ui->radioCustomPerKilobyte->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked()); ui->radioCustomAtLeast->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked()); ui->customFee->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked()); } void SendCoinsDialog::updateGlobalFeeVariables() { if (ui->radioSmartFee->isChecked()) { nTxConfirmTarget = (int)25 - (int)std::max(0, std::min(24, ui->sliderSmartFee->value())); payTxFee = CFeeRate(0); } else { nTxConfirmTarget = 25; payTxFee = CFeeRate(ui->customFee->value()); fPayAtLeastCustomFee = ui->radioCustomAtLeast->isChecked(); } fSendFreeTransactions = ui->checkBoxFreeTx->isChecked(); } void SendCoinsDialog::updateFeeMinimizedLabel() { if (!model || !model->getOptionsModel()) return; if (ui->checkSwiftTX->isChecked()) { ui->labelFeeMinimized->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), 1000000)); } else if (ui->radioSmartFee->isChecked()) ui->labelFeeMinimized->setText(ui->labelSmartFee->text()); else { ui->labelFeeMinimized->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ui->customFee->value()) + ((ui->radioCustomPerKilobyte->isChecked()) ? "/kB" : "")); } } void SendCoinsDialog::updateMinFeeLabel() { if (model && model->getOptionsModel()) ui->checkBoxMinimumFee->setText(tr("Pay only the minimum fee of %1").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()) + "/kB")); } void SendCoinsDialog::updateSmartFeeLabel() { if (!model || !model->getOptionsModel()) return; int nBlocksToConfirm = (int)25 - (int)std::max(0, std::min(24, ui->sliderSmartFee->value())); CFeeRate feeRate = mempool.estimateFee(nBlocksToConfirm); // if SwiftX checked, display it in the label if (ui->checkSwiftTX->isChecked()) { ui->labelFeeEstimation->setText(tr("Estimated to get 6 confirmations near instantly with <b>SwiftX</b>!")); ui->labelSmartFee2->hide(); } else if (feeRate <= CFeeRate(0)) // not enough data => minfee { ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()) + "/kB"); ui->labelSmartFee2->show(); // (Smart fee not initialized yet. This usually takes a few blocks...) ui->labelFeeEstimation->setText(""); } else { ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB"); ui->labelSmartFee2->hide(); ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", nBlocksToConfirm)); } updateFeeMinimizedLabel(); } // UTXO splitter void SendCoinsDialog::splitBlockChecked(int state) { if (model) { CoinControlDialog::coinControl->fSplitBlock = (state == Qt::Checked); fSplitBlock = (state == Qt::Checked); ui->splitBlockLineEdit->setEnabled((state == Qt::Checked)); ui->labelBlockSizeText->setEnabled((state == Qt::Checked)); ui->labelBlockSize->setEnabled((state == Qt::Checked)); coinControlUpdateLabels(); } } //UTXO splitter void SendCoinsDialog::splitBlockLineEditChanged(const QString& text) { //grab the amount in Coin Control AFter Fee field QString qAfterFee = ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", "").simplified().replace(" ", ""); //convert to CAmount CAmount nAfterFee; ParseMoney(qAfterFee.toStdString().c_str(), nAfterFee); //if greater than 0 then divide after fee by the amount of blocks CAmount nSize = nAfterFee; int nBlocks = text.toInt(); if (nAfterFee && nBlocks) nSize = nAfterFee / nBlocks; //assign to split block dummy, which is used to recalculate the fee amount more outputs CoinControlDialog::nSplitBlockDummy = nBlocks; //update labels ui->labelBlockSize->setText(QString::fromStdString(FormatMoney(nSize))); coinControlUpdateLabels(); } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace("~", "")); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", "")); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace("~", "")); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Dust" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace("~", "")); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); if (checked) coinControlUpdateLabels(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (state == Qt::Unchecked) { CoinControlDialog::coinControl->destChange = CNoDestination(); ui->labelCoinControlChangeLabel->clear(); } else // use this to re-validate an already entered address coinControlChangeEdited(ui->lineEditCoinControlChange->text()); ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString& text) { if (model && model->getAddressTableModel()) { // Default to no change address until verified CoinControlDialog::coinControl->destChange = CNoDestination(); ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); CBitcoinAddress addr = CBitcoinAddress(text.toStdString()); if (text.isEmpty()) // Nothing entered { ui->labelCoinControlChangeLabel->setText(""); } else if (!addr.IsValid()) // Invalid address { ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid GGCash address")); } else // Valid address { CPubKey pubkey; CKeyID keyid; addr.GetKeyID(keyid); if (!model->getPubKey(keyid, pubkey)) // Unknown change address { ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address")); } else // Known change address { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); // Query label QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else ui->labelCoinControlChangeLabel->setText(tr("(no label)")); CoinControlDialog::coinControl->destChange = addr.Get(); } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
[ "fanaticosfaucet@gmail.com" ]
fanaticosfaucet@gmail.com
6eef69f3eaa2085747cc543eaa92e9f54c00d404
69ce50a6b76f831d4b948bcd3308385c075c7888
/PaperEngineFull/PaperEngine/util/IProfile.h
d7a440976d1e08b87af749860dae027b7d57e070
[]
no_license
WindyPaper/Paper
834fca671630300643d613335b24d69ccd238589
dbe15de8ea44bd700f55f65a0f25e3a186ec7e67
refs/heads/master
2021-01-15T09:57:49.594716
2016-09-05T00:46:29
2016-09-05T00:46:29
22,540,627
0
0
null
null
null
null
UTF-8
C++
false
false
458
h
#ifndef _I_PROFILE_H_ #define _I_PROFILE_H_ #include "util/Engine_Define.h" class IProfile { public: virtual ~IProfile() {} virtual void startProfile() = 0; virtual void endProfile() = 0; virtual uint getVerticeNum() const = 0; //virtual void setFPS(float frameTime) = 0; virtual uint getFPS() const = 0; virtual uint getDrawCallNum() const = 0; virtual void addVerticeNum(int verticeNum) = 0; virtual void increaseDrawCallNum() = 0; }; #endif
[ "windy_max@163.com" ]
windy_max@163.com
54db61dc3b240f82004d1ffdf58168e0353bb117
a5a144c383f7cc354547e0349ce43b9543a4e950
/injest/hollow_world/Source.cpp
bbccf2be09d0cded2159dc7e1dc416367481599e
[ "MIT" ]
permissive
rnast/IDAdump
e3c357f1c55b2259a1c57bf95fd6bb91706d9a94
334aafdb08bd62e7a6792248652cb3d46b16f099
refs/heads/master
2021-01-01T18:50:03.695961
2017-07-25T23:37:33
2017-07-25T23:37:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
144
cpp
#define WIN32_LEAN_AND_MEAN #include <stdio.h> #include <windows.h> int main(int argc, char **argv) { printf("hollow world"); }
[ "mert@Erics-MacBook-Pro.local" ]
mert@Erics-MacBook-Pro.local
f5f9e4e6f0dec394b375999d1ebf45022be9e038
da7e8450a11834eeb891c543fb22c7eebedf8a78
/submit/ABC101-192/ABC175/175-B.cpp
e95f527f38bc2fb47d64dd124534d463addd2b3f
[]
no_license
uno1142/AtCoder
ecc8334cf7f52de8726f225eedc181d1b7a30bba
da278d45696355c582451202413ad2f18a19e55b
refs/heads/master
2023-04-06T16:57:29.682871
2021-04-07T12:06:54
2021-04-07T12:06:54
264,152,506
0
0
null
null
null
null
UTF-8
C++
false
false
534
cpp
#include<bits/stdc++.h> #define rep(i,n) for (int i =0; i <(n); i++) using namespace std; using ll = long long; int main(){ int N; cin >> N; vector<int>A(N); rep(i,N)cin >> A[i]; sort(A.begin(),A.end()); int ans = 0; rep(i,N){ rep(j,i){ rep(k,j){ if(A[i] == A[j] || A[j] == A[k])continue; if(A[j]+A[k] > A[i] && A[j]+A[i] > A[k] && A[i] + A[k] > A[j])ans++; } } } cout << ans << endl; }
[ "byeethe8@yahoo.co.jp" ]
byeethe8@yahoo.co.jp
d090712bd9fa33c3e2f66558bfad309a003ef735
c91a2e7d34640c191e43168bf14a391139da1670
/code/Script/Script.hpp
79fa0e3134cb50b65d9036e5fee656f8b58879ce
[]
no_license
brettdavidsilverman/bee.fish
69469ada712e9e80b2467c5efc840afcbfc9b725
a7cbe8b4be9126ab6e408ecc71f85b385cf0f831
refs/heads/main
2023-09-01T11:19:09.772149
2023-08-26T15:45:00
2023-08-26T15:45:00
248,724,150
0
0
null
2022-04-18T13:43:30
2020-03-20T10:08:10
C
UTF-8
C++
false
false
140
hpp
#ifndef BEE_FISH_SCRIPT__H #define BEE_FISH_SCRIPT__H #include "version.h" #include "../json/object.h" #include "b-script-parser.h" #endif
[ "brettdavidailverman@gmail.com" ]
brettdavidailverman@gmail.com
6950643d59d9ee0c8d4c84282e52a97c14d81ff2
be7eb4ce1e200781ec4ac1838786122fe64206eb
/facegrabber/src/detector/HaarLikeDetector.cpp
2a47a23f7ce82ccc799da8a3bfa67a90ee7cfae2
[]
no_license
luca-m/facegrabber
ccd7cf7fec5ddb014f3a33ce8efc33763108c672
315073b2dbea1b7dc0dca747619f08e34cf59cc4
refs/heads/master
2020-12-24T14:18:08.277934
2013-08-08T11:25:18
2013-08-08T11:25:18
11,613,544
3
0
null
null
null
null
UTF-8
C++
false
false
5,562
cpp
/* * FaceFeatureDetector.cpp * * Created on: Jul 23, 2013 * Author: stk */ #include "HaarLikeDetector.h" #include "../model/FaceRegion.h" using namespace std; namespace facegrabber { bool HaarLikeDetector::detectFace(IplImage * img, IFaceRegion * faceregion) { vector<Rect> faces; CvRect * facearea = faceregion->getFace(); bool hasFace = false; /* detect faces */ cascade_f.detectMultiScale(img, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, cvSize(40, 60)); if (faces.size() > 0) { facearea->x = faces[0].x; facearea->y = faces[0].y; facearea->width = faces[0].width; facearea->height = faces[0].height; hasFace = true; } else { facearea->x = 0; facearea->y = 0; facearea->width = 0; facearea->height = 0; } return hasFace; } bool HaarLikeDetector::detectFeatures(IplImage * img, IFaceRegion * faceregion) { vector<Rect> eyeL, eyeR, noses, mouths; CvRect eyeROIL, eyeROIR, noseROI, mouthROI, eyeBrow, *tmp_area; tmp_area = faceregion->getFace(); /* Set the Region of Interest for lower pattern matching area */ eyeROIL = cvRect(tmp_area->x + tmp_area->width / 2, tmp_area->y + (tmp_area->height / 5.5), tmp_area->width / 2, tmp_area->height / 3.0); eyeROIR = cvRect(tmp_area->x, tmp_area->y + (tmp_area->height / 5.5), tmp_area->width / 2, tmp_area->height / 3.0); noseROI = cvRect(tmp_area->x, tmp_area->y + tmp_area->height / 2.5, tmp_area->width, tmp_area->height / 3.0); mouthROI = cvRect(tmp_area->x, tmp_area->y + (tmp_area->height / 1.5), tmp_area->width, tmp_area->height / 2.5); if (printRoi && currImg != 0) { /* Print Region of interest (for debugging purposes) */ cvRectangle(currImg, cvPoint(eyeROIL.x, eyeROIL.y), cvPoint(eyeROIL.x + eyeROIL.width, eyeROIL.y + eyeROIL.height), CV_RGB(255, 0, 0), 1, 8, 0); cvRectangle(currImg, cvPoint(eyeROIL.x, eyeROIL.y), cvPoint(eyeROIR.x + eyeROIR.width, eyeROIR.y + eyeROIR.height), CV_RGB(255, 0, 0), 1, 8, 0); cvRectangle(currImg, cvPoint(noseROI.x, noseROI.y), cvPoint(noseROI.x + noseROI.width, noseROI.y + noseROI.height), CV_RGB(0, 255, 0), 1, 8, 0); cvRectangle(currImg, cvPoint(mouthROI.x, mouthROI.y), cvPoint(mouthROI.x + mouthROI.width, mouthROI.y + mouthROI.height), CV_RGB(0, 0, 255), 1, 8, 0); } /* detect eyes (first ones)*/ cvSetImageROI(img, eyeROIL); cascade_el.detectMultiScale(img, eyeL, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(20, 20)); cvResetImageROI(img); if (eyeL.size() > 0) { tmp_area = (CvRect*) &eyeL[0]; tmp_area->x += eyeROIL.x; tmp_area->y += eyeROIL.y + tmp_area->height / 4; faceregion->setEyeL(tmp_area); } else { faceregion->setEyeL(0); } cvSetImageROI(img, eyeROIR); cascade_er.detectMultiScale(img, eyeR, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(20, 20)); cvResetImageROI(img); if (eyeR.size() > 0) { tmp_area = (CvRect*) &eyeR[0]; tmp_area->x += eyeROIR.x; tmp_area->y += eyeROIR.y; faceregion->setEyeR(tmp_area); } else { faceregion->setEyeR(0); } /* detect nose (first one) */ cvSetImageROI(img, noseROI); cascade_n.detectMultiScale(img, noses, 1.1, 3, 0 | CV_HAAR_SCALE_IMAGE, Size(10, 5)); cvResetImageROI(img); if (noses.size() > 0) { tmp_area = (CvRect*) &noses[0]; tmp_area->x += noseROI.x; tmp_area->y += noseROI.y; faceregion->setNose(tmp_area); } else { faceregion->setNose(0); } /* detect mouth (first one) */ cvSetImageROI(img, mouthROI); cascade_m.detectMultiScale(img, mouths, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30)); cvResetImageROI(img); if (mouths.size() > 0) { tmp_area = (CvRect*) &mouths[0]; tmp_area->x += mouthROI.x; tmp_area->y += mouthROI.y; faceregion->setMouth(tmp_area); } else { faceregion->setMouth(0); } /* estimate eyebrows using face proportions */ if (faceregion->hasEyeR()) { eyeBrow.x = faceregion->getEyeR()->x - 13; eyeBrow.y = faceregion->getEyeR()->y - faceregion->getEyeR()->height / 2; eyeBrow.width = faceregion->getEyeR()->width + 14; eyeBrow.height = faceregion->getEyeR()->height; faceregion->setEyeBrowR(&eyeBrow); } if (faceregion->hasEyeL()) { eyeBrow = cvRect(0, 0, 0, 0); eyeBrow.x = faceregion->getEyeL()->x - 10; eyeBrow.y = faceregion->getEyeL()->y - faceregion->getEyeL()->height / 2; eyeBrow.width = faceregion->getEyeL()->width + 14; eyeBrow.height = faceregion->getEyeL()->height; faceregion->setEyeBrowL(&eyeBrow); } return faceregion->isComplete(); } HaarLikeDetector::HaarLikeDetector(char * face_config_file, char * eyeLeft_config_file, char * eyeRight_config_file, char * nose_config_file, char * mouth_config_file,bool faceOnly, bool printRoi) { cascade_f.load(face_config_file); cascade_el.load(eyeLeft_config_file); cascade_er.load(eyeRight_config_file); cascade_n.load(nose_config_file); cascade_m.load(mouth_config_file); assert( !cascade_f.empty() && !cascade_el.empty() && !cascade_n.empty() && !cascade_m.empty()); this->currImg = 0; this->printRoi = printRoi; this->faceOnly = faceOnly; } HaarLikeDetector::~HaarLikeDetector() { } IFaceRegion * HaarLikeDetector::detect(IplImage * frame) { IplImage * im_gray; FaceRegion * face= new FaceRegion(); if (frame == 0) return face; this->currImg = frame; im_gray = cvCreateImage(cvSize(frame->width, frame->height), IPL_DEPTH_8U, 1); cvCvtColor(frame, im_gray, CV_RGB2GRAY); cvEqualizeHist(im_gray, im_gray); if (this->detectFace(im_gray, face) && !faceOnly ) { this->detectFeatures(im_gray, face); } cvReleaseImage(&im_gray); return face; } }/* namespace facedetect */
[ "lucam.ko@gmail.com" ]
lucam.ko@gmail.com
db5e846bd28fdf7c659fe3ffa2289c9b292a4fb5
bd266c1f9ee15b57334135639dba333bb8953f12
/ICPC_old/100/2006.cpp
03da532b3f0c4f0c8d1963ec7c0254e76370e64c
[]
no_license
ryotakano77/atcoder
673cd71efe9e27bc7e005e90b3288a39baaaa23d
468939d1081366e26553adf0a5e5d162e2e109a0
refs/heads/master
2023-08-16T13:39:40.289832
2021-10-05T05:47:34
2021-10-05T05:47:34
382,635,994
0
0
null
null
null
null
UTF-8
C++
false
false
1,952
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define int long long #define FOR(i, a, b) for (int i = (a); i < (b); i++) #define REP(i, n) for (int i = 0; i < (n); i++) #define pb push_back #define ALL(obj) (obj).begin(), (obj).end() #define vi vector<int> #define vvi vector<vector<int>> #define Lower_bound(vec, n) distance((vec).begin(), lower_bound((vec).begin(), (vec).end(), (n))) #define Upper_bound(vec, n) distance((vec).begin(), upper_bound((vec).begin(), (vec).end(), (n))) #define Erase(vec) (vec).erase(unique((vec).begin(), (vec).end()), (vec).end()) //template <class T = int> in()(T x; cin >> x; return (x);) //template <class T> print(T& x) (cout << x << endl;) //using template <class T> vec = vector<T>; using Graph = vector<vector<int>>; const int INF = 1LL << 60; const int MOD = (int)1e9 + 7; const double EPS = 1e-9; signed main() { unordered_map<char, string> um; um['1'] = ".,!? "; um['2'] = "abc"; um['3'] = "def"; um['4'] = "ghi"; um['5'] = "jkl"; um['6'] = "mno"; um['7'] = "pqrs"; um['8'] = "tuv"; um['9'] = "wxyz"; string num; int N; cin >> N; REP(i, N) { cin >> num; int len = num.size(); char c = num[0]; int c_count = 0; int num_count = 1; string ans = ""; while (true) { if (num_count == len) { //if (c != ' ') ans += um[c][c_count % (um[c].size())]; break; } char c_next = num[num_count]; if (c_next == '0') { if (c != '0') ans += um[c][c_count % (um[c].size())]; c = '0'; c_count = 0; } else if (c == '0') { c = num[num_count]; c_count = 0; } else { c_count++; } num_count++; } cout << ans << endl; } }
[ "takano.ryo@gmail.com" ]
takano.ryo@gmail.com
2e7b3b92effc1b42eb60b60e3d148c057a61dac6
00c64e0967d197d8c6fc3427954e2d0b2ff13ca0
/sycl/include/sycl/ext/intel/esimd/detail/half_type_traits.hpp
90604a2ddac685ea8a8bf3d2994674962dab7422
[ "NCSA", "LLVM-exception", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
triSYCL/sycl
893048e80158cf3359c1ad8912da9ccf493faf69
5a95a7136a11b75f01ef839d9229780032bbeecf
refs/heads/sycl/unified/master
2023-08-23T22:06:46.238209
2023-05-24T22:54:31
2023-05-24T22:54:31
178,923,006
103
17
NOASSERTION
2023-09-12T20:03:26
2019-04-01T18:29:01
null
UTF-8
C++
false
false
4,978
hpp
//==-------------- half_type_traits.hpp - DPC++ Explicit SIMD API ----------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // Implementation of SIMD element type traits for the sycl::half type. //===----------------------------------------------------------------------===// #pragma once #include <sycl/ext/intel/esimd/detail/elem_type_traits.hpp> #include <sycl/half_type.hpp> /// @cond ESIMD_DETAIL namespace sycl { __SYCL_INLINE_VER_NAMESPACE(_V1) { namespace ext::intel::esimd::detail { // Standalone definitions to use w/o instantiating element_type_traits. #ifdef __SYCL_DEVICE_ONLY__ // Can't use sycl::detail::half_impl::StorageT as RawT for both host and // device as it still maps to struct on/ host (even though the struct is a // trivial wrapper around uint16_t), and for ESIMD we need a type which can be // an element of clang vector. using half_raw_type = sycl::detail::half_impl::StorageT; // On device, _Float16 is native Cpp type, so it is the enclosing C++ type using half_enclosing_cpp_type = half_raw_type; #else using half_raw_type = uint16_t; using half_enclosing_cpp_type = float; #endif // __SYCL_DEVICE_ONLY__ template <> struct element_type_traits<sycl::half> { using RawT = half_raw_type; using EnclosingCppT = half_enclosing_cpp_type; #ifdef __SYCL_DEVICE_ONLY__ // On device, operations on half are translated to operations on _Float16, // which is natively supported by the device compiler static inline constexpr bool use_native_cpp_ops = true; #else // On host, we can't use native Cpp '+', '-' etc. over uint16_t to emulate the // operations on half type. static inline constexpr bool use_native_cpp_ops = false; #endif // __SYCL_DEVICE_ONLY__ static inline constexpr bool is_floating_point = true; }; // ------------------- Type conversion traits template <int N> struct vector_conversion_traits<sycl::half, N> { using StdT = half_enclosing_cpp_type; using RawT = half_raw_type; static ESIMD_INLINE vector_type_t<RawT, N> convert_to_raw(vector_type_t<StdT, N> Val) #ifdef __SYCL_DEVICE_ONLY__ // use_native_cpp_ops trait is true, so must not be implemented ; #else { vector_type_t<half_raw_type, N> Output = 0; for (int i = 0; i < N; i += 1) { // 1. Convert Val[i] to float (x) using c++ static_cast // 2. Convert x to half (using float2half) // 3. Output[i] = half_of(x) Output[i] = ::sycl::detail::float2Half(static_cast<float>(Val[i])); } return Output; } #endif // __SYCL_DEVICE_ONLY__ static ESIMD_INLINE vector_type_t<StdT, N> convert_to_cpp(vector_type_t<RawT, N> Val) #ifdef __SYCL_DEVICE_ONLY__ // use_native_cpp_ops trait is true, so must not be implemented ; #else { vector_type_t<StdT, N> Output; for (int i = 0; i < N; i += 1) { // 1. Convert Val[i] to float y(using half2float) // 2. Convert y to StdT using c++ static_cast // 3. Store in Output[i] Output[i] = static_cast<StdT>(::sycl::detail::half2Float(Val[i])); } return Output; } #endif // __SYCL_DEVICE_ONLY__ }; // Proxy class to access bit representation of a wrapper type both on host and // device. Declared as friend to the sycl::half. // TODO add this functionality to sycl type implementation? With C++20, // std::bit_cast should be a good replacement. class WrapperElementTypeProxy { public: static ESIMD_INLINE half_raw_type bitcast_to_raw_scalar(sycl::half Val) { #ifdef __SYCL_DEVICE_ONLY__ return Val.Data; #else return Val.Data.Buf; #endif // __SYCL_DEVICE_ONLY__ } static ESIMD_INLINE sycl::half bitcast_to_wrapper_scalar(half_raw_type Val) { #ifndef __SYCL_DEVICE_ONLY__ return sycl::half(::sycl::detail::host_half_impl::half(Val)); #else sycl::half Res; Res.Data = Val; return Res; #endif // __SYCL_DEVICE_ONLY__ } }; template <> struct scalar_conversion_traits<sycl::half> { using RawT = half_raw_type; static ESIMD_INLINE RawT bitcast_to_raw(sycl::half Val) { return WrapperElementTypeProxy::bitcast_to_raw_scalar(Val); } static ESIMD_INLINE sycl::half bitcast_to_wrapper(RawT Val) { return WrapperElementTypeProxy::bitcast_to_wrapper_scalar(Val); } }; #ifdef __SYCL_DEVICE_ONLY__ template <> struct is_esimd_arithmetic_type<half_raw_type, void> : std::true_type {}; #endif // __SYCL_DEVICE_ONLY__ // Misc inline std::ostream &operator<<(std::ostream &O, sycl::half const &rhs) { O << static_cast<float>(rhs); return O; } inline std::istream &operator>>(std::istream &I, sycl::half &rhs) { float ValFloat = 0.0f; I >> ValFloat; rhs = ValFloat; return I; } } // namespace ext::intel::esimd::detail } // __SYCL_INLINE_VER_NAMESPACE(_V1) } // namespace sycl /// @endcond ESIMD_DETAIL
[ "noreply@github.com" ]
triSYCL.noreply@github.com
a67d02d8cec26e96bf5ef8fdcc8ab3b5b8536a43
7b00453292034c8262f8fa620ca7699383f6b6d1
/postfix.cpp
94661b3082662fc17b606eb34444db2091c9c716
[]
no_license
ImRajendra/Practise-programs
dadb807c263ac4b3f7dea7525eee9891aa4f6c05
5a6ee5a36182521e49c78708255068f2d257341f
refs/heads/master
2020-05-22T07:17:47.316229
2019-05-12T14:11:09
2019-05-12T14:11:09
186,262,220
0
0
null
null
null
null
UTF-8
C++
false
false
1,128
cpp
#include<iostream> #include<stdlib.h> using namespace std; int top=-1; char skt[20]; void push(char x) { skt[++top]=x; } int pop() { return skt[top--]; } bool empty() { if(top==-1) return true; else return false; } int pr(char ch) { switch(ch) { case'#':return 0; case'+': case'-': return 2; case')':return 1; case'*': case'/':return 3; } } int main() { char infix[20],postfix[20],ch,e,s[50]; int i=0; int k=0; cout<<"Enter the infix expresion\n"; cin>>infix; push('#'); while((ch=infix[i++])!='\0') { if(ch=='(') push(ch) ; if(isdigit(ch)) postfix[k++]=ch; else if(ch==')') { while(s[top]!='(') postfix[k++]=pop(); e=pop(); } else { while(pr(s[top])>pr(ch)) postfix[k++]=pop(); push(ch); } } while(s[top]!='#') postfix[k++]=pop(); postfix[k]='\0'; cout<<"given infix\t" while(*s) { cout<< } cout<<"postfix expresion"<<postfix<<"\n"; }
[ "noreply@github.com" ]
ImRajendra.noreply@github.com
40651ebd498bd83f40b8567b6a7b92c7eca5b539
a8ae52d335a392ca10fc7e4e562139a7b6e942ee
/src/server/game/Movement/FollowerReference.cpp
140027a22766c679f0e9d5353a332a047e917247
[]
no_license
bromacia/ProjectAxium
54f3c622b17039c94b02914f22a1762cd635b327
e815318616a57a343f9883340af7b8cb93007682
refs/heads/master
2021-04-27T11:03:48.445914
2017-09-09T18:16:53
2017-09-09T18:16:53
122,552,525
1
0
null
2018-02-23T00:29:29
2018-02-23T00:29:28
null
UTF-8
C++
false
false
361
cpp
#include "Unit.h" #include "TargetedMovementGenerator.h" #include "FollowerReference.h" void FollowerReference::targetObjectBuildLink() { getTarget()->addFollower(this); } void FollowerReference::targetObjectDestroyLink() { getTarget()->removeFollower(this); } void FollowerReference::sourceObjectDestroyLink() { getSource()->stopFollowing(); }
[ "saeshyls@gmail.com" ]
saeshyls@gmail.com
964a6cff78c7f0703372d7f4cea6392f6e7288c0
4f4caf4f3202082b03d7dfd6cfa517fc73c5cef0
/Point.cpp
c5f6b2b4865905bac19ae9aed4e8e7be30755383
[]
no_license
hlongn2469/GreedyRobot
e18ef7a5f1521e0cdb69fcfa2c9fd160a88426be
cbc9dc583155b08adf64754586e3c0758259716b
refs/heads/main
2023-03-03T01:09:53.092732
2021-02-13T03:00:28
2021-02-13T03:00:28
338,484,728
1
0
null
null
null
null
UTF-8
C++
false
false
1,133
cpp
//Point.cpp //CSS 342 Program2 //Implemented by_ Kray_ Nguy_en on 11/2/2020 #include "Point.h" #include <cstdlib> #include <iostream> using namespace std; Point::~Point(){ } Point::Point(){ this -> x_ = 0; this -> y_ = 0; } Point::Point(int x_, int y_){ this -> x_ = x_; this -> y_ = y_; } int Point::getX(){ return x_; } int Point::getY(){ return y_; } bool Point::setCoordinates(int x_, int y_){ this -> x_ = x_; this -> y_ = y_; return true; } Point Point::operator+(const Point &other) const{ Point retVal = *this; retVal.x_ += other.x_; retVal.y_ += other.y_; return retVal; } Point Point::operator-(const Point &other) const{ Point retVal = *this; retVal.x_ -= other.x_; retVal.y_ -= other.y_; return retVal; } bool Point::operator==(const Point &other) const{ return ((this -> x_ == other.x_) && (this -> y_ == other.y_)); } bool Point::operator!=(const Point &other) const{ return ((this -> x_ != other.x_) || (this -> y_ != other.y_)); } ostream& operator<<(ostream &outStream, const Point &other){ outStream << "(" << other.x_ << ", " << other.y_ << ")"; return outStream; }
[ "noreply@github.com" ]
hlongn2469.noreply@github.com
0b4ddd4d81e8bbebf02b4eb608a6c1b452fee0bc
6ab549e40f1bff79b7b7d00ae76776cd00d96087
/Project3D/Character.h
1b7749d182ece7861f7f439c480c3f4a94580521
[]
no_license
BilelAvans/Menghindar_Diri
89b5bc6d42aab2606d1e4f44fca77051a9764292
4c0cb1544fef9fad4fbf953bd223fc8e7ad9429e
refs/heads/master
2021-01-17T10:19:25.951253
2017-03-21T16:34:34
2017-03-21T16:34:34
57,043,079
0
0
null
2016-06-20T11:44:25
2016-04-25T13:17:56
HTML
UTF-8
C++
false
false
220
h
#pragma once #include <iostream> #include "ModelObject.h" class Character { // Our model ModelObject Model; std::string Name; public: Character(ModelObject model, std::string naam); ModelObject getModel(); };
[ "bbghiel@student.avans.nl" ]
bbghiel@student.avans.nl
334271e7a9702a32f20f521cb6f699d3c77a5206
740afff2a8cfef1494680a462adda5032946f690
/gpudb/protocol/admin_add_ranks.h
daa332d66aa3bba6b13944466198474cb16a0c74
[ "MIT" ]
permissive
kyle-sutton/kinetica-api-cpp
e392451488ae1053e4ffdaf2e1484117986e546b
9383702ca9ed3a096ed30bf50349e46a2fa4dc84
refs/heads/master
2023-03-14T02:25:12.258708
2021-03-05T20:31:22
2021-03-05T20:31:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,942
h
/* * This file was autogenerated by the GPUdb schema processor. * * DO NOT EDIT DIRECTLY. */ #ifndef __ADMIN_ADD_RANKS_H__ #define __ADMIN_ADD_RANKS_H__ namespace gpudb { /** * A set of input parameters for {@link * #adminAddRanks(const AdminAddRanksRequest&) const}. * <p> * Add one or more ranks to an existing Kinetica cluster. The new ranks * will not contain any data initially (other than replicated tables) and * will not be assigned any shards. To rebalance data and shards across the * cluster, use {@link * #adminRebalance(const AdminRebalanceRequest&) const}. * <p> * The database must be offline for this operation, see {@link * #adminOffline(const AdminOfflineRequest&) const} * <p> * For example, if attempting to add three new ranks (two ranks on host * 172.123.45.67 and one rank on host 172.123.45.68) to a Kinetica cluster * with additional configuration parameters: * <p> * * @a hosts * would be an array including 172.123.45.67 in the first two indices * (signifying two ranks being added to host 172.123.45.67) and * 172.123.45.68 in the last index (signifying one rank being added * to host 172.123.45.67) * * @a configParams * would be an array of maps, with each map corresponding to the ranks * being added in @a hosts. The key of each map would be * the configuration parameter name and the value would be the * parameter's value, e.g. '{"rank.gpu":"1"}' * This endpoint's processing includes copying all replicated table data to * the new rank(s) and therefore could take a long time. The API call may * time out if run directly. It is recommended to run this endpoint * asynchronously via {@link * #createJob(const CreateJobRequest&) const}. */ struct AdminAddRanksRequest { /** * Constructs an AdminAddRanksRequest object with default parameter * values. */ AdminAddRanksRequest() : hosts(std::vector<std::string>()), configParams(std::vector<std::map<std::string, std::string> >()), options(std::map<std::string, std::string>()) { } /** * Constructs an AdminAddRanksRequest object with the specified * parameters. * * @param[in] hosts_ Array of host IP addresses (matching a * hostN.address from the gpudb.conf file), or host * identifiers (e.g. 'host0' from the gpudb.conf * file), on which to add ranks to the cluster. The * hosts must already be in the cluster. If needed * beforehand, to add a new host to the cluster use * /admin/add/host. Include the same entry as many * times as there are ranks to add to the cluster, * e.g., if two ranks on host 172.123.45.67 should * be added, @a hosts could look like * '["172.123.45.67", "172.123.45.67"]'. All ranks * will be added simultaneously, i.e. they're not * added in the order of this array. Each entry in * this array corresponds to the entry at the same * index in the @a configParams. * @param[in] configParams_ Array of maps containing configuration * parameters to apply to the new ranks found * in @a hosts. For example, * '{"rank.gpu":"2", * "tier.ram.rank.limit":"10000000000"}'. * Currently, the available parameters are * rank-specific parameters in the <a * href="../../../config/#network" * target="_top">Network</a>, <a * href="../../../config/#hardware" * target="_top">Hardware</a>, <a * href="../../../config/#text-search" * target="_top">Text Search</a>, and <a * href="../../../config/#ram-tier" * target="_top">RAM Tiered Storage</a> * sections in the gpudb.conf file, with the * key exception of the 'rankN.host' settings * in the Network section that will be * determined by @a hosts instead. Though * many of these configuration parameters * typically are affixed with 'rankN' in the * gpudb.conf file (where N is the rank * number), the 'N' should be omitted in @a * configParams as the new rank number(s) are * not allocated until the ranks have been * added to the cluster. Each entry in this * array corresponds to the entry at the same * index in the @a hosts. This array must * either be completely empty or have the * same number of elements as the @a hosts. * An empty @a configParams array will result * in the new ranks being set with default * parameters. * @param[in] options_ Optional parameters. * <ul> * <li> gpudb::admin_add_ranks_dry_run: If * @a true, only validation checks will be * performed. No ranks are added. * <ul> * <li> gpudb::admin_add_ranks_true * <li> gpudb::admin_add_ranks_false * </ul> * The default value is * gpudb::admin_add_ranks_false. * </ul> * */ AdminAddRanksRequest(const std::vector<std::string>& hosts_, const std::vector<std::map<std::string, std::string> >& configParams_, const std::map<std::string, std::string>& options_): hosts( hosts_ ), configParams( configParams_ ), options( options_ ) { } std::vector<std::string> hosts; std::vector<std::map<std::string, std::string> > configParams; std::map<std::string, std::string> options; }; } namespace avro { template<> struct codec_traits<gpudb::AdminAddRanksRequest> { static void encode(Encoder& e, const gpudb::AdminAddRanksRequest& v) { ::avro::encode(e, v.hosts); ::avro::encode(e, v.configParams); ::avro::encode(e, v.options); } static void decode(Decoder& d, gpudb::AdminAddRanksRequest& v) { if (::avro::ResolvingDecoder *rd = dynamic_cast< ::avro::ResolvingDecoder*>(&d)) { const std::vector<size_t> fo = rd->fieldOrder(); for (std::vector<size_t>::const_iterator it = fo.begin(); it != fo.end(); ++it) { switch (*it) { case 0: ::avro::decode(d, v.hosts); break; case 1: ::avro::decode(d, v.configParams); break; case 2: ::avro::decode(d, v.options); break; default: break; } } } else { ::avro::decode(d, v.hosts); ::avro::decode(d, v.configParams); ::avro::decode(d, v.options); } } }; } namespace gpudb { /** * A set of output parameters for {@link * #adminAddRanks(const AdminAddRanksRequest&) const}. * <p> * Add one or more ranks to an existing Kinetica cluster. The new ranks * will not contain any data initially (other than replicated tables) and * will not be assigned any shards. To rebalance data and shards across the * cluster, use {@link * #adminRebalance(const AdminRebalanceRequest&) const}. * <p> * The database must be offline for this operation, see {@link * #adminOffline(const AdminOfflineRequest&) const} * <p> * For example, if attempting to add three new ranks (two ranks on host * 172.123.45.67 and one rank on host 172.123.45.68) to a Kinetica cluster * with additional configuration parameters: * <p> * * @a hosts * would be an array including 172.123.45.67 in the first two indices * (signifying two ranks being added to host 172.123.45.67) and * 172.123.45.68 in the last index (signifying one rank being added * to host 172.123.45.67) * * @a configParams * would be an array of maps, with each map corresponding to the ranks * being added in @a hosts. The key of each map would be * the configuration parameter name and the value would be the * parameter's value, e.g. '{"rank.gpu":"1"}' * This endpoint's processing includes copying all replicated table data to * the new rank(s) and therefore could take a long time. The API call may * time out if run directly. It is recommended to run this endpoint * asynchronously via {@link * #createJob(const CreateJobRequest&) const}. */ struct AdminAddRanksResponse { /** * Constructs an AdminAddRanksResponse object with default parameter * values. */ AdminAddRanksResponse() : addedRanks(std::vector<std::string>()), info(std::map<std::string, std::string>()) { } std::vector<std::string> addedRanks; std::map<std::string, std::string> info; }; } namespace avro { template<> struct codec_traits<gpudb::AdminAddRanksResponse> { static void encode(Encoder& e, const gpudb::AdminAddRanksResponse& v) { ::avro::encode(e, v.addedRanks); ::avro::encode(e, v.info); } static void decode(Decoder& d, gpudb::AdminAddRanksResponse& v) { if (::avro::ResolvingDecoder *rd = dynamic_cast< ::avro::ResolvingDecoder*>(&d)) { const std::vector<size_t> fo = rd->fieldOrder(); for (std::vector<size_t>::const_iterator it = fo.begin(); it != fo.end(); ++it) { switch (*it) { case 0: ::avro::decode(d, v.addedRanks); break; case 1: ::avro::decode(d, v.info); break; default: break; } } } else { ::avro::decode(d, v.addedRanks); ::avro::decode(d, v.info); } } }; } #endif
[ "mmahmud@kinetica.com" ]
mmahmud@kinetica.com
c3177aa14651f1a4e3a1434dc6ec59aa6bdd0732
b7f1b4df5d350e0edf55521172091c81f02f639e
/components/exo/data_device_unittest.cc
71f836a732ecefb5fdd5aacb4ef16fa84fb55f3e
[ "BSD-3-Clause" ]
permissive
blusno1/chromium-1
f13b84547474da4d2702341228167328d8cd3083
9dd22fe142b48f14765a36f69344ed4dbc289eb3
refs/heads/master
2023-05-17T23:50:16.605396
2018-01-12T19:39:49
2018-01-12T19:39:49
117,339,342
4
2
NOASSERTION
2020-07-17T07:35:37
2018-01-13T11:48:57
null
UTF-8
C++
false
false
9,218
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/exo/data_device.h" #include <memory> #include <string> #include <vector> #include "ash/shell.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "components/exo/data_device_delegate.h" #include "components/exo/data_offer.h" #include "components/exo/data_offer_delegate.h" #include "components/exo/file_helper.h" #include "components/exo/seat.h" #include "components/exo/surface.h" #include "components/exo/test/exo_test_base.h" #include "components/exo/test/exo_test_helper.h" #include "ui/aura/client/focus_client.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/base/dragdrop/drop_target_event.h" #include "ui/base/dragdrop/os_exchange_data.h" #include "ui/events/event.h" namespace exo { namespace { enum class DataEvent { kOffer, kEnter, kLeave, kMotion, kDrop, kDestroy, kSelection }; class TestDataOfferDelegate : public DataOfferDelegate { public: ~TestDataOfferDelegate() override {} // Overridden from DataOfferDelegate: void OnDataOfferDestroying(DataOffer* offer) override { delete this; } void OnOffer(const std::string& mime_type) override {} void OnSourceActions( const base::flat_set<DndAction>& source_actions) override {} void OnAction(DndAction action) override {} }; class TestDataDeviceDelegate : public DataDeviceDelegate { public: TestDataDeviceDelegate() {} size_t PopEvents(std::vector<DataEvent>* out) { out->swap(events_); events_.clear(); return out->size(); } Surface* entered_surface() const { return entered_surface_; } void DeleteDataOffer() { data_offer_.reset(); } void set_can_accept_data_events_for_surface(bool value) { can_accept_data_events_for_surface_ = value; } // Overridden from DataDeviceDelegate: void OnDataDeviceDestroying(DataDevice* data_device) override { events_.push_back(DataEvent::kDestroy); } DataOffer* OnDataOffer() override { events_.push_back(DataEvent::kOffer); data_offer_.reset(new DataOffer(new TestDataOfferDelegate)); return data_offer_.get(); } void OnEnter(Surface* surface, const gfx::PointF& location, const DataOffer& data_offer) override { events_.push_back(DataEvent::kEnter); entered_surface_ = surface; } void OnLeave() override { events_.push_back(DataEvent::kLeave); } void OnMotion(base::TimeTicks time_stamp, const gfx::PointF& location) override { events_.push_back(DataEvent::kMotion); } void OnDrop() override { events_.push_back(DataEvent::kDrop); } void OnSelection(const DataOffer& data_offer) override { events_.push_back(DataEvent::kSelection); } bool CanAcceptDataEventsForSurface(Surface* surface) override { return can_accept_data_events_for_surface_; } private: std::vector<DataEvent> events_; std::unique_ptr<DataOffer> data_offer_; Surface* entered_surface_ = nullptr; bool can_accept_data_events_for_surface_ = true; DISALLOW_COPY_AND_ASSIGN(TestDataDeviceDelegate); }; class TestFileHelper : public FileHelper { public: TestFileHelper() = default; // Overridden from FileHelper: std::string GetMimeTypeForUriList() const override { return ""; } bool ConvertPathToUrl(const base::FilePath& path, GURL* out) override { return true; } private: DISALLOW_COPY_AND_ASSIGN(TestFileHelper); }; class TestSeat : public Seat { public: TestSeat() {} void set_focused_surface(Surface* surface) { surface_ = surface; } // Overriden from Seat: Surface* GetFocusedSurface() override { return surface_; } private: Surface* surface_ = nullptr; DISALLOW_COPY_AND_ASSIGN(TestSeat); }; class DataDeviceTest : public test::ExoTestBase { public: void SetUp() override { test::ExoTestBase::SetUp(); seat_ = std::make_unique<TestSeat>(); device_ = std::make_unique<DataDevice>(&delegate_, seat_.get(), &file_helper_); data_.SetString(base::string16(base::ASCIIToUTF16("Test data"))); surface_ = std::make_unique<Surface>(); } void TearDown() override { surface_.reset(); device_.reset(); seat_.reset(); test::ExoTestBase::TearDown(); } protected: TestDataDeviceDelegate delegate_; std::unique_ptr<TestSeat> seat_; TestFileHelper file_helper_; std::unique_ptr<DataDevice> device_; ui::OSExchangeData data_; std::unique_ptr<Surface> surface_; }; TEST_F(DataDeviceTest, Destroy) { std::vector<DataEvent> events; device_.reset(); ASSERT_EQ(1u, delegate_.PopEvents(&events)); EXPECT_EQ(DataEvent::kDestroy, events[0]); } TEST_F(DataDeviceTest, DataEventsDrop) { ui::DropTargetEvent event(data_, gfx::Point(), gfx::Point(), ui::DragDropTypes::DRAG_MOVE); ui::Event::DispatcherApi(&event).set_target(surface_->window()); std::vector<DataEvent> events; device_->OnDragEntered(event); ASSERT_EQ(2u, delegate_.PopEvents(&events)); EXPECT_EQ(DataEvent::kOffer, events[0]); EXPECT_EQ(DataEvent::kEnter, events[1]); EXPECT_EQ(ui::DragDropTypes::DRAG_LINK, device_->OnDragUpdated(event)); ASSERT_EQ(1u, delegate_.PopEvents(&events)); EXPECT_EQ(DataEvent::kMotion, events[0]); device_->OnPerformDrop(event); ASSERT_EQ(1u, delegate_.PopEvents(&events)); EXPECT_EQ(DataEvent::kDrop, events[0]); } TEST_F(DataDeviceTest, DataEventsExit) { ui::DropTargetEvent event(data_, gfx::Point(), gfx::Point(), ui::DragDropTypes::DRAG_MOVE); ui::Event::DispatcherApi(&event).set_target(surface_->window()); std::vector<DataEvent> events; device_->OnDragEntered(event); ASSERT_EQ(2u, delegate_.PopEvents(&events)); EXPECT_EQ(DataEvent::kOffer, events[0]); EXPECT_EQ(DataEvent::kEnter, events[1]); EXPECT_EQ(ui::DragDropTypes::DRAG_LINK, device_->OnDragUpdated(event)); ASSERT_EQ(1u, delegate_.PopEvents(&events)); EXPECT_EQ(DataEvent::kMotion, events[0]); device_->OnDragExited(); ASSERT_EQ(1u, delegate_.PopEvents(&events)); EXPECT_EQ(DataEvent::kLeave, events[0]); } TEST_F(DataDeviceTest, DeleteDataOfferDuringDrag) { ui::DropTargetEvent event(data_, gfx::Point(), gfx::Point(), ui::DragDropTypes::DRAG_MOVE); ui::Event::DispatcherApi(&event).set_target(surface_->window()); std::vector<DataEvent> events; device_->OnDragEntered(event); ASSERT_EQ(2u, delegate_.PopEvents(&events)); EXPECT_EQ(DataEvent::kOffer, events[0]); EXPECT_EQ(DataEvent::kEnter, events[1]); delegate_.DeleteDataOffer(); EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, device_->OnDragUpdated(event)); EXPECT_EQ(0u, delegate_.PopEvents(&events)); device_->OnPerformDrop(event); EXPECT_EQ(0u, delegate_.PopEvents(&events)); } TEST_F(DataDeviceTest, NotAcceptDataEventsForSurface) { ui::DropTargetEvent event(data_, gfx::Point(), gfx::Point(), ui::DragDropTypes::DRAG_MOVE); ui::Event::DispatcherApi(&event).set_target(surface_->window()); std::vector<DataEvent> events; delegate_.set_can_accept_data_events_for_surface(false); device_->OnDragEntered(event); EXPECT_EQ(0u, delegate_.PopEvents(&events)); EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, device_->OnDragUpdated(event)); EXPECT_EQ(0u, delegate_.PopEvents(&events)); device_->OnPerformDrop(event); EXPECT_EQ(0u, delegate_.PopEvents(&events)); } TEST_F(DataDeviceTest, ClipboardCopy) { // Selection event sent when getting a focus. device_->OnSurfaceFocusing(surface_.get()); std::vector<DataEvent> events; ASSERT_EQ(2u, delegate_.PopEvents(&events)); EXPECT_EQ(DataEvent::kOffer, events[0]); EXPECT_EQ(DataEvent::kSelection, events[1]); // Next focus does not send selection. device_->OnSurfaceFocusing(surface_.get()); EXPECT_EQ(0u, delegate_.PopEvents(&events)); // Clipboard change device_->OnClipboardDataChanged(); ASSERT_EQ(2u, delegate_.PopEvents(&events)); EXPECT_EQ(DataEvent::kOffer, events[0]); EXPECT_EQ(DataEvent::kSelection, events[1]); // Losing focuse does not create events. device_->OnSurfaceFocusing(nullptr); EXPECT_EQ(0u, delegate_.PopEvents(&events)); } TEST_F(DataDeviceTest, ClipboardCopyWithoutFocus) { device_->OnClipboardDataChanged(); std::vector<DataEvent> events; EXPECT_EQ(0u, delegate_.PopEvents(&events)); } TEST_F(DataDeviceTest, ClipboardDeviceCreatedAfterFocus) { seat_->set_focused_surface(surface_.get()); device_.reset(); std::vector<DataEvent> events; delegate_.PopEvents(&events); device_ = std::make_unique<DataDevice>(&delegate_, seat_.get(), &file_helper_); ASSERT_EQ(2u, delegate_.PopEvents(&events)); EXPECT_EQ(DataEvent::kOffer, events[0]); EXPECT_EQ(DataEvent::kSelection, events[1]); } TEST_F(DataDeviceTest, ClipboardFocusedSurfaceDestroyed) { device_->OnSurfaceFocusing(surface_.get()); surface_.reset(); std::vector<DataEvent> events; delegate_.PopEvents(&events); device_->OnClipboardDataChanged(); EXPECT_EQ(0u, delegate_.PopEvents(&events)); } } // namespace } // namespace exo
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
3c925f6a888299efeb28a771fe73a7d0a56c5b97
c1d172eb019c7a4783a0758d534402e2b82233fb
/src/wtl_control_examples/Kibbles/DownloadFileDlg.h
df63aefb52da49262cf971fa1beed06addc21f6b
[]
no_license
zhengfish/wtl-examples
e0218432e43900c0824dbadcaa0a9041043fc896
300d59bcb4421871e404d4932513c83f1f155538
refs/heads/master
2020-03-29T08:00:54.306880
2017-09-20T16:06:48
2017-09-20T16:06:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,356
h
// DownloadFileDlg.h: interface for the CDownloadFileDlg class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_DOWNLOADFILEDLG_H__D93E5C00_2951_424C_8754_A031F1F9DB9F__INCLUDED_) #define AFX_DOWNLOADFILEDLG_H__D93E5C00_2951_424C_8754_A031F1F9DB9F__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CDownloadFileDlg : public CDialogImpl<CDownloadFileDlg>, public CWinDataExchange<CDownloadFileDlg> { public: enum { IDD = IDD_DOWNLOAD_FILE }; // Construction CDownloadFileDlg(); // Maps BEGIN_MSG_MAP(CDownloadFileDlg) MSG_WM_INITDIALOG(OnInitDialog) COMMAND_ID_HANDLER_EX(IDC_BROWSE, OnBrowse) COMMAND_ID_HANDLER_EX(IDOK, OnOK) COMMAND_ID_HANDLER_EX(IDCANCEL, OnCancel) END_MSG_MAP() BEGIN_DDX_MAP(CDownloadFileDlg) DDX_TEXT(IDC_URL, m_sURL) DDX_TEXT(IDC_LOCAL_FILENAME, m_sLocalFilename) END_DDX_MAP() // Message handlers BOOL OnInitDialog(HWND hwndFocus, LPARAM lParam); // Command handlers void OnBrowse(UINT uCode, int nID, HWND hwndCtrl); void OnOK(UINT uCode, int nID, HWND hwndCtrl); void OnCancel(UINT uCode, int nID, HWND hwndCtrl); // DDX data CString m_sURL, m_sLocalFilename; }; #endif // !defined(AFX_DOWNLOADFILEDLG_H__D93E5C00_2951_424C_8754_A031F1F9DB9F__INCLUDED_)
[ "wyrover@gmail.com" ]
wyrover@gmail.com
0afd8e37c327203f823473150ddc75a729700406
6d4398f454ed278c0d3f6e166fa0e1370ebaa0ad
/software/QGroundStation/plugins/uavobjects/gcs/pathplan.cpp
383093f5e61dc63d59e972a4d71467dd5f480f42
[]
no_license
nongxiaoming/QGroundStation
4b27cb2165b91b0510210e65a781daf5fc919c64
0a491c9d910e465633c232ecd74a7c283def5301
refs/heads/master
2020-05-18T11:03:00.538465
2014-10-08T16:48:51
2014-10-08T16:48:51
19,404,192
1
1
null
null
null
null
UTF-8
C++
false
false
6,282
cpp
/** ****************************************************************************** * * @file pathplan.cpp * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @see The GNU Public License (GPL) Version 3 * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup UAVObjectsPlugin UAVObjects Plugin * @{ * * @note Object definition file: pathplan.xml. * This is an automatically generated file. * DO NOT modify manually. * * @brief The UAVUObjects GCS plugin *****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "pathplan.h" #include "uavobjectfield.h" const QString PathPlan::NAME = QString("PathPlan"); const QString PathPlan::DESCRIPTION = QString("Flight plan informations"); const QString PathPlan::CATEGORY = QString("Navigation"); /** * Constructor */ PathPlan::PathPlan(): UAVDataObject(OBJID, ISSINGLEINST, ISSETTINGS, NAME) { // Create fields QList<UAVObjectField *> fields; QStringList WaypointCountElemNames; WaypointCountElemNames.append("0"); fields.append( new UAVObjectField(QString("WaypointCount"), QString(""), UAVObjectField::UINT16, WaypointCountElemNames, QStringList(), QString(""))); QStringList PathActionCountElemNames; PathActionCountElemNames.append("0"); fields.append( new UAVObjectField(QString("PathActionCount"), QString(""), UAVObjectField::UINT16, PathActionCountElemNames, QStringList(), QString(""))); QStringList CrcElemNames; CrcElemNames.append("0"); fields.append( new UAVObjectField(QString("Crc"), QString(""), UAVObjectField::UINT8, CrcElemNames, QStringList(), QString(""))); // Initialize object initializeFields(fields, (quint8 *)&data, NUMBYTES); // Set the default field values setDefaultFieldValues(); // Set the object description setDescription(DESCRIPTION); // Set the Category of this object type setCategory(CATEGORY); connect(this, SIGNAL(objectUpdated(UAVObject *)), SLOT(emitNotifications())); } /** * Get the default metadata for this object */ UAVObject::Metadata PathPlan::getDefaultMetadata() { UAVObject::Metadata metadata; metadata.flags = ACCESS_READONLY << UAVOBJ_ACCESS_SHIFT | ACCESS_READWRITE << UAVOBJ_GCS_ACCESS_SHIFT | 1 << UAVOBJ_TELEMETRY_ACKED_SHIFT | 1 << UAVOBJ_GCS_TELEMETRY_ACKED_SHIFT | UPDATEMODE_MANUAL << UAVOBJ_TELEMETRY_UPDATE_MODE_SHIFT | UPDATEMODE_MANUAL << UAVOBJ_GCS_TELEMETRY_UPDATE_MODE_SHIFT | UPDATEMODE_MANUAL << UAVOBJ_LOGGING_UPDATE_MODE_SHIFT; metadata.flightTelemetryUpdatePeriod = 0; metadata.gcsTelemetryUpdatePeriod = 0; metadata.loggingUpdatePeriod = 0; return metadata; } /** * Initialize object fields with the default values. * If a default value is not specified the object fields * will be initialized to zero. */ void PathPlan::setDefaultFieldValues() { } /** * Get the object data fields */ PathPlan::DataFields PathPlan::getData() { QMutexLocker locker(mutex); return data; } /** * Set the object data fields */ void PathPlan::setData(const DataFields& data) { QMutexLocker locker(mutex); // Get metadata Metadata mdata = getMetadata(); // Update object if the access mode permits if (UAVObject::GetGcsAccess(mdata) == ACCESS_READWRITE) { this->data = data; emit objectUpdatedAuto(this); // trigger object updated event emit objectUpdated(this); } } void PathPlan::emitNotifications() { //if (data.WaypointCount != oldData.WaypointCount) emit WaypointCountChanged(data.WaypointCount); //if (data.PathActionCount != oldData.PathActionCount) emit PathActionCountChanged(data.PathActionCount); //if (data.Crc != oldData.Crc) emit CrcChanged(data.Crc); } /** * Create a clone of this object, a new instance ID must be specified. * Do not use this function directly to create new instances, the * UAVObjectManager should be used instead. */ UAVDataObject *PathPlan::clone(quint32 instID) { PathPlan *obj = new PathPlan(); obj->initialize(instID, this->getMetaObject()); return obj; } /** * Create a clone of this object only to be used to retrieve defaults */ UAVDataObject *PathPlan::dirtyClone() { PathPlan *obj = new PathPlan(); return obj; } /** * Static function to retrieve an instance of the object. */ PathPlan *PathPlan::GetInstance(UAVObjectManager *objMngr, quint32 instID) { return dynamic_cast<PathPlan *>(objMngr->getObject(PathPlan::OBJID, instID)); } quint16 PathPlan::getWaypointCount() const { QMutexLocker locker(mutex); return data.WaypointCount; } void PathPlan::setWaypointCount(quint16 value) { mutex->lock(); bool changed = data.WaypointCount != value; data.WaypointCount = value; mutex->unlock(); if (changed) emit WaypointCountChanged(value); } quint16 PathPlan::getPathActionCount() const { QMutexLocker locker(mutex); return data.PathActionCount; } void PathPlan::setPathActionCount(quint16 value) { mutex->lock(); bool changed = data.PathActionCount != value; data.PathActionCount = value; mutex->unlock(); if (changed) emit PathActionCountChanged(value); } quint8 PathPlan::getCrc() const { QMutexLocker locker(mutex); return data.Crc; } void PathPlan::setCrc(quint8 value) { mutex->lock(); bool changed = data.Crc != value; data.Crc = value; mutex->unlock(); if (changed) emit CrcChanged(value); }
[ "nongxiaoming@gmail.com" ]
nongxiaoming@gmail.com
2c68f52fc50f0f42c68b24e82e360ddea744bc90
8a5f0eda7e09ef69b8a2a49b760397bc6200d134
/Templates/Tree/heavy_light_decomposition.cpp
b4a0ae6c44731267e0f7616a7991661fb0777e5f
[]
no_license
2997ms/Competitive-programming-problems
5ea54f2c63d963655cd046f33c8a85e03e314d51
23028f10875631897588613180fc5a8f2613e724
refs/heads/master
2022-12-15T08:54:56.269845
2022-12-08T21:45:09
2022-12-08T22:20:42
58,099,655
2
0
null
2019-09-01T01:40:51
2016-05-05T02:53:10
C++
UTF-8
C++
false
false
3,712
cpp
// https://www.lydsy.com/JudgeOnline/problem.php?id=1036 #include <algorithm> #include <cstdio> #include <cstring> #define lc o << 1 #define rc o << 1 | 1 const int maxn = 60010; const int inf = 2e9; int n, a, b, w[maxn], q, u, v; int cur, h[maxn], nxt[maxn], p[maxn]; int siz[maxn], top[maxn], son[maxn], dep[maxn], fa[maxn], dfn[maxn], rnk[maxn], cnt; char op[10]; inline void add_edge(int x, int y) { cur++; nxt[cur] = h[x]; h[x] = cur; p[cur] = y; } struct SegTree { int sum[maxn * 4], maxx[maxn * 4]; void build(int o, int l, int r) { if (l == r) { sum[o] = maxx[o] = w[rnk[l]]; return; } int mid = (l + r) >> 1; build(lc, l, mid); build(rc, mid + 1, r); sum[o] = sum[lc] + sum[rc]; maxx[o] = std::max(maxx[lc], maxx[rc]); } int query1(int o, int l, int r, int ql, int qr) // max { if (l > qr || r < ql) return -inf; if (ql <= l && r <= qr) return maxx[o]; int mid = (l + r) >> 1; return std::max(query1(lc, l, mid, ql, qr), query1(rc, mid + 1, r, ql, qr)); } int query2(int o, int l, int r, int ql, int qr) // sum { if (l > qr || r < ql) return 0; if (ql <= l && r <= qr) return sum[o]; int mid = (l + r) >> 1; return query2(lc, l, mid, ql, qr) + query2(rc, mid + 1, r, ql, qr); } void update(int o, int l, int r, int x, int t) { if (l == r) { maxx[o] = sum[o] = t; return; } int mid = (l + r) >> 1; if (x <= mid) update(lc, l, mid, x, t); else update(rc, mid + 1, r, x, t); sum[o] = sum[lc] + sum[rc]; maxx[o] = std::max(maxx[lc], maxx[rc]); } } st; void dfs1(int o) { son[o] = -1; siz[o] = 1; for (int j = h[o]; j; j = nxt[j]) if (!dep[p[j]]) { dep[p[j]] = dep[o] + 1; fa[p[j]] = o; dfs1(p[j]); siz[o] += siz[p[j]]; if (son[o] == -1 || siz[p[j]] > siz[son[o]]) son[o] = p[j]; } } void dfs2(int o, int t) { top[o] = t; cnt++; dfn[o] = cnt; rnk[cnt] = o; if (son[o] == -1) return; dfs2(son[o], t); for (int j = h[o]; j; j = nxt[j]) if (p[j] != son[o] && p[j] != fa[o]) dfs2(p[j], p[j]); } int querymax(int x, int y) { int ret = -inf, fx = top[x], fy = top[y]; while (fx != fy) { if (dep[fx] >= dep[fy]) ret = std::max(ret, st.query1(1, 1, n, dfn[fx], dfn[x])), x = fa[fx]; else ret = std::max(ret, st.query1(1, 1, n, dfn[fy], dfn[y])), y = fa[fy]; fx = top[x]; fy = top[y]; } if (x != y) { if (dfn[x] < dfn[y]) ret = std::max(ret, st.query1(1, 1, n, dfn[x], dfn[y])); else ret = std::max(ret, st.query1(1, 1, n, dfn[y], dfn[x])); } else ret = std::max(ret, st.query1(1, 1, n, dfn[x], dfn[y])); return ret; } int querysum(int x, int y) { int ret = 0, fx = top[x], fy = top[y]; while (fx != fy) { if (dep[fx] >= dep[fy]) ret += st.query2(1, 1, n, dfn[fx], dfn[x]), x = fa[fx]; else ret += st.query2(1, 1, n, dfn[fy], dfn[y]), y = fa[fy]; fx = top[x]; fy = top[y]; } if (x != y) { if (dfn[x] < dfn[y]) ret += st.query2(1, 1, n, dfn[x], dfn[y]); else ret += st.query2(1, 1, n, dfn[y], dfn[x]); } else ret += st.query2(1, 1, n, dfn[x], dfn[y]); return ret; } int main() { scanf("%d", &n); for (int i = 1; i < n; i++) scanf("%d%d", &a, &b), add_edge(a, b), add_edge(b, a); for (int i = 1; i <= n; i++) scanf("%d", w + i); dep[1] = 1; dfs1(1); dfs2(1, 1); st.build(1, 1, n); scanf("%d", &q); while (q--) { scanf("%s%d%d", op, &u, &v); if (!strcmp(op, "CHANGE")) st.update(1, 1, n, dfn[u], v); if (!strcmp(op, "QMAX")) printf("%d\n", querymax(u, v)); if (!strcmp(op, "QSUM")) printf("%d\n", querysum(u, v)); } return 0; }
[ "wangchong756@gmail.com" ]
wangchong756@gmail.com
edf5512c052e301f9b099057af4be46b83d016c3
a58fa5b607256944fb3510e9959ed2c3b06a0d14
/samples/Test_JS/Classes/AppDelegate.cpp
322f72f0f98f5b68ed9d7ec34659cdd29be918ee
[]
no_license
fhaoquan/nano-CrossApp
16d4069063bafeb1ab800c7becdf6be59ff8ab4c
2d7fdbe661f412414c4740f9bffd3475be08968b
refs/heads/master
2020-05-23T08:17:25.829410
2016-09-18T06:50:22
2016-09-18T06:50:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,633
cpp
#include "AppDelegate.h" #include "ScriptingCore.h" #include "jsb_crossapp_auto.hpp" #include "crossapp_specifics.hpp" #include "js_crossapp_delegates_manual.hpp" USING_NS_CC; AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { } bool AppDelegate::applicationDidFinishLaunching() { // initialize director CAApplication* pDirector = CAApplication::getApplication(); CCEGLView* pEGLView = CCEGLView::sharedOpenGLView(); pDirector->setOpenGLView(pEGLView); ScriptingCore* sc = ScriptingCore::getInstance(); sc->addRegisterCallback(register_all_crossapp); sc->addRegisterCallback(register_cocos2dx_js_core); sc->addRegisterCallback(register_all_crossapp_delegates_manual); sc->start(); sc->runScript("script/jsb_boot.js"); sc->enableDebugger(); sc->runScript("script/jsb_crossapp.js"); CCScriptEngineManager::sharedManager()->setScriptEngine(sc); sc->runScript("js/main.js"); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { CAApplication::getApplication()->stopAnimation(); // if you use SimpleAudioEngine, it must be pause // SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { CAApplication::getApplication()->startAnimation(); // if you use SimpleAudioEngine, it must resume here // SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); }
[ "jtly1985@gmail.com" ]
jtly1985@gmail.com
95a09575335b907d6ed127fb3f6b25abc2a6d2f7
1524822de37e805b2c2c4c39d597f5a95d43a9fa
/tanks/Temp/StagingArea/Data/il2cppOutput/AssemblyU2DCSharp_Complete_ShellExplosion1270022755.h
ffeb09ac72c45b4329f31ee54a38378f2dbca9d0
[]
no_license
atiqahhhamzah/tanks_repo
de591638d242485cb84ebba60b226ce1fdce286b
6c5fc4a7eb818475d3ca07713382487b49f8d8e5
refs/heads/master
2021-01-11T21:45:24.868053
2017-01-14T02:05:24
2017-01-14T02:05:24
78,845,967
0
0
null
null
null
null
UTF-8
C++
false
false
4,495
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // UnityEngine.ParticleSystem struct ParticleSystem_t3394631041; // UnityEngine.AudioSource struct AudioSource_t1135106623; #include "UnityEngine_UnityEngine_MonoBehaviour1158329972.h" #include "UnityEngine_UnityEngine_LayerMask3188175821.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Complete.ShellExplosion struct ShellExplosion_t1270022755 : public MonoBehaviour_t1158329972 { public: // UnityEngine.LayerMask Complete.ShellExplosion::m_TankMask LayerMask_t3188175821 ___m_TankMask_2; // UnityEngine.ParticleSystem Complete.ShellExplosion::m_ExplosionParticles ParticleSystem_t3394631041 * ___m_ExplosionParticles_3; // UnityEngine.AudioSource Complete.ShellExplosion::m_ExplosionAudio AudioSource_t1135106623 * ___m_ExplosionAudio_4; // System.Single Complete.ShellExplosion::m_MaxDamage float ___m_MaxDamage_5; // System.Single Complete.ShellExplosion::m_ExplosionForce float ___m_ExplosionForce_6; // System.Single Complete.ShellExplosion::m_MaxLifeTime float ___m_MaxLifeTime_7; // System.Single Complete.ShellExplosion::m_ExplosionRadius float ___m_ExplosionRadius_8; public: inline static int32_t get_offset_of_m_TankMask_2() { return static_cast<int32_t>(offsetof(ShellExplosion_t1270022755, ___m_TankMask_2)); } inline LayerMask_t3188175821 get_m_TankMask_2() const { return ___m_TankMask_2; } inline LayerMask_t3188175821 * get_address_of_m_TankMask_2() { return &___m_TankMask_2; } inline void set_m_TankMask_2(LayerMask_t3188175821 value) { ___m_TankMask_2 = value; } inline static int32_t get_offset_of_m_ExplosionParticles_3() { return static_cast<int32_t>(offsetof(ShellExplosion_t1270022755, ___m_ExplosionParticles_3)); } inline ParticleSystem_t3394631041 * get_m_ExplosionParticles_3() const { return ___m_ExplosionParticles_3; } inline ParticleSystem_t3394631041 ** get_address_of_m_ExplosionParticles_3() { return &___m_ExplosionParticles_3; } inline void set_m_ExplosionParticles_3(ParticleSystem_t3394631041 * value) { ___m_ExplosionParticles_3 = value; Il2CppCodeGenWriteBarrier(&___m_ExplosionParticles_3, value); } inline static int32_t get_offset_of_m_ExplosionAudio_4() { return static_cast<int32_t>(offsetof(ShellExplosion_t1270022755, ___m_ExplosionAudio_4)); } inline AudioSource_t1135106623 * get_m_ExplosionAudio_4() const { return ___m_ExplosionAudio_4; } inline AudioSource_t1135106623 ** get_address_of_m_ExplosionAudio_4() { return &___m_ExplosionAudio_4; } inline void set_m_ExplosionAudio_4(AudioSource_t1135106623 * value) { ___m_ExplosionAudio_4 = value; Il2CppCodeGenWriteBarrier(&___m_ExplosionAudio_4, value); } inline static int32_t get_offset_of_m_MaxDamage_5() { return static_cast<int32_t>(offsetof(ShellExplosion_t1270022755, ___m_MaxDamage_5)); } inline float get_m_MaxDamage_5() const { return ___m_MaxDamage_5; } inline float* get_address_of_m_MaxDamage_5() { return &___m_MaxDamage_5; } inline void set_m_MaxDamage_5(float value) { ___m_MaxDamage_5 = value; } inline static int32_t get_offset_of_m_ExplosionForce_6() { return static_cast<int32_t>(offsetof(ShellExplosion_t1270022755, ___m_ExplosionForce_6)); } inline float get_m_ExplosionForce_6() const { return ___m_ExplosionForce_6; } inline float* get_address_of_m_ExplosionForce_6() { return &___m_ExplosionForce_6; } inline void set_m_ExplosionForce_6(float value) { ___m_ExplosionForce_6 = value; } inline static int32_t get_offset_of_m_MaxLifeTime_7() { return static_cast<int32_t>(offsetof(ShellExplosion_t1270022755, ___m_MaxLifeTime_7)); } inline float get_m_MaxLifeTime_7() const { return ___m_MaxLifeTime_7; } inline float* get_address_of_m_MaxLifeTime_7() { return &___m_MaxLifeTime_7; } inline void set_m_MaxLifeTime_7(float value) { ___m_MaxLifeTime_7 = value; } inline static int32_t get_offset_of_m_ExplosionRadius_8() { return static_cast<int32_t>(offsetof(ShellExplosion_t1270022755, ___m_ExplosionRadius_8)); } inline float get_m_ExplosionRadius_8() const { return ___m_ExplosionRadius_8; } inline float* get_address_of_m_ExplosionRadius_8() { return &___m_ExplosionRadius_8; } inline void set_m_ExplosionRadius_8(float value) { ___m_ExplosionRadius_8 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "atiqahamzah@gmail.com" ]
atiqahamzah@gmail.com
f3c2b3737eca67b67d0665c0fc6197e4bd935a56
240d466f2bdd940c0704cae23de6d07b8e96ba05
/f/f.cpp
7989435ec34e78b1e4776d782a474771bb9b118d
[]
no_license
cppascalinux/nowcoder12
9dcae4baeb53cb82933a77f02ef57def76e29be5
1d5b8df5e2c6d82ff2c575d4fe8ab46da6683006
refs/heads/master
2020-04-27T21:40:26.190626
2019-03-09T14:54:41
2019-03-09T14:54:41
174,707,358
0
0
null
null
null
null
UTF-8
C++
false
false
1,074
cpp
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #define pii pair<int,int> #define fi first #define se second #define ll long long using namespace std; int n,m,mx,tp; int vis[100009]; ll v[100009],sm[100009]; ll tmp[100009]; pii st[100009]; void rebuild() { memset(tmp,0,sizeof(tmp)); memset(vis,0,sizeof(vis)); for(int i=1;i<=tp;i++) { int p=st[i].fi; tmp[p]+=st[i].se; vis[p]=1; } for(int i=1;i<=n;i++) if(vis[i]) for(int j=i;j<=n;j+=i) v[j]+=tmp[i]; for(int i=1;i<=n;i++) sm[i]=sm[i-1]+v[i]; // for(int i=1;i<=n;i++) // printf("i:%d sm;%lld\n",i,tmp[i]); tp=0; } int main() { #ifndef ONLINE_JUDGE freopen("f.in","r",stdin); freopen("f.out","w",stdout); #endif scanf("%d%d",&n,&m); mx=sqrt(n*20); for(int i=1,a,b,c;i<=m;i++) { scanf("%d%d%d",&a,&b,&c); if(a==1) { st[++tp]=pii(b,c); if(tp>mx) rebuild(); } else { ll ans=sm[c]-sm[b-1]; for(int j=1;j<=tp;j++) { int d=st[j].fi; ans+=(ll)(c/d-(b-1)/d)*st[j].se; } printf("%lld\n",ans); } } return 0; }
[ "cppascalinux@gmail.com" ]
cppascalinux@gmail.com
4bf1fc949bcd7e6cc37480fb8b71719cc6731e23
a94935bd3855fa6da97265b491dd18930ccbb134
/RealmLib/Packets/Server/Aoe.cpp
f489a7e1a11ad0af91ef198cb5e7f0a4d75dd4cb
[ "MIT" ]
permissive
hcoffey1/RealmNet
7531deed1fd80baaeb1fa8b42aa73271d86241e8
76ead08b4a0163a05b65389e512942a620331256
refs/heads/master
2022-04-25T13:37:49.505083
2019-03-05T21:29:56
2019-03-05T21:29:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
959
cpp
#include "stdafx.h" #include <GameData/Constants.h> #include <GameData/TypeManager.h> #include "Packets/PacketWriter.h" #include "Packets/PacketReader.h" #include <Packets/Aoe.h> Aoe::Aoe(const Location& position, float radius, ushort damage, byte effect, float duration, ushort originType, int color) : position(position), radius(radius), damage(damage), effect(effect), duration(duration), originType(originType), color(color) { } Aoe::Aoe(byte* data) { PacketReader r(data); r.read(position); r.read(radius); r.read(damage); r.read(effect); r.read(duration); r.read(originType); r.read(color); } void Aoe::emplace(byte* buffer) const { PacketWriter w(buffer, size(), TypeManager::typeToId[PacketType::Aoe]); w.write(position); w.write(radius); w.write(damage); w.write(effect); w.write(duration); w.write(originType); w.write(color); } int Aoe::size() const { return 30; } String Aoe::toString() const { return String("AOE"); }
[ "willurotmg@gmail.com" ]
willurotmg@gmail.com
439a6942ac15e5c0e4a91ee8f87edc8640a3a226
97e9961cfdbfb10bee028f2827a8321cc06da8a9
/cuttingstockproblem.cpp
faa6fd271bd8cbcc35d1fa686f25fdaa8488393f
[]
no_license
WoodieGeek/Cutting_stock_problem
e2cc717d8a9c2355be8cc39b7dbd8ca9c83d87ac
99d0e7d655a1d23ecb96d42d603ee75015e46300
refs/heads/master
2020-04-12T12:26:09.528605
2019-10-08T17:11:06
2019-10-08T17:11:06
162,491,836
0
1
null
null
null
null
UTF-8
C++
false
false
723
cpp
#include "cuttingstockproblem.h" CuttingStockProblem::CuttingStockProblem(size_t L, size_t N, std::vector<size_t>& Ls, std::vector<size_t>& C) : L_(L) , N_(N) , Ls_(Ls) , C_(C) {} CuttingStockProblem::CuttingStockProblem(size_t L, size_t N, std::vector<size_t>&& Ls, std::vector<size_t>&& C) : L_(L) , N_(N) , Ls_(Ls) , C_(C) {} Answer CuttingStockProblem::GetAnswer(std::unique_ptr<Solver> solver) { return solver->Solve(this); } size_t CuttingStockProblem::Get_L() { return L_; } size_t CuttingStockProblem::Get_N() { return N_; } std::vector<size_t>& CuttingStockProblem::Get_Ls() { return Ls_; } std::vector<size_t>& CuttingStockProblem::Get_C() { return C_; }
[ "shakirov-ernest@mail.ru" ]
shakirov-ernest@mail.ru
e5217976cdcea7a59ffbae19af12dc128218196b
6dc1cafa766e7c3b3932c3fd5d434f2499f4a889
/64_Minimum_Path_Sum.cpp
5491b77a8fde484e1c83181b75f13d9e4113a834
[]
no_license
mekks/leetcode_solution
6f116312976b3403a8a8df718b9e81d22409a582
aa76e7c16d34a9eacfa030c4fb3f922a75f31d24
refs/heads/master
2021-02-07T11:20:13.108214
2020-08-28T05:15:11
2020-08-28T05:15:11
244,019,207
1
0
null
null
null
null
UTF-8
C++
false
false
954
cpp
/* Question: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Example: Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum. */ //Sol:1 20ms class Solution { public: int minPathSum(vector<vector<int>>& grid) { int m=grid.size(); int n=grid[0].size(); for(int i=m-2;i>=0;i--) { grid[i][n-1]=grid[i+1][n-1]+grid[i][n-1]; } for(int i=n-2;i>=0;i--) { grid[m-1][i]=grid[m-1][i+1]+grid[m-1][i]; } for(int i=m-2 ; i>=0;i--) { for(int j=n-2;j>=0;j--) { grid[i][j]=grid[i][j]+min(grid[i+1][j],grid[i][j+1]); } } return grid[0][0]; } };
[ "noreply@github.com" ]
mekks.noreply@github.com
b71d1bb61c5f32b1b67d210d7b2b043ae7d9827a
b784b4a1ee1f9ada153f6430cc94ddd1ec45e4f6
/d912pxy/v3/util/memory_block.h
422141137eeb8abeb82bf2807cc87ea771b57fd6
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
hauntek/d912pxy
87884cc89f522de338c8d7046bf0edd10c9e5a90
bf5c3377e1121c5f15679eac86a3e67a77e5fbcb
refs/heads/master
2022-12-03T01:42:00.122205
2020-08-15T20:35:49
2020-08-15T20:35:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,466
h
/* MIT License Copyright(c) 2020 megai2 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 "stdafx.h" namespace d912pxy { class MemoryBlock : public BaseObject { void* ptr = nullptr; public: MemoryBlock() = default; MemoryBlock(void* in_ptr) : ptr(in_ptr) {}; MemoryBlock(intptr_t size); ~MemoryBlock(); void alloc(intptr_t size); void realloc(intptr_t newSize); void free(); template<class T> T* c_arr() { return (T*)ptr; } }; }
[ "megai2@ya.ru" ]
megai2@ya.ru
ff0a8e8579da65ecc1f0d9b356ec21ef46bfcb49
0757a28db8864314bf597aa13ff6af548ac310a5
/lmyunit/compile_bench/MIniFile__CreateObject/test.cpp
903a4d471cc1f8c4eabb1ba24bdcc91a5a68d109
[]
no_license
greshem/lmyunit
25a3f6fc7b7d04d8b3e5bdab5406003d68fd4ca6
a5036c67b36e4e58472bd91fbfdd7d1c29018687
refs/heads/master
2021-07-11T01:01:45.599991
2017-10-08T12:36:30
2017-10-08T12:36:30
106,174,697
0
0
null
null
null
null
UTF-8
C++
false
false
124
cpp
#include <lmyunit/unitlib.h> int main(int argc, char *argv[]) { MIniFile::CreateObject(); //target call return 0; }
[ "qianzhongjie@gmail.com" ]
qianzhongjie@gmail.com
b341dfb7aca1170e994e09219976aadb559f4021
844041997269a47471b430439f1f60ee7de954c2
/gbsearch.h
dc230066af3190773ad7d5d73d361e9248885d84
[]
no_license
ajw170/FSU-Spy
a4d8e281014e7967c3689cbec5f9d6a921fd0b03
138d8a93ed1195f1ae00627fae9a9541ef47575f
refs/heads/master
2021-01-25T05:43:29.335739
2017-02-27T22:22:49
2017-02-27T22:22:49
80,661,672
0
0
null
null
null
null
UTF-8
C++
false
false
9,132
h
/* gbsearch.h 01/01/12 Chris Lacher Generic binary search algorithms for random access iterators 02/01/14: removed const from P& 10/10/14: added g_range Iterative implementations: runtime = Theta(log n) runspace = +Theta(1) These algorithms take parameters of type I, T, and optionally a third parameter of type P. about I ======= I is a random access iterator type; this means that the bracket operator T& operator [] (unsigned int); is defined and the usual "pointer" arithmetic operations are defined: I& operator += (long n); I& operator -= (long n); I operator + (long n) const; long operator - (const I& I2) const; Examples include: ordinary array iterators (pointers); TVector<T>::Iterator; TDeQueue<T>::Iterator; about T ======= T is the value type of the iterator I about P ======= P is a predicate class used for order; an object cmp of class P has the function evaluation operator overloaded with the prototype bool operator () (const T&, const T&); Note that P must be used to order the elements so that P can work as a search condition: "a < b" iff "true = P(a,b)". g_lower_bound() and g_upper_bound() implement binary search for random access iterators. It is assumed that the elements of iteration are in nondecreasing order (using operator < or an optional predicate object). g_lower_bound returns an iterator to the first location containing the search value if found, and the location where it would be otherwise. g_upper_bound returns an iterator to the first location whose element is greater than the search value if such exists or the end iterator otherwise. I.e. (assuming L = lower bound and U = upper bound): if t is in the collection: t == *L, t < *U, and L and U point to the first elements in the range with these properties; thus, L and U mark the range of t in the collection; if t is not in the collection: L == U, and these iterators point to the location where t could be inserted and maintain nondecreasing order. bool binary_search() uses the same algorithm, returning true iff found. All these versions of binary search run in logorithmic time and require only a constant amount of additional run space. g_range returns a pair of p iterators such that p.first_ is the loewr bound and p.second_ is the upper bound. Thus [p.first_, p.second_) is the range of values equal to the search value. Copyright 2014, R.C. Lacher */ #ifndef _GBSEARCH_H #define _GBSEARCH_H #include <compare.h> #include <pair.h> namespace fsu { template < class I, typename T, class P > typename fsu::Pair<I,I> g_range (I low, I hih, const T& val, P& cmp) // pre: I is a random access iterator (operator [] and "pointer" arithmetic) // I has ValueType T // low + n = hih for some n >= 0 // low[0] ... low[n-1] are in non-decreasing order using cmp // post: no state is changed // return: Pair p such that // p.first_ = lower bound location in range // p.second_ = upper bound location in range { I low1(low), low2(low), hih1(hih), hih2(hih), mid1, mid2; while (low1 != hih1 && low2 != hih2) { mid1 = low1 + ((hih1 - low1) >> 1); if (cmp(*mid1 , val)) low1 = mid1 + 1; else hih1 = mid1; mid2 = low2 + ((hih2 - low2) >> 1); if (cmp(val, *mid2)) hih2 = mid2; else low2 = mid2 + 1; } while (low1 != hih1) { mid1 = low1 + ((hih1 - low1) >> 1); if (cmp(*mid1 , val)) low1 = mid1 + 1; else hih1 = mid1; } while (low2 != hih2) { mid2 = low2 + ((hih2 - low2) >> 1); if (cmp(val, *mid2)) hih2 = mid2; else low2 = mid2 + 1; } return fsu::Pair<I,I>(low1,hih2); } template < class I, typename T > typename fsu::Pair<I,I> g_range (I low, I hih, const T& val) // pre: I is a random access iterator (operator [] and "pointer" arithmetic) // I has ValueType T // low + n = hih for some n >= 0 // low[0] ... low[n-1] are in non-decreasing order using cmp // post: no state is changed // return: Pair p such that // p.first_ = lower bound location in range // p.second_ = upper bound location in range { I low1(low), low2(low), hih1(hih), hih2(hih), mid1, mid2; while (low1 != hih1 && low2 != hih2) { mid1 = low1 + ((hih1 - low1) >> 1); if (*mid1 < val) low1 = mid1 + 1; else hih1 = mid1; mid2 = low2 + ((hih2 - low2) >> 1); if (val < *mid2) hih2 = mid2; else low2 = mid2 + 1; } while (low1 != hih1) { mid1 = low1 + ((hih1 - low1) >> 1); if (*mid1 < val) low1 = mid1 + 1; else hih1 = mid1; } while (low2 != hih2) { mid2 = low2 + ((hih2 - low2) >> 1); if (val < *mid2) hih2 = mid2; else low2 = mid2 + 1; } return fsu::Pair<I,I>(low1,hih2); } template <class I, typename T, class P> I g_lower_bound (I low, I hih, const T& val, P& cmp) // pre: I is a random access iterator (operator [] and "pointer" arithmetic) // I has ValueType T // low + n = hih for some n >= 0 // low[0] ... low[n-1] are in non-decreasing order using cmp // post: no state is changed // return: itr = lower bound location in range, that is: // itr = low + i, where low[i-1] < val <= low[i] or // itr = hih if no such i exists { I mid; while (low != hih) { mid = low + ((hih - low) >> 1); // low <= mid < hih **pointer arithemetic, not valid in list iterators if (cmp(*mid , val)) // *mid < val low = ++mid; // *mid <= val else // val <= *mid hih = mid; // val <= *hih } return low; } /* here is an equivalent integer version of the code { unsigned long max = hih - low; // 1 + largest valid index unsigned long lo(0), hi(max), mi; while (lo < hi) { mi = (lo + hi) / 2; if (LessThan(low[mi] , val)) lo = mi + 1; else hi = mi; } return low + lo; } */ template <class I, typename T, class P> I g_upper_bound (I low, I hih, const T& val, P& cmp) // pre: I is a random access iterator (operator [] and "pointer" arithmetic) // I has ValueType T // low + n = hih for some n >= 0 // low[0] ... low[n-1] are in non-decreasing order using cmp // post: no state is changed // return: itr = low + i, where low[i-1] <= val < low[i]; or // itr = hih if no such i exists { I mid; while (low != hih) { mid = low + ((hih - low) >> 1); // low <= mid < hih if (cmp(val, *mid)) // val < low[mid] hih = mid; // val < low[hih] else // low[mid] <= val low = ++mid; // low[low - 1] <= val } return hih; } template <class I, typename T, class P> bool g_binary_search (I low, I hih, const T& val, P& cmp) // pre: I is a random access iterator (operator [] and "pointer" arithmetic) // I has ValueType T // low + n = hih for some n >= 0 // low[0] ... low[n-1] are in non-decreasing order using cmp // post: no state is changed // return: true if found, false if not found { I lb = fsu::g_lower_bound(low, hih, val, cmp); if (lb != hih) { if (val == *lb) { return 1; } } return 0; } template <class I, typename T> I g_lower_bound (I low, I hih, const T& val) { fsu::LessThan<T> cmp; return fsu::g_lower_bound(low, hih, val, cmp); } template <class I, typename T> I g_upper_bound (I low, I hih, const T& val) { fsu::LessThan<T> cmp; return fsu::g_upper_bound(low, hih, val, cmp); } template <class I, typename T> bool g_binary_search (I low, I hih, const T& val) { fsu::LessThan<T> cmp; return fsu::g_binary_search(low, hih, val, cmp); } /* Proof (g_lower_bound) ----- Before entering loop, define beg = low, top = hih - 1 loop invariants: beg[0..low-1] are < val beg[hih..top] are >= val 0 <= low <= mid <= hih <= top Proof of Termination: (hih - low) collides with 0 Return Value: after loop terminates, the following are true: low == hih 0 <= low <= top beg[low] == beg + low is where val SHOULD be, i.e.: val <= beg[0] if low == 0 beg[low - 1] < val <= beg[low] if 0 < low < top beg[top - 1] < val if low == top */ } // namespace fsu #endif
[ "AJWOOD@Andrew-Woods-iMac.local" ]
AJWOOD@Andrew-Woods-iMac.local
7085583cc8096630f234e7c4a415b14a3cb3f4a4
33fd5786ddde55a705d74ce2ce909017e2535065
/build/iOS/Release/include/Fuse.Animations.CycleWaveform.h
63bd0dc267271d29b4644421c6042766a6c22213
[]
no_license
frpaulas/iphodfuse
04cee30add8b50ea134eb5a83e355dce886a5d5a
e8886638c4466b3b0c6299da24156d4ee81c9112
refs/heads/master
2021-01-23T00:48:31.195577
2017-06-01T12:33:13
2017-06-01T12:33:13
92,842,106
3
3
null
2017-05-30T17:43:28
2017-05-30T14:33:26
C++
UTF-8
C++
false
false
380
h
// This file was generated based on '../../../../Library/Application Support/Fusetools/Packages/Fuse.Animations/0.47.7/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Int.h> namespace g{ namespace Fuse{ namespace Animations{ // public enum CycleWaveform :759 uEnumType* CycleWaveform_typeof(); }}} // ::g::Fuse::Animations
[ "frpaulas@gmail.com" ]
frpaulas@gmail.com
20afa203f9c806c943bc207b035a5c9a73589906
c924ffb35ad2184898d34bf2564c9ac4e9c67aa2
/src/main.cpp
4fcd7518b6ff944f1963bfd253a2abbca78016c9
[]
no_license
Rexagon/programmer
e1db4a1e2dcdf45e3228db05bdde5aeda1959e34
b92b6eef7a2a2e899bfbdb38c54af86dfc190f9e
refs/heads/master
2020-08-09T14:12:07.390058
2019-10-12T12:58:26
2019-10-12T12:58:26
214,104,304
0
0
null
null
null
null
UTF-8
C++
false
false
399
cpp
#include <QApplication> #include "Windows/MainWindow.h" int main(int argc, char **argv) { QApplication programmer(argc, argv); QApplication::setOrganizationName("RC MODULE"); QApplication::setApplicationName("Programmer"); QApplication::setApplicationVersion(APP_VERSION); app::MainWindow mainWindow; mainWindow.show(); return QApplication::exec(); }
[ "reide740@gmail.com" ]
reide740@gmail.com
ee2fd2596b402e4420d4c96e405c0571f6e80f08
d24cef73100a0c5d5c275fd0f92493f86d113c62
/SRC/engine/rank3tensor.C
1334bb9a94dc9e8fe63f44b31ecde5ed74a2967e
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
rlinder1/oof3d
813e2a8acfc89e67c3cf8fdb6af6b2b983b8b8ee
1fb6764d9d61126bd8ad4025a2ce7487225d736e
refs/heads/master
2021-01-23T00:40:34.642449
2016-09-15T20:51:19
2016-09-15T20:51:19
92,832,740
1
0
null
null
null
null
UTF-8
C++
false
false
6,208
c
// -*- C++ -*- // $RCSfile: rank3tensor.C,v $ // $Revision: 1.17.10.2 $ // $Author: fyc $ // $Date: 2014/07/28 22:15:26 $ /* This software was produced by NIST, an agency of the U.S. government, * and by statute is not subject to copyright in the United States. * Recipients of this software assume all responsibilities associated * with its operation, modification and maintenance. However, to * facilitate maintenance we ask that before distributing modified * versions of this software, you first contact the authors at * oof_manager@nist.gov. */ #include <oofconfig.h> #include "common/corientation.h" #include "common/doublevec.h" #include "common/ooferror.h" #include "engine/fieldindex.h" #include "engine/ooferror.h" #include "engine/property/elasticity/cijkl.h" #include "engine/rank3tensor.h" #include "engine/symeig3.h" #include <iomanip> #include <iostream> Rank3Tensor::Rank3Tensor(const Rank3Tensor& sm) : m0(3), m1(3), m2(3), nrows(3) { (*this)=sm; } Rank3Tensor::~Rank3Tensor() {} bool Rank3Tensor::operator==(const Rank3Tensor &that) { return (m0==that.m0 && m1==that.m1 && m2==that.m2); } Rank3Tensor& Rank3Tensor::operator=(const Rank3Tensor& sm) { if(&sm != this) { m0 = sm.m0; m1 = sm.m1; m2 = sm.m2; } return *this; } // access double Rank3Tensor::operator()(unsigned int i, unsigned int j, unsigned int k) const { assert(i<nrows && j<nrows && k<nrows && i>=0 && j>=0 && k>=0); if(i==0) return m0(j,k); if(i==1) return m1(j,k); return m2(j,k); } double &Rank3Tensor::operator()(unsigned int i, unsigned int j, unsigned int k) { assert(i<nrows && j<nrows && k<nrows && i>=0 && j>=0 && k>=0); if(i==0) return m0(j,k); if(i==1) return m1(j,k); return m2(j,k); } double &Rank3Tensor::operator()(int i, const SymTensorIndex &jk) { return operator()(i, jk.row(), jk.col()); } double Rank3Tensor::operator()(int i, const SymTensorIndex &jk) const { return operator()(i, jk.row(), jk.col()); } Rank3Tensor &Rank3Tensor::operator+=(const Rank3Tensor &a) { m0 +=a.m0; m1 +=a.m1; m2 +=a.m2; return *this; } Rank3Tensor &Rank3Tensor::operator-=(const Rank3Tensor &a) { m0 -= a.m0; m1 -= a.m1; m2 -= a.m2; return *this; } SymmMatrix operator*(const Rank3Tensor &a, const DoubleVec &x) { // TODO OPT: Use Rank3Tensor::operator* here, or vice versa. unsigned int nrows = a.nrows; if(x.size() != nrows) throw ErrProgrammingError("Vector has wrong dimension", __FILE__, __LINE__); if(x.size() != nrows) abort(); SymmMatrix result(nrows); for(unsigned int i=0; i<nrows; i++) { for(unsigned int j=i; j<nrows; j++) for(unsigned int k=0; k<nrows;k++) result(i,j) += a(k,i,j)*x[k]; } return result; } // Compute A^ T (*this) A Rank3Tensor Rank3Tensor::transform(const COrientation *orient) const { SmallMatrix A = orient->rotation(); assert(A.rows() == nrows); // from Nye page 111, equation 5 // TODO OPT: Use partial sums to speed this up? Rank3Tensor result; for(unsigned int i=0; i<nrows; i++) { for(unsigned int j=0; j<nrows; j++) { // Only need to index k starting from j, because each index i // corresponds to a SymmMatrix, which automatically increments // both off-diagonals. for (unsigned int k=j; k<nrows; k++) { double &r = result(i, j, k); for(unsigned int l=0; l<nrows; l++) for(unsigned int m=0; m<nrows; m++) for(unsigned int n=0; n<nrows; n++) r += A(i, l) * A(j, m) * A(k,n) * (*this)(l, m, n); } } } return result; } Rank3Tensor operator*(double x, const Rank3Tensor &A) { Rank3Tensor result(A); result.m0 *= x; result.m1 *= x; result.m2 *= x; return result; } Rank3Tensor operator*(const Rank3Tensor &A, double x) { Rank3Tensor result(A); result.m0 *= x; result.m1 *= x; result.m2 *= x; return result; } Rank3Tensor &Rank3Tensor::operator*=(double x) { m0 *= x; m1 *= x; m2 *= x; return *this; } Rank3Tensor &Rank3Tensor::operator/=(double x) { return operator*=(1./x); } Rank3Tensor operator/(const Rank3Tensor &A, double x) { Rank3Tensor result(A); result *= 1./x; return result; } std::string Rank3Tensor::classname_("Rank3Tensor"); std::string Rank3Tensor::modulename_("ooflib.SWIG.engine.rank3tensor"); SymmMatrix &Rank3Tensor::operator()(unsigned int i) { assert(i<nrows && i>=0); if(i==0) return m0; if(i==1) return m1; return m2; } SymmMatrix Rank3Tensor::operator()(unsigned int i) const { assert(i<nrows && i>=0); if(i==0) return m0; if(i==1) return m1; return m2; } SymmMatrix Rank3Tensor::operator*(const DoubleVec& E) { SymmMatrix result(nrows); // There's no sum over i and j here. We really just do a vector dot // product for each i, j pair. Since the result is a SymmMatrix, // there's no need to compute the (j,i) component if we've already // computed the (i,j) component. for(unsigned int i=0;i<nrows; i++) for(unsigned int j=i; j<nrows;j++) for(unsigned int k=0; k<nrows;k++) result(i,j) += (*this)(k,i,j)*E[k]; return result; } Rank3Tensor operator*(const Cijkl &a, const DoubleVec &x) { Rank3Tensor result; unsigned int nrows = x.size(); for(unsigned int i=0; i<nrows; i++) for(unsigned int j=0; j<nrows; j++) for(unsigned int k=0; k<=j; k++) { double &r = result(i,j,k); for(unsigned int l=0; l<nrows; l++) r += a(l,i,j,k)*x[l]; } return result; } Rank3Tensor operator*(const Cijkl& c, const Rank3Tensor& d) { Rank3Tensor e; int nrows = d.nrows; for(int i=0; i<nrows;i++) for(int j=0; j<nrows;j++) for(int k=j; k<nrows;k++) { // e_i is stored as a SymmMatrix double &eijk = e(i,j,k); for(int l=0; l<nrows;l++) for(int m=0; m<nrows;m++) eijk += d(i,l,m)*c(l,m,j,k); } return e; } std::ostream &operator<<(std::ostream &os, const Rank3Tensor &dd) { os.setf(std::ios::scientific, std::ios::floatfield); os << "[ "; for(unsigned int i=0; i<dd.nrows; i++){ for(unsigned int j=0;j<dd.nrows;j++) { for(unsigned int k=0; k<dd.nrows; k++) os << dd(i, j, k) << " "; os << std::endl; } os << std::endl; } os << "]"; return os ; }
[ "faical.congo@nist.gov" ]
faical.congo@nist.gov
d68811449599c63eacfb7abd3931583e56225aa7
20a2f451e28d8012220d50651e6b2832c0fa4dcf
/C++/Lab 2.9.1/src/Lab 2.9.1.cpp
1e16e8373625f0c70c8a300681d1cf791b76d405
[]
no_license
taitken0010/Labs
cbfeec122546124650144de68d55f860c5ca88ce
6ef4114f75d87d2e5e32197abe5779a3e71bb156
refs/heads/master
2020-04-07T13:56:05.777779
2018-11-20T18:58:18
2018-11-20T18:58:18
158,427,843
0
0
null
null
null
null
UTF-8
C++
false
false
606
cpp
//============================================================================ // Name : 1.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; int main() { int vector1[7] = {4, 7, 2, 8, 1, 3, 0}; int vector2[7]; int b=1; for (int a = 0; a < 6; a++){ vector2[0] = vector1[6]; vector2[b] = vector1[a]; b++; } for(int i = 0; i < 7; i++) cout << vector2[i] << ' '; cout << endl; return 0; }
[ "taitken0010@vbtc.net" ]
taitken0010@vbtc.net
b0c675497e35a188eb28fd23d15907e50cc35cb1
ecbc8f17671bbcd97a1fa03eb4e18a8bb490a324
/src/Applications/Windows/Calibra/ContainerView.cpp
d9bf205f62e644548eb21e3bd554c21de531d537
[ "MIT" ]
permissive
xtsxisaxns/Calibra
b1fbbde1d2fb74569640b0ab444d123205f94a7c
f482cf414c24ddbe103b49c1d3a22a8605bb9b03
refs/heads/master
2021-09-27T08:39:39.920103
2018-07-08T11:07:38
2018-07-08T11:07:38
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,591
cpp
// ============================================================================= // ContainerView.cpp // // MIT License // // Copyright (c) 2007-2018 Dairoku Sekiguchi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // ============================================================================= #include "stdafx.h" #include "Calibra.h" #include "ContainerView.h" #include "CalibraDoc.h" #include "afxpriv.h" // CContainerView IMPLEMENT_DYNCREATE(CContainerView, CView) CContainerView::CContainerView() { mChildWnd = NULL; } CContainerView::~CContainerView() { } BEGIN_MESSAGE_MAP(CContainerView, CView) ON_WM_SIZE() ON_WM_CREATE() END_MESSAGE_MAP() // CContainerView 描画 void CContainerView::OnDraw(CDC* pDC) { CDocument* pDoc = GetDocument(); // TODO: 描画コードをここに追加してください。 } // CContainerView 診断 #ifdef _DEBUG void CContainerView::AssertValid() const { CView::AssertValid(); } #ifndef _WIN32_WCE void CContainerView::Dump(CDumpContext& dc) const { CView::Dump(dc); } #endif #endif //_DEBUG // CContainerView メッセージ ハンドラ BOOL CContainerView::CreateChildView(CRuntimeClass *pViewClass, CCreateContext* pContext) { #ifdef _DEBUG ASSERT_VALID(this); ASSERT(pViewClass != NULL); ASSERT(pViewClass->IsDerivedFrom(RUNTIME_CLASS(CWnd))); ASSERT(AfxIsValidAddress(pViewClass, sizeof(CRuntimeClass), FALSE)); #endif if (GetChildView() != NULL) DeleteView(); BOOL bSendInitialUpdate = FALSE; CCreateContext contextT; if (pContext == NULL) { // if no context specified, generate one from the currently selected // client if possible // set info about last pane ASSERT(contextT.m_pCurrentFrame == NULL); contextT.m_pLastView = this; contextT.m_pCurrentDoc = GetDocument(); if (contextT.m_pCurrentDoc != NULL) contextT.m_pNewDocTemplate = contextT.m_pCurrentDoc->GetDocTemplate(); pContext = &contextT; bSendInitialUpdate = TRUE; } TRY { mChildWnd = (CWnd *)pViewClass->CreateObject(); if (mChildWnd == NULL) AfxThrowMemoryException(); } CATCH_ALL(e) { TRACE(traceAppMsg, 0, "Out of memory creating a container.\n"); // Note: DELETE_EXCEPTION(e) not required return FALSE; } END_CATCH_ALL ASSERT_KINDOF(CWnd, mChildWnd); ASSERT(mChildWnd->m_hWnd == NULL); // not yet created DWORD dwStyle = AFX_WS_DEFAULT_VIEW & ~WS_BORDER; // Create with the right size (wrong position) CRect rect(CPoint(0,0), CPoint(0,0)); if (!mChildWnd->Create(NULL, NULL, dwStyle, rect, this, AFX_IDW_PANE_FIRST, pContext)) { TRACE(traceAppMsg, 0, "Warning: couldn't create client pane for splitter.\n"); // pWnd will be cleaned up by PostNcDestroy return FALSE; } //ASSERT((int)_AfxGetDlgCtrlID(pWnd->m_hWnd) == IdFromRowCol(row, col)); // send initial notification message if (bSendInitialUpdate) { mChildWnd->SendMessage(WM_INITIALUPDATE); CRect rect; GetClientRect(rect); mChildWnd->MoveWindow(rect); } return TRUE; } void CContainerView::DeleteView() { ASSERT_VALID(this); if (mChildWnd == NULL) return; // default implementation assumes view will auto delete in PostNcDestroy mChildWnd->DestroyWindow(); mChildWnd = NULL; } void CContainerView::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); if (mChildWnd == NULL) return; mChildWnd->MoveWindow(0, 0, cx, cy); } int CContainerView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CView::OnCreate(lpCreateStruct) == -1) return -1; ((CCalibraDoc *)GetDocument())->SetContainerView(this); return 0; }
[ "dairoku@gmail.com" ]
dairoku@gmail.com
417141cf712228fa979438b5381e8a61937dea33
9a3fff6e8387e00b59dc0137d1d080215e1de558
/RotaryButton.cpp
ed42d07901069c6e70dc8ffe71f0b272a72777b1
[]
no_license
gertst/SunriseAlarm
aa5d56b7d688c3bf8aa82153176252b5fe266ac0
613ec6b7b36fa4046fe5843d74b04ffb69288476
refs/heads/master
2023-02-07T20:59:55.146955
2021-01-01T14:11:07
2021-01-01T14:11:07
296,873,850
0
0
null
null
null
null
UTF-8
C++
false
false
1,842
cpp
#include "RotaryButton.h" #include "Arduino.h" int lastActivityTime = 0; RotaryButton::RotaryButton(uint8_t encoderAPin_, uint8_t encoderBPin_, uint8_t switchPin_) { encoderAPin = encoderAPin_; encoderBPin = encoderBPin_; switchPin = switchPin_; pinMode (encoderAPin, INPUT_PULLUP); pinMode (encoderBPin, INPUT_PULLUP); pinMode (switchPin, INPUT); valueALast = digitalRead(encoderAPin); encoderPosCount = 0; } int RotaryButton::getPosition() { valueA = digitalRead(encoderAPin); if (valueA != valueALast){ // Means the knob is rotating // if the knob is rotating, we need to determine direction // We do that by reading pin B. if (digitalRead(encoderBPin) == valueA) { // Means pin A Changed first - We're Rotating Clockwise encoderPosCount ++; isClockWise = true; } else {// Otherwise B changed first and we're moving CCW isClockWise = false; encoderPosCount--; } lastActivityTime = millis(); } valueALast = valueA; // return encoderPosCount; return roundf(encoderPosCount / 2); // we divide by 2 because stepper has an inbetween step that is not required } unsigned long RotaryButton::getSecondsIdle() { return long((millis() - lastActivityTime) / 1000); } boolean RotaryButton::getIsButtonPressed() { int switchValue = digitalRead(switchPin); //disable for 200 millis if (millis() - lastActivityTime > 200) { if (!isButtonPressed && switchValue == LOW) { isButtonPressed = true; lastActivityTime = millis(); return true; } else { if (switchValue == HIGH) { isButtonPressed = false; } return false; } } else { return false; } }
[ "gertst@gmail.com" ]
gertst@gmail.com
645449bb4c92009a93c192958849776e438c9f83
c415b67b1c6585eadc5cb1b110af401b0e3efc29
/cpp/Math/Permutation.cpp
565d4abbeefd098b1d20ebcf8d58bd9b3b6fb8e1
[]
no_license
ASHD27/algorithmBasic
6eab42feeffadeafc126cb8c67a268749897cf16
0a6519466a2ddba2425388a7bd93824454bb80ed
refs/heads/master
2022-12-24T01:15:49.848226
2020-10-01T04:55:21
2020-10-01T04:55:21
300,148,572
0
0
null
2020-10-01T04:55:32
2020-10-01T04:55:31
null
UTF-8
C++
false
false
1,314
cpp
/* 순열을 표현한 cpp 코드 순열은 순서가 있는 n 개의 원소들에 대해서 모든 경우의 수를 전부 구하는 방법임 원소 {1,2,3} 이 주어지면, 이를 나열하기 위한 모든 경우의 수는 1,2,3 1,3,2 2,1,3 2,3,1 3,1,2 3,2,1 총 6가지로 3! 가 된다. */ #include <algorithm> #include <iostream> #include <vector> using namespace std; vector<int> vec = {1, 2, 3}; void permutation(int start, int end) { if (start == end) { for (auto it : vec) { cout << it << " "; } cout << '\n'; } else { for (int i = start; i <= end; i++) { swap(vec[start], vec[i]); permutation(start + 1, end); swap(vec[start], vec[i]); // swap 을 이렇게 두번 수행하는 이유는 다음 차례에서 원상복귀 시킨 상태에서 다시 연산하기 위함이다. // 예를 들면, P = [1,2,3,4,5] 일 때, // [1,2,3,5,4] 로 swap 연산이 이뤄졌으면 그 다음엔 [1,2,4,3,5] 가 되야 하므로 // [1,2,3,4,5] 로 다시 바꿔줘야 다음 차례에서 이에 대한 연산을 제대로 수행할 수 있기 때문 } } } int main() { permutation(0, 2); return 0; }
[ "vel1024@khu.ac.kr" ]
vel1024@khu.ac.kr
836acffcd85a8de9cb1209e77ca029107cc618bf
547ac91590a4d80a216af7b1bdaecdac0df854d4
/libengin/Renderer.cpp
864e7056c7d7ef72ad85320995856c8a992ae63e
[]
no_license
sunnylanwanjun/soft-render-framework
95021b2c1d147247ecdb2790c5907fc5cf4769d9
5a1c0c2a82216513c17dcc09fd641cf9704ba5c6
refs/heads/master
2020-03-26T19:23:32.141046
2018-08-19T02:21:38
2018-08-19T02:21:38
145,262,438
3
1
null
null
null
null
GB18030
C++
false
false
6,578
cpp
#include "Renderer.h" #include "t3dlib1.h" #include "Director.h" #include "WindowView.h" #include "log.h" NS_ENGIN_BEGIN #define DIRECTDRAW_BPP 32 #define NEED_RENDER static GAME_MODE _renderMode; static HWND _wndHwnd; static bool _supportRotation = true; Renderer::Renderer() :_lpdd7(nullptr), _lpddsprimary(nullptr), _lpddsback(nullptr), _lpddsbuffer(nullptr), _lpddbufferclipper(nullptr), _surfaceSize(0,0){ } Renderer::~Renderer(){ if (_lpddsbuffer){ _lpddsbuffer->Release(); _lpddsbuffer = nullptr; } if (_lpddsback){ _lpddsback->Release(); _lpddsback = nullptr; } if (_lpddsprimary){ _lpddsprimary->Release(); _lpddsprimary = nullptr; } if (_lpdd7){ _lpdd7->Release(); _lpdd7 = nullptr; } if (_lpddclipper){ _lpddclipper->Release(); _lpddclipper = nullptr; } if (_lpddbufferclipper){ _lpddbufferclipper->Release(); _lpddbufferclipper = nullptr; } } bool Renderer::initRender(){ #ifdef NEED_RENDER auto director = Director::getInstance(); auto wndView = director->getWindowView(); _renderMode = director->getGameMode(); _wndHwnd = (HWND)wndView->getHwnd(); _surfaceSize.width = (float)GetSystemMetrics(SM_CXSCREEN); _surfaceSize.height = (float)GetSystemMetrics(SM_CYSCREEN); _lpdd7 = DirectDraw7Init(_wndHwnd, _renderMode == MODE_FULLSCREEN, (DWORD)_surfaceSize.width, (DWORD)_surfaceSize.height, DIRECTDRAW_BPP); if (_lpdd7 == nullptr){ return false; } if (_renderMode == MODE_FULLSCREEN){ DirectDrawSurfaceInit_Primary(_lpdd7, &_lpddsprimary, &_lpddsback); if (_lpddsprimary == nullptr || _lpddsback == nullptr){ return false; } /*谁调用blt谁使用clipper,设置后,只有cliper区域的blt起作用,没有设置裁剪程序也不会挂,不过图像在靠近边缘的地方就消失了。*/ RECT clipRect; clipRect.top = 0; clipRect.left = 0; clipRect.bottom = (LONG)_surfaceSize.height; clipRect.right = (LONG)_surfaceSize.width; _lpddclipper = DirectDrawClipperInit(_lpdd7, _lpddsback, 1, &clipRect); if (_lpddclipper == nullptr){ return false; } } //非全屏模式下不能使用页面切换技术 else{ _lpddsprimary = DirectDrawSurfaceInit_Primary(_lpdd7); if (_lpddsprimary == nullptr){ return false; } _lpddsbuffer = DirectDrawSurfaceInit_Common(_lpdd7, (int)_surfaceSize.width, (int)_surfaceSize.height); if (_lpddsbuffer == nullptr){ return false; } _lpddclipper = DirectDrawClipperInit(_lpdd7, _lpddsprimary, _wndHwnd); if (_lpddclipper == nullptr){ return false; } _lpddbufferclipper = DirectDrawClipperInit(_lpdd7, _lpddsbuffer, _wndHwnd); if (_lpddbufferclipper == nullptr){ return false; } } DDPIXELFORMAT ddpf; DDRAW_INIT_STRUCT(ddpf); _lpddsprimary->GetPixelFormat(&ddpf); if (ddpf.dwRGBBitCount != DIRECTDRAW_BPP){ Error("Renderer::initRender sorry,game only run in 32 bit mode"); return false; } DDCAPS hel_caps; DDCAPS hal_caps; DDRAW_INIT_STRUCT(hel_caps); DDRAW_INIT_STRUCT(hal_caps); _lpdd7->GetCaps(&hal_caps, &hel_caps); if (!(hel_caps.dwFXCaps&DDFXCAPS_BLTROTATION) && !(hal_caps.dwFXCaps&DDFXCAPS_BLTROTATION)){ Error("Renderer::initRender do not support rotation"); _supportRotation = false; } #endif return true; } void Renderer::render(Vec3f& pos, Size& contentSize, float scaleX, float scaleY, float rotation, Texture* data){ LPDIRECTDRAWSURFACE7 lpdds = data->getDirectDrawSurface(); render(pos, contentSize, scaleX, scaleY, rotation, lpdds); } void Renderer::render(Vec3f& pos, Size& contentSize, float scaleX, float scaleY, float rotation, LPDIRECTDRAWSURFACE7 lpdds){ #ifdef NEED_RENDER static RECT destRect; static RECT srcRect; srcRect.top = 0; srcRect.bottom = (LONG)(srcRect.top + contentSize.height); srcRect.left = 0; srcRect.right = (LONG)(srcRect.left + contentSize.width); if (_renderMode == MODE_FULLSCREEN){ //全屏模式窗口左上角的位置是固定的 destRect.top = (LONG)(pos.y); destRect.bottom = (LONG)(destRect.top + contentSize.height*scaleY); destRect.left = (LONG)(pos.x); destRect.right = (LONG)(destRect.left + contentSize.width*scaleX); //硬件光栅,不要锁定表面,否则会blt失败 if (FAILED(_lpddsback->Blt(&destRect, lpdds, &srcRect, DDBLT_WAIT | DDBLT_KEYSRC, nullptr))){ Error("Renderer::render Blt back failed"); } } //窗口模式不能使用后备缓冲,所以只能直接blt到主表面 else{ //硬件光栅 //主表面不支持目标色彩键,所以不能使用DDBLT_KEYSRC,否则会blt失败,但是缓冲表面可以使用 //只要有blt的表面,都需要设置裁剪,否则会因为blt超出表面,而发生失败 const Vec2f& wndOrigin = Director::getInstance()->getWindowOrigin(); destRect.top = (LONG)(wndOrigin.y + pos.y); destRect.bottom = (LONG)(destRect.top + contentSize.height*scaleY); destRect.left = (LONG)(wndOrigin.x + pos.x); destRect.right = (LONG)(destRect.left + contentSize.width*scaleX); if (_supportRotation){ static DDBLTFX ddbltfx; DDRAW_INIT_STRUCT(ddbltfx); ddbltfx.dwRotationAngle = (DWORD)rotation; if (FAILED(_lpddsbuffer->Blt(&destRect, lpdds, &srcRect, DDBLT_WAIT | DDBLT_KEYSRC | DDBLT_ROTATIONANGLE, &ddbltfx))){ Error("Renderer::render Blt buffer failed 1 "); } } else{ if (FAILED(_lpddsbuffer->Blt(&destRect, lpdds, &srcRect, DDBLT_WAIT | DDBLT_KEYSRC, nullptr))){ Error("Renderer::render Blt buffer failed 2 "); } } } #endif } void Renderer::clear(){ #ifdef NEED_RENDER DDBLTFX ddbltfx; DDRAW_INIT_STRUCT(ddbltfx); ddbltfx.dwFillColor = 0x00; if (_renderMode == MODE_FULLSCREEN){ _lpddsback->Blt(nullptr, nullptr, nullptr, DDBLT_WAIT | DDBLT_COLORFILL, &ddbltfx); } else{ _lpddsbuffer->Blt(nullptr, nullptr, nullptr, DDBLT_WAIT | DDBLT_COLORFILL, &ddbltfx); } #endif } void Renderer::flip(){ #ifdef NEED_RENDER if (_renderMode == MODE_FULLSCREEN){ _lpddsprimary->Flip(nullptr, DDFLIP_WAIT); // 在窗口模式下,会出现画面残影的情况,而全屏模式下不会,在不使用flip,而使用blt把后备缓冲切换到 // 主表面的情况下,也会出现画面残影的情况,所以主要问题在于blt,可能这个接口的效率不高,有待解决???!!! //_lpddsprimary->Blt(nullptr, _lpddsback, nullptr, DDBLT_WAIT, nullptr); } else{ _lpddsprimary->Blt(nullptr, _lpddsbuffer, nullptr, DDBLT_WAIT, nullptr); } #endif } LPDIRECTDRAW7 Renderer::getDirectDraw(){ return _lpdd7; } LPDIRECTDRAWSURFACE7 Renderer::getDirectDrawSurface(){ return _renderMode == MODE_FULLSCREEN ? _lpddsback : _lpddsbuffer; } NS_ENGIN_END
[ "1053210246@qq.com" ]
1053210246@qq.com
24a5453b82e266e26421d7f556f5e8b1c94b68db
45be8168d193bb672a8a511f3645855fdb86b95c
/main.cpp
64ff4a60cdc77ce636802b0921ae935c87150dd4
[]
no_license
EtienneHouze/Langton
0a1a1d27d025e3f8e5bf55d17339888468046cda
f55f014244c7ce803dc857be5c3e86167a70c979
refs/heads/master
2021-08-29T19:03:38.931141
2017-12-14T18:07:48
2017-12-14T18:07:48
114,281,457
0
0
null
null
null
null
UTF-8
C++
false
false
2,764
cpp
#include <iostream> #include <vector> #include <string> #include <sstream> #include "langtonGrid.hpp" int main(int argc, char** argv){ int windowH = 0; int windowW = 0; int gridH = 0; int gridW = 0; std::cout << " Welcome to the Langton Ant World !" << std::endl; std::cout << "Please enter the dimensions, in pixels, of the window (width height)"<<std::endl; while (windowH == 0 || windowW == 0){ try{ std::cin >> windowW >> windowH; } catch (...){ std::cout << "Invalid dimensions, please try again" << std::endl; } } std::cout << "Now, enter the basic dimensions of the grid (even number only, the default is 20 20)\nThe format is still (width height)" << std::endl; try{ std::cin >> gridW >> gridH; } catch (...){ std::cout << "Invalide dimensions, the default has been applied." << std::endl; } LangtonGrid grid = LangtonGrid(gridW,gridH); std::cout << "Now, if you want some cells to be initally black, please enter their coordinates as follow:\n x y\nKnowing that the ant beigins in the (0,0) cell and is facing up" << std::endl; std::cout << "You can end this process by entering \"no\" " << std::endl; while(true){ int x,y; std::string line; std::getline(std::cin,line); if (line == std::string("no")) break; else{ if (line.size() > 1){ auto stream = std::stringstream(line); stream >> x >> y; grid.setBlack(std::pair<int,int>(x,y)); std::cerr << "black" << std::endl; } } std::cerr<<x <<" "<<y <<std::endl; } std::cout << "Now for the last step : enter how many rounds you want to run, and how long they should last\n The format is \n {number of turns} {time in ms par turn}" << std::endl; int numberOfTurns = 0; int timePerTurn = 0; grid.init(windowW,windowH); while (numberOfTurns == 0 || timePerTurn == 0){ try{ std::cin >> numberOfTurns >> timePerTurn; } catch (...){ std::cout<<"Invalid Values, try again !" << std::endl; } } bool finished = false; while (!finished){ grid.run_loop(numberOfTurns,timePerTurn); std::cout << "if you want to continue, please enter the number of additional steps. \n 0 will stop the simulation." << std::endl; int additionalSteps; try{ std::cin >> additionalSteps; if (additionalSteps == 0) finished = true; numberOfTurns += additionalSteps; } catch (...){ finished = true; } } return 0; }
[ "noreply@github.com" ]
EtienneHouze.noreply@github.com
335d0e8fb3a749c964fd70f802a43ccdc20ce2ef
0057005bb64e68fe58c5ca0e40e7112bd23badef
/signal_transfer/src/data_transfer.h
b1e6647d75bf3a7c17eb48ff3390a145e04896de
[]
no_license
jiohLee/selfcar_2020_ws
e4b3c68d16c978499dc2ec55800384ddb94d0663
0cb2044edb20d65b72f7560a2c6d22d51b95640d
refs/heads/master
2023-03-06T16:02:19.431646
2021-02-23T04:45:27
2021-02-23T04:45:27
341,431,101
0
0
null
null
null
null
UTF-8
C++
false
false
3,463
h
#include <ros/ros.h> #include <std_msgs/String.h> #include <darknet_ros_msgs/BoundingBoxes.h> #include <darknet_ros_msgs/ObjectCount.h> using namespace std; using namespace ros; class data { private: ros::NodeHandle nh; ros::Publisher ros_pub; ros::Subscriber ros_sub; ros::Subscriber ros_sub2; darknet_ros_msgs::BoundingBoxes box; string R; string G; string LG; string LR; std_msgs::String trans; public: data(); data( string sub ); data( string sub, string pub); data( string sub, int n ); void imageCallback_bounding( const darknet_ros_msgs::BoundingBoxes::ConstPtr& msg ); void imageCallback_bounding_pub( const darknet_ros_msgs::BoundingBoxes::ConstPtr& msg ); void stringCallback( const std_msgs::String::ConstPtr& msg ); }; data::data(){} data::data( string sub ) { ros_sub = nh.subscribe<darknet_ros_msgs::BoundingBoxes>( sub, 100, &data::imageCallback_bounding, this ); R = "RED"; G = "GREEN"; LG = "LEFT_GREEN"; LR = "LEFT_RED"; } data::data( string sub, string pub ) { R = "RED"; G = "GREEN"; LG = "LEFT_GREEN"; LR = "LEFT_RED"; ros_sub = nh.subscribe<darknet_ros_msgs::BoundingBoxes>( sub, 100, &data::imageCallback_bounding_pub, this ); ros_pub = nh.advertise<std_msgs::String>(pub, 100); } data::data( string sub, int n ) { ros_sub = nh.subscribe<std_msgs::String>( sub, 100, &data::stringCallback, this ); } //ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ void data::imageCallback_bounding( const darknet_ros_msgs::BoundingBoxes::ConstPtr& msg ) { int num = msg->bounding_boxes.size(); for( int i = 0; i < num; i++ ) { if( msg->bounding_boxes[i].id == 0 ) ROS_INFO("%s", G.c_str() ); else if( msg->bounding_boxes[i].id == 1) ROS_INFO("%s", R.c_str() ); else if( msg->bounding_boxes[i].id == 2) ROS_INFO("%s", LG.c_str() ); else if( msg->bounding_boxes[i].id == 3) ROS_INFO("%s", LR.c_str() ); else if( msg->bounding_boxes[i].id == 4) ROS_INFO("%s", R.c_str() ); } } void data::imageCallback_bounding_pub( const darknet_ros_msgs::BoundingBoxes::ConstPtr& msg ) { int num = msg->bounding_boxes.size(); for( int i = 0; i < num; i++ ) { if( msg->bounding_boxes[i].id == 0 ) { ROS_INFO("%s", G.c_str() ); trans.data = G; } else if( msg->bounding_boxes[i].id == 1 ) { ROS_INFO("%s", R.c_str() ); trans.data = R; } else if( msg->bounding_boxes[i].id == 2 ) { ROS_INFO("%s", LG.c_str() ); trans.data = LG; } else if( msg->bounding_boxes[i].id == 3 ) { ROS_INFO("%s", LR.c_str() ); trans.data = LR; } else if( msg->bounding_boxes[i].id == 4 ) { ROS_INFO("%s", R.c_str() ); trans.data = R; } ros_pub.publish(trans); } } void data::stringCallback( const std_msgs::String::ConstPtr& msg ) { if( msg->data == "RED") ROS_INFO("RED"); else if( msg->data == "GREEN") ROS_INFO("GREEN"); else if( msg->data == "LEFT_GREEN") ROS_INFO("LEFT_GREEN"); else if( msg->data == "LEFT_RED") ROS_INFO("LEFT_RED"); }
[ "jiosiro@gmail.com" ]
jiosiro@gmail.com
4efa200230e1a93d562eb9b3356c196a2251e8c4
f5e6eff638593cd3e936fc2f66ac0ce386bb163a
/src/CODEFORCES/467B.cpp
eba5fd985874acc8b673f08a86a827307bf017ca
[]
no_license
DunittMonagas/competitive-programming
b08030882976b30b25f538eda48b8038b1f7e65c
885dacb2e992db90982c599f0d650492bf855117
refs/heads/master
2020-12-21T13:06:20.049690
2020-08-28T12:20:51
2020-08-28T12:20:51
236,438,846
0
0
null
null
null
null
UTF-8
C++
false
false
824
cpp
/* ***************************************************************** * PROBLEMA * ***************************************************************** * Codeforce 467B - Fedor and New Game * ***************************************************************** */ #include <iostream> #include <bitset> using namespace std; int J[1010]; bool Diferencia(int a, int b, int t){ int cont= 0; bitset<25> BitA (a); bitset<25> Bitb (b); for(int i= 24; i>=0; --i) if(BitA[i] != Bitb[i]) ++cont; return cont > t ? true:false; } int main(){ int n, m, k, cont= 0; cin >> n >> m >> k; for(int i= 0; i<= m; ++i) cin >> J[i+1]; for(int i= 1; i<=m; ++i) if(!Diferencia(J[i], J[m+1], k)) ++cont; cout << cont << "\n"; return 0; }
[ "dunitt.monagas@example.com" ]
dunitt.monagas@example.com
e600be3d446b9ee13487e6ab813a8517b31f3af6
b125fd6a7777fbdd1a957e4a79a6ca33ea25b128
/SocketConnector.cpp
b7971508120f00a640b0efdfa78c8cd54ce9eb22
[]
no_license
pawkrol/customSocketServer
9279b8de8f3e66567f02161fe65a3c5491093b61
3343ec8493dc785e7accdf848d983bcf861f84c2
refs/heads/master
2021-01-10T05:26:21.415540
2015-12-07T22:09:24
2015-12-07T22:09:24
47,512,832
0
0
null
null
null
null
UTF-8
C++
false
false
3,105
cpp
// // Created by pawkrol on 12/1/15. // #include <cstring> #include <arpa/inet.h> #include <unistd.h> #include "SocketConnector.h" SocketConnector::SocketConnector(std::string port) { this->port = port; setStructs(); checkStatus(); setSocket(); makeBind(); freeHostsList(); } SocketConnector::~SocketConnector() { close(sockfd); } void SocketConnector::checkStatus() { if (status != 0){ exit(-1); } } void SocketConnector::setStructs() { addrinfo host; addrinfo *hostList; memset(&host, 0, sizeof(host)); host.ai_family = AF_UNSPEC; host.ai_socktype = SOCK_STREAM; host.ai_flags = AI_PASSIVE; status = getaddrinfo(NULL, port.c_str(), &host, &hostList); this->hostList = hostList; } void SocketConnector::setSocket() { int yes = 1; sockfd = socket(hostList->ai_family, hostList->ai_socktype, hostList->ai_protocol); setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); } void SocketConnector::makeBind() { bind(sockfd, hostList->ai_addr, hostList->ai_addrlen); } void SocketConnector::freeHostsList() { freeaddrinfo(hostList); } void SocketConnector::makeListen() { listen(sockfd, 4); } ssize_t SocketConnector::getResponse(void *buff, size_t size) { ssize_t received = recv(clientfd, buff, size, 0); if (received == -1) { std::cerr << "Receiving error" << std::endl; } else if (received == 0) { std::cerr << "Client closed connection" << std::endl; } return received; } ssize_t SocketConnector::getResponse(Packet *&packet) { uint8_t tmp[256]; ssize_t receivedH = recv(clientfd, tmp, 11, 0); if (receivedH == -1) { std::cerr << "Receiving header error" << std::endl; return receivedH; } else if (receivedH == 0) { std::cerr << "Client closed connection" << std::endl; return receivedH; } packet = new Packet(tmp); ssize_t receivedD = recv(clientfd, tmp, packet->getDataSize(), 0); packet->putData(tmp, packet->getDataSize()); if (receivedD == -1) { std::cerr << "Receiving data error" << std::endl; } else if (receivedD == 0) { std::cerr << "Client closed connection" << std::endl; } return receivedH + receivedD; } void SocketConnector::makeAccept() { sckSize = sizeof(clientAddr); clientfd = accept(sockfd, (sockaddr*)&clientAddr, &sckSize); if (clientfd == -1){ exit(0); } } ssize_t SocketConnector::sendMessage(std::string msg) { ssize_t bytesSent = send(clientfd, msg.c_str(), msg.length(), 0); return bytesSent; } ssize_t SocketConnector::sendMessage(Packet *packet) { ssize_t bytesSent = send(clientfd, packet, (size_t)packet->getSize(), 0); return bytesSent; } void SocketConnector::closeClientSocket() { close(clientfd); } std::string SocketConnector::getReadableClientAddr() { char s[INET_ADDRSTRLEN]; inet_ntop(clientAddr.ss_family, &((sockaddr_in*)&clientAddr)->sin_addr, s, sizeof(s)); std::string addr(s); return addr; }
[ "pawkrol19@gmail.com" ]
pawkrol19@gmail.com
32a340dadce98dd9c2b37eb8cd45ff2723384020
982ba5b4822be347875cb3b1d63edebeeeee332b
/HOFMAN.CPP
314d0e0d0155dee8415f0369ff75bf7fa10acbb4
[]
no_license
amit988684/algorithm_problems
635aa9f7d71cf611439406e4d9bc00a16bc5e9d5
fc2b6283aec4936095eeec68a10bc013fd1f2e44
refs/heads/master
2020-03-13T04:00:05.062358
2018-04-25T05:23:12
2018-04-25T05:23:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,709
cpp
// C++ program to encode and decode a string using // Huffman Coding. #include <bits/stdc++.h> #define MAX_TREE_HT 256 using namespace std; // to map each character its huffman value map<char, string> codes; // to store the frequency of character of the input data map<char, int> freq; // A Huffman tree node struct MinHeapNode { char data; // One of the input characters int freq; // Frequency of the character MinHeapNode *left, *right; // Left and right child MinHeapNode(char data, int freq) { left = right = NULL; this->data = data; this->freq = freq; } }; // utility function for the priority queue struct compare { bool operator()(MinHeapNode* l, MinHeapNode* r) { return (l->freq > r->freq); } }; // utility function to print characters along with // there huffman value void printCodes(struct MinHeapNode* root, string str) { if (!root) return; if (root->data != '$') cout << root->data << ": " << str << "\n"; printCodes(root->left, str + "0"); printCodes(root->right, str + "1"); } // utility function to store characters along with // there huffman value in a hash table, here we // have C++ STL map void storeCodes(struct MinHeapNode* root, string str) { if (root==NULL) return; if (root->data != '$') codes[root->data]=str; storeCodes(root->left, str + "0"); storeCodes(root->right, str + "1"); } // STL priority queue to store heap tree, with respect // to their heap root node value priority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> minHeap; // function to build the Huffman tree and store it // in minHeap void HuffmanCodes(int size) { struct MinHeapNode *left, *right, *top; for (map<char, int>::iterator v=freq.begin(); v!=freq.end(); v++) minHeap.push(new MinHeapNode(v->first, v->second)); while (minHeap.size() != 1) { left = minHeap.top(); minHeap.pop(); right = minHeap.top(); minHeap.pop(); top = new MinHeapNode('$', left->freq + right->freq); top->left = left; top->right = right; minHeap.push(top); } storeCodes(minHeap.top(), ""); } // utility function to store map each character with its // frequency in input string void calcFreq(string str, int n) { for (int i=0; i<str.size(); i++) freq[str[i]]++; } // function iterates through the encoded string s // if s[i]=='1' then move to node->right // if s[i]=='0' then move to node->left // if leaf node append the node->data to our output string string decode_file(struct MinHeapNode* root, string s) { string ans = ""; struct MinHeapNode* curr = root; for (int i=0;i<s.size();i++) { if (s[i] == '0') curr = curr->left; else curr = curr->right; // reached leaf node if (curr->left==NULL and curr->right==NULL) { ans += curr->data; curr = root; } } // cout<<ans<<endl; return ans+'\0'; } // Driver program to test above functions int main() { string str = "geeksforgeeks"; string encodedString, decodedString; calcFreq(str, str.length()); HuffmanCodes(str.length()); cout << "Character With there Frequencies:\n"; for (auto v=codes.begin(); v!=codes.end(); v++) cout << v->first <<' ' << v->second << endl; for (auto i: str) encodedString+=codes[i]; cout << "\nEncoded Huffman data:\n" << encodedString << endl; decodedString = decode_file(minHeap.top(), encodedString); cout << "\nDecoded Huffman Data:\n" << decodedString << endl; return 0; }
[ "amitsharma.sgr99@gmail.com" ]
amitsharma.sgr99@gmail.com
5ee586c380c825d1e6933d4d84de15dbe2dcbb19
89b48905a2c1b3187a931e6e8cd3226a85d79916
/class/aggregation.cpp
e73c01581bc6b94cc8f822e4c334160e7f690b1b
[]
no_license
Geeky-har/c-files
36b3fd79466561aee83403434934a5a6010c6850
2b534efc5dd67987b7d50ea24442d688a54611f2
refs/heads/master
2022-12-15T07:59:33.228695
2020-09-06T12:25:08
2020-09-06T12:25:08
287,599,702
0
0
null
null
null
null
UTF-8
C++
false
false
1,131
cpp
#include<iostream> #include<string> using namespace std; class Address { public: string address_line,city,state; double pincode; Address(string address_line, string city, string state, double pincode) { this->address_line=address_line; this->city=city; this->state=state; this->pincode=pincode; } }; class Employee { Address *address; //address type pointer of address class public: int emp_id; string name; double sal; Employee(int emp_id, string name, double sal, Address *address) //accepting a reference type parameter { this->emp_id=emp_id; this->name=name; this->address=address; this->sal=sal; } void display() { cout<<"Your name is: "<<name<<endl; cout<<"Your id is: "<<emp_id<<endl; cout<<"Your salary is: "<<sal<<endl; cout<<"Your address is: "<<endl; cout<<address->address_line<<", "; cout<<address->city<<", "; cout<<address->state<<"-"; cout<<address->pincode<<endl; } }; int main() { Address a("H.no: 3103","faridabad","Haryana",121004); Employee e(101,"Harsh",45000,&a); //passing object as a argument e.display(); return 0; }
[ "harshnegi6477@gmail.com" ]
harshnegi6477@gmail.com
a17e2f83ec82babd07ddea6a8d54d9c06492a559
2b23944ed854fe8d2b2e60f8c21abf6d1cfd42ac
/CodeForces/612C/6592971_AC_46ms_2172kB.cpp
263935dc160cdf4e1f48ca6ec9b467e4470acb21
[]
no_license
weakmale/hhabb
9e28b1f2ed34be1ecede5b34dc2d2f62588a5528
649f0d2b5796ec10580428d16921879aa380e1f2
refs/heads/master
2021-01-01T20:19:08.062232
2017-07-30T17:23:21
2017-07-30T17:23:21
98,811,298
0
0
null
null
null
null
UTF-8
C++
false
false
646
cpp
#include<cstdio> #include<stack> using namespace std; char str[1000011]; int main(){ scanf("%s",str); int i=0; stack<char>cnt; int cns=0; bool k=true; while(str[i]){ if(str[i]=='['||str[i]=='('||str[i]=='{'||str[i]=='<'){ cnt.push(str[i]); } if(str[i]==']'||str[i]==')'||str[i]=='}'||str[i]=='>'){ if(cnt.empty()){ k=false; break; } else{ if( !( (str[i]==']'&&cnt.top()=='[') || (str[i]=='}'&&cnt.top()=='{')||(str[i]==')'&&cnt.top()=='(')||(str[i]=='>'&&cnt.top()=='<') ) ) cns++; cnt.pop(); } } i++; } if(cnt.empty()&&k) printf("%d\n",cns); else printf("Impossible\n"); return 0; }
[ "wuweak@gmail.com" ]
wuweak@gmail.com
ca00db3f844398671c73f64c941376711b6fd3cb
d22d9f975365921acd6df3bf4d38732edcbacd5a
/pe/problems/014/014.cpp
5816ac2e36e98ace81114411f79b991511b3f9e6
[]
no_license
zachstence/portfolio
81b6c759f259f8ca1f5b43ca3365a50be42d8ea1
65a6bb8af71138d7674ea2c25b806af1bf8abe75
refs/heads/master
2020-03-14T17:32:20.925543
2018-07-24T21:29:07
2018-07-24T21:29:07
131,722,454
0
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
#include<iostream> using namespace std; int findLength(unsigned long long num) { int count = 1; while (num > 1) { if (num % 2 == 0) { num /= 2; // cout << num << endl; count ++; } else { num = 3 * num + 1; // cout << num << endl; count++; } } return count; } int main () { int longest = 0; int length = 0; for (int i = 1; i < 1000000; i += 2) { if (findLength(i) > length) { longest = i; length = findLength(i); } } cout << longest << endl; }
[ "zachstence@gmail.com" ]
zachstence@gmail.com
f6ab0af00c9d4468fd8d60fb7c6c1b0913001276
ca43da281afed9025e9ffc5564b4203880034b3f
/test/mock/core/crypto/ed25519_provider_mock.hpp
71f6bb713cb9d4775b72a21dc13686a4ec9ff3e6
[ "Apache-2.0" ]
permissive
Harrm/kagome
ad914f052347581c6a3a1a818c6c8b0d3ed1ca04
22932bbbbf2f09712ca81b9e6256492f84cf2a46
refs/heads/master
2023-03-21T03:41:02.884895
2021-03-17T09:30:47
2021-03-17T09:30:47
349,340,056
0
0
Apache-2.0
2021-03-19T11:28:03
2021-03-19T07:41:25
null
UTF-8
C++
false
false
953
hpp
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_TEST_MOCK_CORE_CRYPTO_ED25519_PROVIDER_MOCK_HPP #define KAGOME_TEST_MOCK_CORE_CRYPTO_ED25519_PROVIDER_MOCK_HPP #include "crypto/ed25519_provider.hpp" #include <gmock/gmock.h> namespace kagome::crypto { class Ed25519ProviderMock : public Ed25519Provider { public: Ed25519Keypair; Ed25519Keypair; MOCK_CONST_METHOD2(sign, outcome::result<Ed25519Signature>(const Ed25519Keypair &, gsl::span<uint8_t>)); MOCK_CONST_METHOD3( verify, outcome::result<bool>(const Ed25519Signature &signature, gsl::span<uint8_t> message, const Ed25519PublicKey &public_key)); }; } // namespace kagome::crypto #endif // KAGOME_TEST_MOCK_CORE_CRYPTO_ED25519_PROVIDER_MOCK_HPP
[ "noreply@github.com" ]
Harrm.noreply@github.com
f40514df0fa8339d72ed76295c786b849e73ae6d
fb67c1ef104e5591a6bb6cbc8fe5d65172e0e8c9
/assignment_package/src/samplers/sampler.cpp
e1be1dcc204b54b47bc9323a49a0f0b76d8c2158
[]
no_license
CIS-461-2017/hw04_pathtracer_naive
8f8eb46cfdadf32c17acdc6d1c4271b4268e1d7d
9c42b7f54cf113f483c431dc893fdac64cdc2605
refs/heads/master
2021-01-13T08:22:35.193529
2017-05-14T14:40:00
2017-05-14T14:40:00
81,822,221
2
2
null
null
null
null
UTF-8
C++
false
false
1,089
cpp
#include "sampler.h" Sampler::Sampler(int samplesPerPixel, int seed) : samplesPerPixel(samplesPerPixel), rng(seed) {} Point2f Sampler::Get2D() { return Point2f(rng.nextFloat(), rng.nextFloat()); } std::unique_ptr<Sampler> Sampler::Clone(int seed) { Sampler* s = new Sampler(samplesPerPixel, seed); return std::unique_ptr<Sampler>(s); } std::vector<Point2f> Sampler::GenerateStratifiedSamples() { std::vector<Point2f> samples; // The square root of the number of samples input int sqrtVal = (int) (std::sqrt((float) samplesPerPixel) + 0.5); // A number useful for scaling a square of size sqrtVal x sqrtVal to 1 x 1 float invSqrtVal = 1.f / sqrtVal; samplesPerPixel = sqrtVal * sqrtVal; samples.resize(samplesPerPixel); for(int i = 0; i < samplesPerPixel; ++i) { int y = i / sqrtVal; int x = i % sqrtVal; glm::vec2 sample; sample = glm::vec2((x + rng.nextFloat()) * invSqrtVal, (y + rng.nextFloat()) * invSqrtVal); samples[i] = sample; } return samples; }
[ "admally@gmail.com" ]
admally@gmail.com
efffbd073919f1f18c01e9f3bcb78762b5b15b88
e206ed2dc587792460b2baab6056a4ef6cfce1ec
/src/qt/optionsdialog.cpp
e331e260916a767e3dba85a28ecf3b7c3081e929
[ "MIT" ]
permissive
Mrseed12/Vestx
8f2dc91013eb13eb4dce6d3a8432beed95a28bbc
8855e4533dda749e55f85310354c51979c724ed7
refs/heads/master
2020-03-25T01:20:52.981137
2018-09-02T21:40:32
2018-09-02T21:40:32
143,232,712
0
7
MIT
2018-09-22T11:42:07
2018-08-02T02:37:56
C++
UTF-8
C++
false
false
8,166
cpp
#include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "netbase.h" #include "optionsmodel.h" #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> #include <QRegExp> #include <QRegExpValidator> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fRestartWarningDisplayed_Proxy(false), fRestartWarningDisplayed_Lang(false), fProxyIpValid(true) { ui->setupUi(this); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); ui->socksVersion->setEnabled(false); ui->socksVersion->addItem("5", 5); ui->socksVersion->addItem("4", 4); ui->socksVersion->setCurrentIndex(0); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_OS_MAC ui->tabWindow->setVisible(false); #endif /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton())); /* setup/change UI elements when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool))); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } /* update the display unit, to not use the default ("BTC") */ updateDisplayUnit(); /* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */ connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang())); /* disable apply button after settings are loaded as there is nothing to save */ disableApplyButton(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->transactionFee, OptionsModel::Fee); mapper->addMapping(ui->reserveBalance, OptionsModel::ReserveBalance); mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion); /* Window */ #ifndef Q_OS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses); mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures); } void OptionsDialog::enableApplyButton() { ui->applyButton->setEnabled(true); } void OptionsDialog::disableApplyButton() { ui->applyButton->setEnabled(false); } void OptionsDialog::enableSaveButtons() { /* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */ if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); disableApplyButton(); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting VestxCOIN."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting VestxCOIN."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { /* Update transactionFee with the current unit */ ui->transactionFee->setDisplayUnit(model->getDisplayUnit()); } } void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fProxyIpValid = fState; if(fProxyIpValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fProxyIpValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if(event->type() == QEvent::FocusOut) { if(object == ui->proxyIp) { CService addr; /* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */ emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)); } } return QDialog::eventFilter(object, event); }
[ "hackergifta1@gmail.com" ]
hackergifta1@gmail.com
7f8569106f6520444c1bb3c2d11793eda529aa91
9c1e9b9fe210d3047b733245c85245f5a3cf039e
/QT-Example5-CentralizedCollaboration/customfontcombobox.cpp
c7756f58c5c53c92609ac61d0b9a31f1e4c38464
[]
no_license
michstmatt/Design-Patterns
e3dbff724352d7887547ffaad4c3b1368d0c9443
dca859246b4115ab8cddee6bef44c1acf1293233
refs/heads/master
2021-01-20T13:48:18.102842
2017-02-21T18:19:11
2017-02-21T18:19:11
82,712,352
0
0
null
null
null
null
UTF-8
C++
false
false
122
cpp
#include "customfontcombobox.h" void CustomFontComboBox::myCurrentFontChanged(const QFont&) { emit iChanged(this); }
[ "matt.pasco@hotmail.com" ]
matt.pasco@hotmail.com
f0f48b2bdcef7db2a37b6a1a24514d4204ba62f8
879681c994f1ca9c8d2c905a4e5064997ad25a27
/root-2.3.0/run/tutorials/multiphase/twoPhaseEulerFoam/RAS/fluidisedBed/1.2/epsilon.air
b108c9562084e5ac26e05b7d971a09ed6dd42a91
[]
no_license
MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu
3828272d989d45fb020e83f8426b849e75560c62
daeb870be81275e8a81f5cbac4ca1906a9bc69c0
refs/heads/master
2020-05-17T16:36:41.848261
2015-04-18T09:29:48
2015-04-18T09:29:48
34,159,882
1
0
null
null
null
null
UTF-8
C++
false
false
55,463
air
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "1.2"; object epsilon.air; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -3 0 0 0 0]; internalField nonuniform List<scalar> 6000 ( 119.206 18.4706 10.8759 9.80805 9.7256 9.98777 10.2917 10.4739 10.6013 10.5604 10.333 10.0833 9.89056 9.78045 9.69584 9.5828 9.43619 9.31733 9.21342 9.15123 9.175 9.35696 9.56287 9.59482 9.50296 9.38907 9.577 10.5906 17.0991 119.038 68.9648 24.7345 14.8078 12.0377 11.803 12.7539 14.5646 15.3951 15.1425 14.5025 13.6328 12.638 11.8743 11.4081 11.1648 10.9565 10.5957 10.209 9.93834 9.85376 9.98983 10.2484 10.5665 11.0776 11.3674 11.1847 11.8755 14.795 24.1664 71.2405 42.9079 21.2301 14.7721 13.132 13.037 13.4313 14.5754 15.0584 14.5548 13.8198 12.9528 12.0154 11.259 10.7966 10.5509 10.387 10.2246 10.0624 9.92409 9.81388 9.76569 9.86137 10.0809 10.4597 10.8585 11.2145 12.2941 14.7528 21.192 45.0584 34.6759 18.0735 14.0934 12.8762 13.0126 13.87 14.9221 15.0149 14.338 13.4327 12.3815 11.3151 10.5233 10.0646 9.80605 9.63404 9.53704 9.44247 9.32974 9.23621 9.18604 9.29764 9.5387 9.89077 10.3633 10.8971 11.8585 13.8976 18.2079 36.3157 28.5054 15.8421 12.9917 12.3212 12.8177 14.3422 14.9044 14.7508 14.0109 13.0245 11.7245 10.5962 9.86208 9.44293 9.16539 8.98328 8.85762 8.70287 8.5631 8.48995 8.51236 8.65804 8.93933 9.26184 9.68578 10.1518 10.8147 12.4408 15.8453 32.5144 22.77 14.1525 12.0473 12.2518 13.0748 14.8226 14.6909 14.1508 13.2871 12.2601 10.997 9.99598 9.41578 9.03434 8.72056 8.5353 8.43791 8.33843 8.23161 8.12853 8.03607 8.06964 8.23847 8.48726 8.80223 9.02692 9.42057 10.6592 13.4946 28.0823 17.7104 12.1762 11.38 12.4982 13.7308 15.1176 14.2672 13.3816 12.3346 11.3755 10.414 9.60577 9.16171 8.82406 8.57376 8.5536 8.59612 8.50306 8.33383 8.17418 7.98944 7.82592 7.82189 7.97315 8.14341 8.29933 8.58596 9.40207 11.222 21.4854 14.1913 10.457 11.3883 13.1979 14.4821 15.1295 13.8672 12.58 11.5291 10.7711 10.0152 9.48157 9.15561 8.91867 8.82068 9.05073 9.27776 9.12677 8.78893 8.53026 8.318 8.09286 7.99525 8.10511 8.2197 8.20123 8.23491 8.61353 9.38328 15.8497 14.7063 11.1242 12.884 13.7286 14.547 15.2646 13.9976 12.1837 11.1748 10.5441 10.0691 9.67819 9.47143 9.40901 9.53779 9.9558 10.4548 10.3917 9.93847 9.49299 9.2304 9.09547 9.17076 9.41364 9.46389 9.09662 8.85622 9.0507 9.36696 14.5044 18.8479 15.6189 16.9539 14.9063 15.0655 15.9223 14.4819 12.5044 11.6447 11.03 10.5947 10.3169 10.3393 10.6564 11.2527 12.1448 13.0691 13.2751 12.6107 11.7893 11.3563 11.3699 11.7562 12.097 11.9101 11.1178 10.5491 10.6523 10.8133 16.7639 29.3967 24.7876 24.3348 18.265 17.0523 16.7266 15.5024 13.9595 13.3239 12.6356 12.2197 12.1216 12.3008 12.6582 13.1771 13.8788 14.7351 15.3426 14.5584 13.2932 12.6918 12.6903 13.1675 13.4992 13.0179 11.8743 11.1697 10.9881 11.5302 20.6133 40.3737 32.5723 27.7977 23.1061 19.6738 18.4459 17.0671 16.1854 15.4403 14.3379 13.6495 13.3955 13.3026 13.2121 13.2373 13.4852 13.8655 14.1051 13.5224 12.6473 12.37 12.4295 12.6825 12.6152 11.6856 10.6867 10.4397 10.4376 10.9887 19.7693 45.5048 33.45 28.1243 23.8334 21.7086 18.5692 17.3838 16.8756 15.6063 14.4449 13.6259 13.0893 12.6605 12.382 12.3018 12.3529 12.4689 12.492 12.082 11.6022 11.6068 11.5514 11.255 10.56 9.61801 8.94198 8.85584 9.13994 9.79074 17.7965 48.478 32.5317 26.8231 22.4613 19.8129 17.3456 16.233 15.5731 14.6275 13.633 12.8218 12.1882 11.717 11.4476 11.3667 11.3816 11.4046 11.3189 11.0859 10.644 10.5709 10.3075 9.68513 8.91113 8.18374 7.64495 7.43713 7.59994 8.26543 14.0365 49.7917 32.3127 25.0523 20.2125 17.5352 15.6007 14.5143 13.8136 13.1323 12.4652 11.8593 11.3356 10.9067 10.6583 10.5837 10.5831 10.5675 10.4703 10.3701 9.86552 9.58731 9.16293 8.47671 7.80962 7.24449 6.76146 6.40799 6.2987 6.67382 10.0857 50.1303 32.1222 23.1229 18.1604 15.6433 14.0524 13.0861 12.4386 11.9046 11.4273 10.9952 10.6016 10.248 10.04 9.98001 9.9707 9.94444 9.89897 9.84381 9.2402 8.78963 8.27244 7.63044 7.07548 6.60015 6.15048 5.73328 5.45959 5.51195 7.88492 50.5238 30.921 20.8083 16.3632 14.1176 12.7812 11.9418 11.3771 10.9521 10.5981 10.2972 10.0277 9.75182 9.59352 9.5565 9.54367 9.53197 9.55998 9.44596 8.72471 8.18985 7.64338 7.06962 6.58014 6.14399 5.72273 5.3176 5.0168 5.02994 7.66505 53.445 27.7107 18.5322 14.8682 12.925 11.7803 11.0618 10.5814 10.2407 9.97472 9.76813 9.58666 9.39316 9.28053 9.27456 9.27734 9.2971 9.36403 9.04621 8.29636 7.76201 7.23087 6.71057 6.25271 5.83673 5.44492 5.08652 4.84184 4.99509 8.16866 51.5682 24.0908 16.7839 13.7623 12.0758 11.0693 10.431 10.0158 9.73052 9.51827 9.36363 9.22186 9.12562 9.02328 9.08403 9.15537 9.19156 9.13481 8.58334 7.93245 7.44621 6.95413 6.4775 6.0466 5.65619 5.30203 5.00528 4.85149 5.20142 9.59338 46.6198 21.1719 15.4878 13.0412 11.586 10.6502 10.0364 9.6399 9.36737 9.17307 9.02831 8.90712 8.88879 8.785 8.9034 9.07308 9.045 8.72603 8.10549 7.60293 7.17901 6.74779 6.32831 5.94245 5.59347 5.28516 5.04461 4.9831 5.57699 10.9783 38.5135 18.4604 14.3888 12.6524 11.4673 10.5246 9.86806 9.42051 9.10893 8.90014 8.75723 8.65033 8.65193 8.55634 8.65712 8.82548 8.67659 8.16785 7.66477 7.29044 6.95347 6.60601 6.26265 5.93877 5.63852 5.3785 5.20333 5.24343 6.01905 12.2375 32.2263 16.0776 13.6019 12.5738 11.6105 10.6608 9.90502 9.33059 8.93085 8.69282 8.55623 8.47343 8.41933 8.30507 8.33352 8.38412 8.09298 7.64869 7.30699 7.05831 6.81633 6.55906 6.2941 6.03555 5.79971 5.60374 5.49609 5.61884 6.55829 13.5619 31.1394 15.189 13.749 12.9907 11.9985 11.0173 10.0894 9.33732 8.82273 8.55214 8.44714 8.37196 8.21411 8.03561 7.96379 7.8752 7.61067 7.31759 7.11878 6.96321 6.8033 6.62306 6.43718 6.25809 6.09324 5.96211 5.9195 6.1221 7.22649 15.108 30.9643 15.1739 13.6353 13.3793 12.418 11.3388 10.3368 9.40871 8.77773 8.49441 8.43202 8.30675 8.01811 7.76902 7.60849 7.49661 7.34524 7.2037 7.09854 7.00942 6.91448 6.81404 6.71196 6.61183 6.52223 6.46259 6.4901 6.7782 8.06333 17.0004 29.4002 14.8452 12.4587 12.4523 12.3209 11.2792 10.4352 9.44287 8.75171 8.51708 8.4316 8.15783 7.78058 7.52129 7.35582 7.29276 7.28175 7.24759 7.21658 7.19546 7.17235 7.14743 7.1265 7.11249 7.10839 7.13111 7.24251 7.63762 9.14434 19.4224 25.1182 13.8134 11.0783 11.1972 11.7716 10.85 10.1592 9.27192 8.70054 8.48913 8.22139 7.84702 7.56704 7.39708 7.296 7.3393 7.40141 7.44784 7.50185 7.54816 7.58537 7.62906 7.68647 7.76969 7.86488 7.98908 8.22006 8.77751 10.6054 22.7377 19.389 12.2713 10.3363 10.9232 11.5878 10.2785 9.42195 8.87374 8.47846 8.12966 7.84624 7.68935 7.6092 7.5711 7.58896 7.67 7.76407 7.8734 7.9789 8.07404 8.1536 8.25382 8.39224 8.56003 8.76724 9.05045 9.49136 10.3369 12.6213 27.1533 14.9318 10.5815 10.0156 11.3084 11.7767 10.139 8.92145 8.29249 7.99201 7.90936 7.94373 8.03237 8.1599 8.26217 8.32697 8.38037 8.45187 8.55909 8.67944 8.78114 8.87922 9.00712 9.20597 9.4862 9.87655 10.431 11.2572 12.696 16.1539 37.0292 12.7148 9.37987 9.86694 11.7195 12.0783 10.2367 8.69603 8.14733 8.20588 8.43178 8.69479 9.00531 9.32305 9.50019 9.50212 9.47593 9.48093 9.53845 9.62913 9.70667 9.78923 9.95371 10.272 10.7659 11.4518 12.4114 13.8645 16.4006 22.1647 51.8661 11.6685 8.80212 10.0571 12.2191 12.3896 10.4013 8.9682 8.72739 9.17894 9.71393 10.1445 10.546 10.9119 11.1126 11.0658 10.9431 10.8499 10.8368 10.8688 10.9158 11.0075 11.2728 11.7924 12.5779 13.6801 15.261 17.7282 22.184 32.2669 80.6344 11.6781 9.04194 11.0402 13.6407 13.4673 11.1456 10.0604 10.1576 10.7944 11.5579 12.1688 12.6347 12.9715 13.1187 13.0092 12.7708 12.563 12.4631 12.4365 12.4733 12.6248 13.0566 13.8481 15.0339 16.6641 19.0821 22.776 29.1618 43.9258 107.171 12.5315 10.5411 13.6514 17.1964 16.4573 13.247 12.1973 12.2605 12.9183 13.9907 14.8879 15.3952 15.6081 15.5829 15.3247 14.9369 14.6031 14.4109 14.342 14.3915 14.6772 15.3625 16.5057 18.1611 20.4331 23.4988 27.9997 35.3389 47.8347 105.601 15.567 14.1443 18.182 22.903 21.9079 16.9383 15.2354 15.0214 15.6958 17.1317 18.439 18.9208 18.8467 18.4956 17.962 17.3843 16.9184 16.6443 16.5494 16.6581 17.1805 18.2478 19.8551 21.8885 24.3422 27.5357 31.8553 37.4788 47.4256 102.078 21.8619 20.0285 24.6048 28.8116 25.6927 21.0205 18.4386 17.9367 18.7392 20.4972 22.5689 23.1825 22.5584 21.6688 20.7696 19.9832 19.413 19.1005 19.0259 19.2714 20.067 21.3893 23.2321 25.4875 26.8626 29.0554 33.1528 38.8699 48.7151 105.217 34.7239 28.7154 30.4379 30.786 25.6689 22.2505 20.5578 20.3954 21.5318 23.7102 26.3554 27.4505 26.4134 24.7637 23.4766 22.5097 21.9463 21.7091 21.6145 22.0044 23.1014 24.5059 25.3996 25.9801 27.0453 29.8252 34.6074 40.3725 51.0285 113.851 50.2747 34.4797 36.2959 29.7663 25.3951 22.5386 21.0968 21.2522 22.7411 25.2912 28.6416 30.5827 29.5036 27.2551 25.6624 24.6809 24.1744 23.809 23.9338 24.062 24.2819 24.8577 25.1986 25.5925 27.1711 30.7355 35.4243 40.8042 52.0172 119.665 62.4076 38.7463 38.0251 28.7133 24.2948 22.0081 21.1618 21.7048 23.4824 26.3858 29.9661 32.0261 30.81 28.6151 27.0196 26.2209 25.4645 25.0889 24.433 24.1278 24.0438 24.059 24.2426 25.0913 27.4617 31.5124 35.905 40.8303 52.0284 120.968 68.3516 41.1079 37.9988 28.1297 23.4812 21.5129 21.1725 22.1392 24.3213 27.7042 31.9204 33.6544 31.4946 29.1794 27.6592 26.7615 26.093 24.9595 23.8805 23.2493 23.0022 23.0504 23.4722 24.8333 27.931 32.4108 36.5554 40.9279 51.8055 120.316 70.1046 41.9781 37.9379 27.7129 23.1087 21.3552 21.2988 22.5678 25.0472 28.8069 33.4016 34.3856 31.6231 29.0533 27.8328 26.5509 25.5918 24.115 22.9086 22.237 22.0309 22.1953 22.8852 24.747 28.5359 33.4471 37.4053 41.1745 51.3548 118.486 70.4826 42.0856 37.3861 27.3378 22.9404 21.369 21.5064 22.947 25.5929 29.5419 34.2787 34.232 30.9037 28.1183 26.6457 25.5965 24.4294 22.9789 21.8331 21.2357 21.1165 21.4142 22.3872 24.7377 29.1427 34.4534 38.3008 41.5141 50.8628 115.87 69.5105 41.4145 36.1398 26.8352 22.8057 21.4352 21.702 23.2146 25.897 29.8313 34.2793 33.2309 29.4542 26.6136 24.7496 23.9769 22.9376 21.5979 20.6381 20.1845 20.1897 20.6475 21.9074 24.7044 29.6253 35.2809 39.0997 41.8579 50.3931 113.356 68.2061 40.6022 34.4512 26.1587 22.6063 21.4494 21.8188 23.3475 25.957 29.6816 33.4918 31.7803 27.6632 24.8415 22.8206 22.1809 21.3217 20.1497 19.3769 19.0833 19.2257 19.8671 21.3983 24.5822 29.901 35.8144 39.6966 42.1513 49.9592 110.984 68.3802 40.2722 32.6268 25.3533 22.3067 21.3784 21.8082 23.3201 25.8173 29.2129 32.1414 30.0678 25.9447 22.9716 21.0654 20.4327 19.7302 18.73 18.1117 17.9562 18.2339 19.0564 20.832 24.3239 29.903 35.9891 40.0287 42.3496 49.5299 108.64 69.8714 40.2625 30.9833 24.5087 21.9045 21.1847 21.6715 23.1222 25.4443 28.4516 30.4467 28.0474 24.2421 21.2897 19.5275 18.8067 18.2232 17.3732 16.8756 16.8297 17.2279 18.212 20.1962 23.9175 29.6505 35.8347 40.0483 42.3941 49.0689 106.231 69.7381 39.83 29.2702 23.5983 21.3819 20.8269 21.3386 22.6883 24.78 27.2712 28.2789 25.7642 22.3712 19.7346 18.0707 17.2985 16.8075 16.0827 15.6818 15.7233 16.2258 17.345 19.4935 23.3562 29.1045 35.3549 39.8416 42.309 48.5694 103.694 67.1609 38.1168 27.2587 22.5801 20.7366 20.3144 20.8078 22.0268 23.8296 25.6746 25.7172 23.2895 20.4168 18.17 16.6583 15.8873 15.4443 14.8458 14.5389 14.6568 15.2457 16.4684 18.7324 22.6472 28.3072 34.5359 39.3066 42.0359 47.9704 100.686 70.1559 35.08 25.1401 21.4732 19.9759 19.6606 20.1251 21.1957 22.6363 23.6762 22.9323 20.8177 18.5404 16.691 15.3684 14.5929 14.1501 13.6784 13.4617 13.6471 14.301 15.5943 17.9235 21.8112 27.3041 33.4305 38.4162 41.4832 47.2903 97.439 71.3923 31.8887 23.3738 20.3449 19.1276 18.902 19.3403 20.2554 21.2573 21.3979 20.2733 18.5922 16.873 15.3945 14.2536 13.4768 12.9945 12.6075 12.4679 12.7052 13.3994 14.7297 17.0739 20.8697 26.1333 32.0825 37.2243 40.6473 46.356 93.4219 67.7275 29.0808 21.7625 19.1946 18.2306 18.0914 18.5048 19.2239 19.6324 19.0663 17.9431 16.7101 15.4646 14.3052 13.3264 12.5546 12.0034 11.655 11.5692 11.8358 12.5436 13.8782 16.192 19.8457 24.838 30.5541 35.7824 39.5727 45.3353 88.6645 60.538 26.3818 20.1852 18.0668 17.336 17.2744 17.6323 17.9863 17.7378 16.9353 16.0301 15.1635 14.29 13.3974 12.56 11.805 11.1947 10.8332 10.7686 11.0436 11.7369 13.0422 15.2837 18.7572 23.457 28.9032 34.1422 38.2964 44.2479 83.4513 53.4007 24.0261 18.7505 17.0093 16.4738 16.4654 16.6408 16.4735 15.8621 15.1462 14.4907 13.8915 13.284 12.6026 11.8918 11.1762 10.5386 10.1391 10.0571 10.3148 10.9695 12.2189 14.3499 17.615 22.0124 27.1672 32.334 36.761 42.7708 77.5502 47.6934 22.0679 17.4529 16.0419 15.6643 15.5939 15.3721 14.8315 14.2344 13.709 13.252 12.8246 12.38 11.8533 11.2569 10.6094 9.99035 9.5618 9.43302 9.63789 10.2359 11.3977 13.3827 16.4212 20.5111 25.3542 30.3596 34.9082 40.7069 70.9549 43.962 20.4151 16.3245 15.1918 14.8365 14.4706 13.9045 13.3529 12.9134 12.5557 12.2283 11.8971 11.5447 11.1266 10.6228 10.0668 9.51064 9.08075 8.9046 9.02717 9.53572 10.5863 12.3971 15.1814 18.9569 23.4675 28.2278 32.7304 38.1188 64.0796 40.7059 18.9635 15.3931 14.3388 13.7318 13.0812 12.5145 12.1188 11.8388 11.5965 11.3434 11.0656 10.7664 10.422 9.99841 9.53713 9.06868 8.67114 8.46555 8.49957 8.88161 9.78128 11.3926 13.8994 17.3496 21.5071 25.9468 30.2281 35.0691 57.1887 37.3416 17.6552 14.4753 13.1277 12.2776 11.6775 11.3016 11.0785 10.9128 10.7402 10.5363 10.3017 10.0438 9.75188 9.40228 9.02622 8.64466 8.30266 8.08784 8.05468 8.29414 8.98858 10.3707 12.5773 15.694 19.4904 23.5643 27.4802 31.7102 50.4313 32.1073 16.1252 13.0557 11.5263 10.7993 10.4302 10.2525 10.1562 10.0645 9.94439 9.78964 9.60367 9.39009 9.14448 8.85945 8.5516 8.23858 7.95037 7.73973 7.66115 7.7759 8.23506 9.32254 11.2189 13.9638 17.4186 21.1322 24.6351 28.1779 43.9578 24.9806 14.1991 11.0427 9.90676 9.52913 9.40836 9.3744 9.35566 9.31748 9.24738 9.14302 9.00542 8.83566 8.63271 8.39726 8.13868 7.87166 7.61901 7.41298 7.29739 7.30535 7.55521 8.27929 9.80377 12.18 15.2889 18.6766 21.7973 24.6 37.9103 17.1329 10.9145 8.91472 8.5662 8.56243 8.61244 8.66578 8.70257 8.71198 8.68849 8.629 8.53311 8.4011 8.23347 8.03323 7.80748 7.56834 7.33335 7.12521 6.96905 6.89633 6.96256 7.35182 8.39223 10.3506 13.1147 16.2572 19.0705 21.1598 32.3261 11.0712 7.81196 7.44534 7.64501 7.8508 8.00046 8.11599 8.2019 8.25555 8.27329 8.25249 8.19139 8.08979 7.94897 7.7724 7.56664 7.34193 7.11195 6.89302 6.70212 6.55707 6.49409 6.60501 7.16602 8.56803 10.946 13.875 16.5846 18.0451 27.414 8.09176 6.36107 6.66112 7.07094 7.353 7.5577 7.72033 7.84959 7.94385 7.9991 8.01167 7.97937 7.9014 7.77938 7.61699 7.42065 7.1994 6.9645 6.7285 6.504 6.30267 6.14003 6.06929 6.23476 7.03196 8.85789 11.6347 14.1968 15.3181 23.1949 7.93829 6.03438 6.33915 6.74818 7.04339 7.27695 7.47641 7.64468 7.77649 7.86591 7.90784 7.89905 7.83858 7.72797 7.57116 7.37449 7.14649 6.89721 6.63753 6.37801 6.12712 5.89278 5.69081 5.60296 5.8554 6.98352 9.33993 11.9907 12.9216 19.5831 8.90359 6.19997 6.34049 6.6395 6.9082 7.15663 7.38818 7.59299 7.75928 7.87667 7.94034 7.94754 7.89695 7.78992 7.63046 7.42513 7.18261 6.9129 6.62558 6.32744 6.02745 5.73124 5.44031 5.17381 5.0634 5.43979 6.93485 9.58198 11.3529 16.6989 11.6352 6.74548 6.5045 6.68718 6.92923 7.19029 7.44923 7.68507 7.88152 8.02762 8.11491 8.13821 8.0948 7.98572 7.81521 7.5903 7.32034 7.01642 6.6906 6.35321 6.00897 5.6563 5.29657 4.9288 4.59475 4.48504 5.02709 6.89642 9.77128 14.1335 15.0621 7.66316 6.88095 6.89641 7.10215 7.38362 7.67916 7.95421 8.18699 8.36289 8.47093 8.50403 8.45995 8.33979 8.14825 7.89333 7.58566 7.23723 6.86043 6.46835 6.07227 5.67635 5.27542 4.85942 4.42514 4.04642 3.98366 4.8288 7.25074 11.2085 18.3096 8.7267 7.43179 7.30302 7.48503 7.78707 8.1145 8.42335 8.68753 8.8886 9.01296 9.05173 9.00103 8.86167 8.63919 8.34324 7.98668 7.58427 7.15127 6.70219 6.24763 5.79788 5.35711 4.91866 4.46698 3.97458 3.57285 3.76121 5.40071 8.30028 20.6469 9.61407 8.07226 7.87482 8.05826 8.38431 8.74604 9.09265 9.39235 9.62185 9.76364 9.80589 9.74318 9.57624 9.31198 8.96257 8.54419 8.07539 7.57546 7.06264 6.55232 6.05583 5.57726 5.11543 4.65014 4.12652 3.4676 3.13368 4.4002 6.43183 21.1308 10.2104 8.77482 8.60202 8.81261 9.17618 9.5835 9.9787 10.3237 10.5892 10.7524 10.7977 10.7182 10.5147 10.1961 9.77845 9.28254 8.73215 8.15175 7.56447 6.99023 6.44452 5.93674 5.46898 5.02082 4.49292 3.59645 2.95487 3.35783 5.00793 21.3538 11.15 9.65073 9.50007 9.75217 10.1709 10.6422 11.1038 11.5101 11.8238 12.0158 12.066 11.9651 11.7146 11.3265 10.822 10.2287 9.57761 8.89963 8.22345 7.57352 6.96904 6.42337 5.94231 5.50854 4.98527 3.97476 3.076 2.89842 4.11864 22.3852 12.2296 10.6943 10.5756 10.8877 11.3845 11.9446 12.4973 12.9868 13.3666 13.599 13.6578 13.5309 13.2202 12.7425 12.127 11.411 10.635 9.83809 9.05484 8.31384 7.6367 7.03889 6.52843 6.08898 5.54329 4.56955 3.54068 3.09835 4.29586 24.8629 13.5507 11.9335 11.8508 12.2405 12.8413 13.5202 14.1948 14.797 15.267 15.5562 15.6294 15.4699 15.0809 14.4867 13.7283 12.8572 11.9259 10.9834 10.0709 9.22 8.45342 7.78688 7.23168 6.77383 6.21915 5.37794 4.56314 4.11628 6.15122 28.6641 15.2453 13.4255 13.3575 13.8374 14.5692 15.4019 16.2373 16.9905 17.5837 17.9516 18.0446 17.8423 17.3509 16.6045 15.6607 14.5921 13.4678 12.3475 11.2783 10.2949 9.41978 8.66844 8.05612 7.5834 7.07327 6.37525 5.86069 6.26697 11.8637 33.0871 17.2851 15.1833 15.1158 15.6999 16.5942 17.6233 18.6692 19.6246 20.3862 20.8592 20.9733 20.7039 20.0725 19.1282 17.9449 16.6268 15.2651 13.9305 12.6743 11.5315 10.525 9.67097 8.98767 8.49296 8.0574 7.44173 7.17153 8.48822 19.3828 37.902 19.6203 17.1952 17.1294 17.8397 18.9365 20.2167 21.5393 22.7669 23.7603 24.3575 24.4625 24.0619 23.2246 22.0343 20.5648 18.9454 17.3016 15.7162 14.2425 12.9129 11.7475 10.7636 9.98581 9.43931 9.08126 8.56063 8.46762 10.1511 24.4476 42.9987 22.202 19.4395 19.3892 20.2572 21.6096 23.2157 24.9065 26.5048 27.8036 28.5085 28.5263 27.8542 26.6748 25.1946 23.43 21.4915 19.5365 17.6718 15.9548 14.4139 13.0641 11.9162 10.9938 10.3245 9.9311 9.59917 9.66087 11.3444 25.3999 48.3239 24.9892 21.8876 21.8737 22.9401 24.6172 26.6472 28.8343 30.9546 32.5709 33.3771 33.2466 32.0906 30.2992 28.3627 26.3487 24.1615 21.9108 19.7552 17.7776 16.008 14.4559 13.1209 12.0192 11.1688 10.6045 10.4178 10.5839 12.3692 26.4888 53.8464 27.9444 24.501 24.5461 25.8578 27.9384 30.5174 33.3934 36.1278 38.0723 39.142 38.9146 37.0858 34.3928 31.6302 29.2733 26.8739 24.3713 21.9287 19.6824 17.6741 15.9128 14.3906 13.1063 12.0727 11.3272 11.0307 11.3746 13.3109 28.2608 59.5522 31.0259 27.2273 27.3488 28.9447 31.5074 34.7959 38.4843 41.8671 44.2095 46.0587 45.9154 42.991 39.1031 35.4112 32.4111 29.699 26.8923 24.1669 21.6513 19.4002 17.4285 15.7319 14.2834 13.0978 12.1983 11.7234 11.904 13.8277 28.3156 65.4388 34.1701 29.9946 30.192 32.0935 35.2073 39.1925 43.7221 47.6492 50.5494 53.3217 53.4323 49.4101 44.1122 39.4843 35.8853 32.6924 29.4851 26.4592 23.6768 21.182 19.0003 17.128 15.5452 14.2361 13.2233 12.6221 12.5872 14.2289 26.9067 71.476 37.2934 32.7003 32.9614 35.1853 38.7545 43.3158 48.342 52.8424 56.2299 58.7299 58.9076 54.7101 48.806 43.6466 39.551 35.7635 32.1349 28.8052 25.7588 23.0217 20.6311 18.5882 16.874 15.4709 14.3889 13.7222 13.634 15.1957 25.9403 77.5234 40.2838 35.2302 35.544 37.9968 41.995 47.0908 52.491 55.8877 57.6849 59.1232 59.4975 58.2248 53.0834 47.833 43.2191 38.8763 34.8558 31.2209 27.9062 24.9229 22.3225 20.1116 18.2712 16.7858 15.6611 14.9985 14.9653 16.741 27.4364 83.5055 43.0459 37.4571 37.7029 40.3685 44.819 50.3922 54.4838 55.5272 57.1648 58.7605 59.258 59.2278 57.5729 52.2693 46.9982 42.1332 37.7149 33.7445 30.1363 26.8888 24.0672 21.6824 19.7142 18.1484 16.9967 16.3746 16.5125 18.8136 32.6284 89.8376 45.3975 39.1022 39.2374 41.9797 46.5025 51.5487 53.138 54.4949 56.1568 57.7068 58.4428 58.5554 59.1473 56.9528 51.3554 45.7509 40.8165 36.4268 32.4669 28.9179 25.8507 23.2754 21.1684 19.5142 18.335 17.7593 18.0932 20.9662 38.6308 95.5458 46.9808 40.0622 39.936 42.2547 46.8263 49.6807 51.2368 52.8538 54.5044 55.9612 56.8677 57.183 57.6532 58.424 55.8846 50.0195 44.2572 39.3046 34.8993 30.9939 27.6485 24.8608 22.5984 20.8411 19.6204 19.0747 19.5859 22.9895 44.0534 100.291 47.9751 40.3924 39.6762 41.5925 44.9435 47.2669 49.1578 50.7993 52.3069 53.6421 54.5921 55.1242 55.5556 56.2474 56.9563 54.2646 48.1226 42.3578 37.3998 33.0792 29.4216 26.401 23.9694 22.0969 20.8159 20.2723 20.9159 24.7767 49.2857 105.461 48.7583 40.2636 38.9079 40.2352 42.6821 45.2651 47.0885 48.5191 49.8009 50.9306 51.8182 52.4413 52.9513 53.4697 54.1953 54.5529 51.7042 45.5841 39.9177 35.1152 31.1151 27.8495 25.2451 23.256 21.9053 21.3393 22.0443 26.2177 53.0937 110.764 49.0192 39.7153 37.973 38.4619 40.6401 43.297 45.0217 46.1431 47.136 48.0552 48.8366 49.4749 50.0237 50.5206 50.993 51.572 51.6844 48.45 42.4772 37.0527 32.6669 29.1518 26.3867 24.2957 22.8846 22.2946 23.0326 27.3487 55.3895 111.045 48.5569 38.7603 36.3933 36.3671 37.8742 40.2067 42.4226 43.6165 44.3769 45.1261 45.8301 46.462 47.0321 47.5289 47.9454 48.3919 48.9777 48.9726 44.361 38.6604 33.9451 30.2279 27.3489 25.1898 23.7447 23.155 23.9504 28.4892 57.4134 105.174 46.3957 36.843 34.4146 34.2053 35.1737 36.7896 38.7497 40.6029 41.6199 42.2636 42.896 43.498 44.0621 44.5634 44.9917 45.4088 45.914 46.5041 44.869 39.117 34.6191 30.9438 28.0734 25.9045 24.4631 23.9089 24.8075 29.6277 60.3592 91.6547 42.6551 34.6185 32.4781 32.2472 32.9512 34.1249 35.4903 36.9819 38.4693 39.4275 40.0501 40.6565 41.2083 41.6814 42.1117 42.5222 42.9327 43.3455 42.9982 38.7596 34.6592 31.3135 28.5396 26.4212 25.0194 24.5293 25.5556 30.7005 63.4424 82.181 39.7779 32.664 30.7074 30.4491 30.9916 31.9214 32.9686 33.9908 35.0481 36.1904 37.1675 37.9148 38.5091 38.9394 39.3092 39.679 40.0661 40.3715 40.2519 37.747 34.349 31.3727 28.7797 26.7533 25.4175 25.0052 26.1617 31.613 65.6933 79.1988 37.8746 31.0133 29.1223 28.8294 29.2573 30.0264 30.8985 31.7031 32.4029 33.1537 34.0742 35.0118 35.7699 36.2669 36.6557 37.0266 37.3975 37.7612 37.9331 36.3147 33.7196 31.1528 28.8007 26.9148 25.6711 25.3398 26.6084 32.3112 67.7261 77.2737 36.3998 29.6125 27.736 27.4159 27.7665 28.4178 29.1582 29.8465 30.4081 30.8907 31.4721 32.2438 33.0164 33.5946 34.0717 34.5876 35.1062 35.6067 35.8335 34.7141 32.8028 30.6603 28.6087 26.913 25.796 25.5423 26.882 32.7443 69.0161 75.0184 35.0308 28.3916 26.5807 26.2673 26.5631 27.1113 27.7285 28.3097 28.8012 29.2111 29.6225 30.1413 30.7467 31.2939 31.7842 32.3863 33.1064 33.7642 33.9071 33.1405 31.7036 29.9295 28.2044 26.7751 25.823 25.6566 27.0187 32.8362 68.8927 72.1025 33.6756 27.4035 25.7312 25.4393 25.6758 26.117 26.6106 27.0808 27.4964 27.8684 28.2437 28.6659 29.1319 29.5889 30.0517 30.6494 31.4364 32.1305 32.2576 31.6712 30.4825 29.0242 27.6316 26.4972 25.7667 25.717 27.0895 32.7517 67.6351 67.4114 32.4204 26.7425 25.245 24.9682 25.1219 25.441 25.8092 26.1689 26.5035 26.8271 27.1665 27.5395 27.9374 28.3474 28.8066 29.384 30.0907 30.6972 30.7843 30.2519 29.2515 28.0754 26.9791 26.1293 25.6445 25.7361 27.1373 32.7016 66.6698 63.7016 31.8355 26.5179 25.2 24.9193 24.9499 25.1096 25.3355 25.5778 25.8236 26.0848 26.3751 26.6954 27.0381 27.4096 27.8325 28.3363 28.8914 29.3195 29.3384 28.8958 28.1173 27.1986 26.3399 25.7078 25.431 25.6864 27.2137 32.7188 66.9119 63.2972 31.905 26.7765 25.576 25.2734 25.147 25.1107 25.1648 25.2766 25.4263 25.6148 25.8414 26.0999 26.3845 26.697 27.0466 27.4339 27.8163 28.0699 28.0418 27.7061 27.1323 26.4346 25.7631 25.2777 25.1396 25.5985 27.2676 33.0423 67.6401 64.2403 32.7201 27.6323 26.2114 25.7596 25.5563 25.3195 25.1937 25.1857 25.2526 25.3713 25.5304 25.7234 25.9448 26.1903 26.4565 26.729 26.9675 27.0942 27.0327 26.7679 26.3364 25.8028 25.2714 24.8874 24.8369 25.4328 27.3842 33.3811 70.0542 68.1365 34.7033 28.7986 26.9369 26.1266 25.7754 25.4827 25.2661 25.2045 25.2285 25.2964 25.4017 25.5411 25.7087 25.8965 26.092 26.2758 26.4137 26.458 26.3674 26.1349 25.7835 25.3534 24.9159 24.5952 24.5909 25.2368 27.3511 34.0091 72.6389 77.4268 36.9564 30.1397 27.4406 26.2483 25.7213 25.4448 25.2962 25.264 25.2843 25.3407 25.4292 25.5469 25.6868 25.8377 25.9853 26.11 26.1843 26.1776 26.0627 25.8376 25.522 25.1474 24.7673 24.4863 24.4924 25.1344 27.2514 34.1318 72.4807 86.5512 39.7792 31.1543 27.7954 26.3391 25.7182 25.4496 25.3688 25.383 25.4388 25.5212 25.6263 25.7501 25.8861 26.0241 26.1493 26.2435 26.2847 26.2495 26.1172 25.8862 25.5756 25.2168 24.8578 24.5914 24.5898 25.1885 27.179 33.7047 71.2628 91.1424 41.7711 31.6448 27.9957 26.4821 25.8586 25.6212 25.5582 25.614 25.7423 25.8985 26.0645 26.2324 26.3944 26.5401 26.6571 26.7303 26.7448 26.6829 26.5293 26.2809 25.9557 25.5875 25.2237 24.9472 24.9122 25.4273 27.2254 32.9997 67.6489 92.2655 41.6723 31.5969 28.1351 26.726 26.1631 25.8838 25.8472 26.0198 26.2699 26.5387 26.8041 27.0539 27.2764 27.4596 27.592 27.6607 27.6574 27.5703 27.3882 27.1085 26.7469 26.3385 25.9327 25.6089 25.5098 25.9191 27.5141 32.9064 63.4664 89.8944 40.5641 31.315 28.2704 27.0125 26.376 26.1644 26.3471 26.696 27.1041 27.5225 27.9248 28.2926 28.6089 28.857 29.0228 29.0948 29.07 28.9449 28.7163 28.383 27.9599 27.4816 27.0004 26.5943 26.4004 26.6855 28.1038 33.2462 63.0176 89.2347 39.7921 31.2187 28.4216 27.0714 26.5906 26.7346 27.1591 27.7118 28.3187 28.9333 29.5213 30.0543 30.5064 30.8524 31.0705 31.1497 31.0905 30.9017 30.5929 30.1705 29.6512 29.0688 28.4766 27.9531 27.6348 27.7816 29.0477 33.9953 64.2318 88.8392 39.0843 31.0504 28.1232 27.1599 27.1868 27.6358 28.3162 29.1221 29.9897 30.867 31.7082 32.4725 33.1198 33.6088 33.902 33.9853 33.8658 33.5688 33.1264 32.5614 31.8967 31.1665 30.4234 29.7475 29.2776 29.279 30.4294 35.3794 67.3646 81.401 37.0987 29.9886 28.0197 27.6964 28.1595 28.9525 29.9336 31.0462 32.2417 33.4593 34.6412 35.7262 36.6513 37.3471 37.7454 37.8167 37.5842 37.1044 36.4461 35.6612 34.7849 33.8528 32.914 32.0475 31.3963 31.2447 32.3147 37.424 71.7838 62.7812 33.9578 29.2191 28.3481 28.7709 29.7096 30.8669 32.1835 33.6529 35.2383 36.8858 38.5134 40.0346 41.3574 42.3636 42.9062 42.9208 42.4699 41.6815 40.6856 39.5753 38.4031 37.2043 36.0207 34.9256 34.0626 33.7396 34.7327 40.0761 77.0469 49.4122 31.8911 29.1365 29.4109 30.6588 32.1001 33.5853 35.2455 37.1135 39.1701 41.3453 43.5334 45.6219 47.4995 48.9837 49.7641 49.622 48.7402 47.4486 45.9467 44.3798 42.8144 41.2793 39.804 38.4508 37.3546 36.8342 37.7351 43.3184 83.3834 50.4132 31.9767 30.2738 31.7273 33.6691 35.3854 37.1787 39.2422 41.6 44.2212 47.0291 49.8896 52.6623 55.2399 57.3975 58.5807 58.203 56.5572 54.4509 52.2493 50.0875 48.0342 46.0993 44.2955 42.6757 41.3541 40.619 41.4008 47.2442 91.1276 57.5117 34.3871 33.4602 35.6127 37.5978 39.5225 41.7031 44.2869 47.2504 50.5464 54.1016 57.7396 61.2964 64.6421 67.4074 69.0289 68.5535 65.8639 62.5698 59.4943 56.6329 54.0266 51.6506 49.4991 47.6293 46.1315 45.2137 45.9326 52.1963 101.222 72.4313 40.98 39.38 40.5353 42.2711 44.4724 47.2185 50.4989 54.2099 58.2939 62.7042 67.2358 71.7975 76.1543 79.2896 80.4418 79.676 75.9108 71.5113 67.4931 63.9127 60.7348 57.9228 55.4237 53.3467 51.7 50.7751 51.7297 58.9036 114.944 93.8433 52.0181 46.224 45.8643 47.6362 50.3747 53.9372 58.1032 62.7346 67.6962 72.9712 78.5635 84.6704 90.8367 94.2095 93.1318 90.4732 85.9671 81.0538 76.1963 71.8994 68.13 64.8873 62.0981 59.9237 58.2538 57.5612 59.3722 68.8029 139.155 127.201 63.1243 52.4478 51.6835 53.8642 57.4429 62.1247 67.4784 73.2875 79.2601 85.3817 92.2167 100.492 108.947 111.26 107.167 101.962 97.1298 91.5999 85.9284 80.775 76.2993 72.5842 69.5971 67.398 66.2406 66.0135 69.1368 82.2133 166.773 148.134 69.6315 58.4143 58.1491 60.9837 65.7985 72.0043 79.0398 86.5294 93.9422 101.206 109.059 119.215 128.983 128.574 123.257 116.197 110.474 103.798 97.1413 90.8981 85.5408 81.2803 77.954 75.4247 75.2458 76.3002 79.9085 98.2422 215.046 163.21 76.7441 65.5997 65.2487 69.0142 75.4948 83.6771 93.0404 103.106 113.031 121.889 129.81 139.961 148.71 146.446 143.185 134.401 125.669 117.811 109.999 102.62 96.1534 91.088 86.9828 83.8243 83.3382 85.9062 91.6764 115.642 271.053 175.208 83.4159 72.5665 72.6247 77.974 86.4289 96.9477 109.497 123.54 137.747 149.187 155.15 161.679 166.961 164.923 166.017 154.85 143.379 134.079 125.072 116.372 108.554 102.205 97.0188 92.91 90.622 91.3524 98.0202 121.412 267.399 170.774 87.687 78.6695 80.6499 87.7826 98.1372 111.208 127.789 147.788 170.1 185.561 187.641 185.166 185.198 183.151 185.337 175.141 164.214 153.803 143.099 132.591 123.131 115.139 108.581 103.656 99.4861 97.3881 101.177 125.117 254.031 169.602 93.8679 86.5131 90.0996 98.737 110.403 126.074 146.687 173.862 203.356 225.272 225.189 210.444 204.759 202.498 199.772 195.578 189.812 178.011 164.617 151.31 139.816 130.164 122.63 116.254 110.464 105.699 104.992 119.721 223.143 188.266 107.485 97.2576 101.16 110.925 124.217 142.619 164.809 192.549 226.311 248.626 254.023 231.006 220.869 217.521 212.526 214.058 217.934 207.304 189.56 171.796 157.052 145.465 137.18 129.601 122.848 117.492 113.119 119.262 182.482 247.643 127.851 112.504 114.921 124.579 138.596 155.383 175.535 202.17 232.313 249.233 255.332 240.918 228.256 225.104 222.911 230.457 244.785 238.363 216.331 193.363 172.869 159.017 147.693 139.492 133.837 130.264 125.177 117.577 139.765 302.763 149.103 126.225 125.506 133.615 147.339 164.944 184.043 207.746 234.696 246.818 246.881 242.091 231.331 227.867 229.299 239.213 251.729 255.661 234.905 209.341 186.335 166.445 151.85 140.735 133.424 129.884 125.642 119.347 140.682 301.591 148.366 127.214 127.303 136.06 149.896 166.374 185.354 210.221 235.875 243.068 238.451 237.25 235.534 232.776 234.486 239.757 246.972 253.043 240.362 215.753 191.07 171.004 155.493 142.006 131.975 125.788 122.817 125.709 201.4 286.537 145.131 125.897 127.094 136.225 150.013 165.787 185.23 210.509 232.357 235.777 231.36 231.03 234.102 235.768 235.846 236.054 240.443 247.765 241.653 218.816 193.245 173.485 158.219 144.198 132.806 125.496 123.351 134.799 271.143 277.572 143.667 125.375 127.404 136.989 150.614 165.842 185.861 210.199 226.293 226.224 223.188 223.558 226.794 229.809 230.248 230.132 234.793 244.083 245.172 224.615 196.962 175.595 159.959 146.265 134.736 127.105 125.685 141.91 289.667 274.233 143.572 126.1 128.956 139.223 152.526 167.59 188.444 211.121 220.441 216.839 213.812 213.811 215.794 218.424 220.361 222.846 229.533 241.146 248.008 231.88 202.502 178.31 161.132 147.346 136.017 128.342 126.501 142.434 276.54 277.512 144.573 128.277 131.999 143.147 156.014 171.613 193.462 213.1 214.933 208.371 204.485 203.551 204.472 206.774 210.054 215.028 223.89 237.349 248.441 238.642 208.88 181.87 162.714 147.803 136.007 128.172 125.732 140.239 258.114 287.152 147.424 131.979 136.361 148.282 161.229 178.164 200.784 214.48 209.156 200.648 195.891 194.173 194.471 196.628 200.722 207.253 217.483 231.977 246.175 243.52 215.496 186.304 165.222 148.564 135.646 127.257 124.335 137.496 238.987 299.253 151.787 136.838 141.691 154.037 167.834 187.148 209.39 213.787 203.003 193.49 188.165 185.982 186.031 188.177 192.61 199.768 210.438 225.134 241.393 245.952 221.957 191.513 168.731 150.577 136.436 127.298 124.173 136.205 226.477 308.791 157.249 142.409 147.579 160.237 175.561 198.047 217.009 210.858 196.815 186.873 181.247 178.84 178.838 181.035 185.533 192.702 203.149 217.478 234.85 245.706 227.938 197.28 173.252 154.162 139.313 130.049 127.418 141.138 236.669 315.988 163.154 148.293 153.83 166.772 184.507 210.042 220.836 206.3 190.809 180.756 175.013 172.527 172.555 174.82 179.28 186.165 196.021 209.589 227.179 242.993 233.281 203.378 178.505 158.949 144.093 135.545 134.73 154.902 286.55 325.67 169.278 154.225 160.012 173.409 194.469 221.021 219.96 200.706 184.955 175.018 169.308 166.855 166.954 169.29 173.686 180.213 189.328 201.877 218.807 237.607 237.347 209.515 184.019 164.382 149.862 142.046 142.935 165.359 349.087 340.953 175.972 160.162 165.851 179.858 204.005 226.937 215.576 194.38 179.113 169.51 163.987 161.667 161.87 164.265 168.594 174.774 183.145 194.539 210.16 229.943 238.833 215.279 189.372 169.794 155.598 147.714 146.756 165.853 325.691 362.115 183.245 166.177 171.326 186.225 212.802 226.314 208.1 187.362 173.136 164.089 158.915 156.814 157.142 159.563 163.788 169.644 177.345 187.568 201.456 220.287 236.012 220.563 194.565 174.857 160.655 151.12 148.109 163.644 315.88 385.654 190.769 172.371 176.735 193.126 219.561 220.139 198.948 179.894 166.972 158.648 153.942 152.12 152.583 154.986 159.04 164.551 171.652 180.801 192.851 209.535 228.064 224.567 200.123 179.612 164.442 153.365 147.343 159.928 297.883 408.725 199.002 178.664 182.006 199.969 220.39 210.395 189.12 172.171 160.615 153.092 148.91 147.393 147.973 150.306 154.11 159.223 165.739 173.929 184.304 198.388 216.143 223.677 205.291 183.863 167.517 155.273 146.91 156.042 268.939 430.612 207.917 184.926 187.226 205.86 214.647 198.628 179.177 164.33 154.074 147.351 143.677 142.446 143.106 145.301 148.777 153.414 159.301 166.618 175.626 187.289 202.045 214.187 207.711 188.014 170.549 157.811 150.155 160.073 260.092 451.411 216.489 189.583 191.116 207.078 203.871 186.353 169.374 156.458 147.39 141.415 138.153 137.144 137.814 139.812 142.904 147.008 152.228 158.755 166.744 176.564 188.081 199.084 202.554 190.662 174.301 161.723 156.102 168.904 284.366 460.297 221.76 191.212 192.244 201.628 191.28 174.396 159.775 148.614 140.616 135.332 132.349 131.43 132.027 133.786 136.48 140.043 144.636 150.512 157.758 166.336 175.576 184.061 189.501 188.255 177.806 166.598 162.994 181.149 331.818 437.472 219.008 190.067 191.752 192.821 178.528 162.986 150.443 140.877 133.865 129.146 126.376 125.397 125.837 127.327 129.634 132.71 136.808 142.165 148.805 156.417 164.124 170.885 175.725 177.978 176.976 171.375 169.493 192.834 380.631 410.383 213.139 186.769 189.572 182.558 166.192 152.208 141.496 133.35 127.249 123 120.437 119.297 119.496 120.683 122.635 125.336 129.079 133.954 139.96 146.595 153.019 158.583 162.875 165.943 168.594 171.097 175.012 202.236 415.921 390.036 206.191 181.8 184.197 170.592 154.373 142.146 133.027 126.101 120.824 117.005 114.627 113.413 113.298 114.167 115.8 118.232 121.638 125.996 131.258 136.846 142.104 146.706 150.554 154.005 158.235 164.754 175.52 204.43 446.955 389.909 199.209 176.198 173.349 157.29 143.11 132.697 124.948 119.06 114.53 111.154 108.918 107.775 107.455 108.003 109.348 111.53 114.479 118.259 122.689 127.249 131.528 135.428 139.03 142.813 148.03 156.436 169.548 201.054 455.019 397.75 190.747 171.008 158.993 144.132 132.293 123.535 116.993 112.017 108.177 105.274 103.249 102.112 101.763 102.11 103.198 105.015 107.475 110.627 114.218 117.881 121.413 124.846 128.372 132.533 138.519 147.957 161.399 191.786 439.311 394.597 183.048 159.676 144.533 131.435 121.629 114.398 108.974 104.828 101.625 99.1933 97.4394 96.3335 95.8832 96.0756 96.9496 98.4541 100.511 103.053 105.898 108.84 111.804 114.884 118.327 122.681 128.987 138.61 151.259 178.533 402.993 334.247 170.218 144.274 129.794 118.972 111.126 105.33 100.939 97.5527 94.9318 92.9328 91.4583 90.4624 89.9649 90.0277 90.7153 91.9626 93.643 95.6526 97.8911 100.26 102.751 105.479 108.693 112.88 118.923 127.801 138.523 162.412 358.481 291.892 152.366 128.034 115.659 107.202 101.12 96.584 93.1028 90.3939 88.2941 86.6864 85.4803 84.6417 84.1879 84.1868 84.713 85.7063 87.0318 88.5996 90.3555 92.2598 94.328 96.6659 99.4859 103.195 108.504 115.92 124.414 144.789 310.622 274.686 137.055 113.81 103.309 96.6356 91.9173 88.3951 85.6779 83.557 81.9134 80.6525 79.7007 79.033 78.6637 78.6444 79.0393 79.7986 80.8134 82.0194 83.3866 84.9033 86.5884 88.5204 90.8659 93.9496 98.2934 104.069 110.659 127.75 264.355 252.1 123.716 101.893 92.765 87.34 83.6255 80.891 78.7956 77.1654 75.9034 74.9381 74.2148 73.7109 73.4338 73.4173 73.7117 74.2768 75.0366 75.9504 77.0019 78.1898 79.5299 81.077 82.9591 85.4245 88.8202 93.2171 98.6069 113.264 226.96 229.529 111.728 91.6252 83.6556 79.1775 76.2174 74.0895 72.4849 71.249 70.2993 69.5795 69.0493 68.6896 68.4983 68.4953 68.7184 69.133 69.6915 70.3723 71.1672 72.0775 73.1167 74.327 75.8103 77.7532 80.3839 83.8064 88.6041 102.158 202.571 206.696 100.804 82.6743 75.7201 71.984 69.603 67.9408 66.7179 65.7945 65.0963 64.5769 64.2044 63.963 63.8433 63.8584 64.0363 64.3409 64.7446 65.2416 65.8294 66.511 67.2994 68.2333 69.3993 70.9411 73.0211 75.8176 80.3296 93.6268 187.938 186.148 91.094 74.8352 68.7523 65.61 63.6801 62.3769 61.4502 60.7721 60.2741 59.9153 59.6693 59.5209 59.4551 59.4871 59.6403 59.8694 60.1574 60.5114 60.9344 61.4319 62.0193 62.7347 63.6564 64.8991 66.6005 69.0094 73.3392 86.476 177.259 168.607 82.6051 67.9567 62.6045 59.9365 58.3591 57.3362 56.6384 56.15 55.8083 55.5756 55.4283 55.3501 55.322 55.3666 55.5079 55.688 55.8922 56.1371 56.4314 56.7841 57.2136 57.7588 58.4902 59.5063 60.9447 63.1098 67.2636 79.9205 165.945 153.376 75.2332 61.93 57.1672 54.8707 53.5707 52.7671 52.2454 51.9007 51.6764 51.5383 51.464 51.4341 51.4299 51.484 51.6196 51.7689 51.9144 52.0785 52.2749 52.5163 52.8232 53.235 53.8135 54.6497 55.8895 57.8729 61.8107 73.6435 152.89 140.536 68.8436 56.6451 52.3494 50.3431 49.2596 48.6244 48.2365 47.9985 47.8586 47.7854 47.7571 47.7532 47.7619 47.8245 47.9582 48.0892 48.1953 48.3017 48.4262 48.5839 48.7971 49.102 49.5531 50.2363 51.3069 53.1244 56.8107 67.6289 139.04 129.566 63.2951 52.0028 48.0784 46.2959 45.3756 44.8667 44.5772 44.4158 44.3333 44.2994 44.2919 44.292 44.3028 44.3724 44.5071 44.6297 44.712 44.7797 44.8538 44.9505 45.0924 45.311 45.6535 46.2008 47.1127 48.7586 52.1815 62.0464 126.014 120.107 58.4371 47.9081 44.282 42.6709 41.8709 41.4528 41.2329 41.1232 41.0761 41.061 41.0544 41.0412 41.0433 41.1156 41.2526 41.3747 41.4462 41.4913 41.5324 41.5868 41.6754 41.8251 42.0763 42.5042 43.2671 44.7372 47.9131 57.0399 115.066 111.693 54.1165 44.2644 40.8882 39.4109 38.698 38.3425 38.1684 38.0901 38.0602 38.048 38.0294 37.9931 37.9788 38.0469 38.1853 38.3125 38.3835 38.4185 38.4409 38.4684 38.5195 38.6165 38.7945 39.1226 39.7545 41.0537 43.9954 52.5718 106.218 103.984 50.2188 40.9892 37.8314 36.4619 35.8128 35.4988 35.3514 35.2874 35.2602 35.2382 35.1988 35.1365 35.1038 35.1627 35.2994 35.4341 35.5121 35.5467 35.5618 35.575 35.6022 35.662 35.7848 36.034 36.5559 37.7003 40.4145 48.4961 98.4584 96.7993 46.6479 38.0118 35.0553 33.7774 33.1765 32.8889 32.754 32.6915 32.6558 32.6145 32.5466 32.4598 32.4129 32.461 32.592 32.7331 32.8229 32.8644 32.8808 32.8896 32.9042 32.9401 33.0226 33.2098 33.6405 34.6497 37.1468 44.7418 91.3234 90.0081 43.3357 35.2777 32.5139 31.3185 30.7561 30.4852 30.3532 30.283 30.2305 30.1637 30.0668 29.9608 29.9047 29.9421 30.0629 30.2065 30.3097 30.3627 30.3867 30.3982 30.4084 30.4292 30.482 30.6201 30.9756 31.8664 34.1571 41.2684 84.7369 83.5559 40.2373 32.7464 30.1714 29.0538 28.5246 28.2646 28.1299 28.0467 27.973 27.8794 27.7578 27.642 27.5821 27.6089 27.7146 27.8544 27.9688 28.0354 28.0701 28.0881 28.0981 28.109 28.1394 28.2389 28.5321 29.3183 31.4147 38.052 78.7256 77.4343 37.3292 30.3912 28.0012 26.959 26.4603 26.2084 26.0681 25.9696 25.8737 25.7579 25.6242 25.5089 25.45 25.4666 25.5533 25.6802 25.7986 25.8775 25.9227 25.9474 25.958 25.9609 25.9735 26.0415 26.281 26.9732 28.8838 35.0312 72.7617 71.6291 34.6015 28.1947 25.9838 25.0153 24.5463 24.3013 24.1545 24.041 23.9262 23.7978 23.668 23.5644 23.5112 23.519 23.5841 23.6885 23.7991 23.8844 23.9365 23.9646 23.9733 23.9679 23.9644 24.0043 24.1949 24.7984 26.5251 32.1563 66.6646 66.1353 32.0411 26.1419 24.1043 23.2086 22.7689 22.5307 22.3776 22.251 22.1254 21.9991 21.8862 21.8035 21.7611 21.7622 21.8056 21.8813 21.9709 22.0504 22.1027 22.1284 22.1308 22.1145 22.0939 22.1072 22.2507 22.7671 24.309 29.4109 60.6651 60.8959 29.6287 24.219 22.351 21.5272 21.1164 20.8845 20.7259 20.5921 20.467 20.3553 20.2681 20.2119 20.1843 20.1825 20.2056 20.2513 20.3103 20.3695 20.4111 20.4255 20.4159 20.3856 20.3475 20.3353 20.4345 20.8672 22.2289 26.812 54.9551 55.9254 27.3534 22.4169 20.7143 19.9601 19.576 19.35 19.1897 19.0571 18.9435 18.8539 18.7951 18.7665 18.7562 18.7551 18.7626 18.7799 18.8058 18.8339 18.8494 18.8434 18.8161 18.7697 18.7148 18.6797 18.7393 19.095 20.2879 24.3825 49.6751 51.3054 25.2213 20.7321 19.1854 18.4946 18.1346 17.9159 17.7603 17.6388 17.5444 17.4793 17.447 17.4425 17.4479 17.4512 17.4486 17.443 17.4373 17.429 17.4097 17.3764 17.3266 17.2615 17.1907 17.1364 17.1619 17.45 18.4912 22.1441 44.8657 46.959 23.2282 19.1576 17.7524 17.1172 16.78 16.5734 16.4318 16.3296 16.2587 16.2176 16.2058 16.2122 16.2234 16.2296 16.2233 16.2042 16.1752 16.137 16.0866 16.0242 15.9491 15.8632 15.7757 15.705 15.702 15.9326 16.8433 20.1132 40.5612 42.8798 21.368 17.6853 16.403 15.8165 15.5045 15.3183 15.1992 15.1223 15.0769 15.0582 15.0579 15.0642 15.0727 15.0764 15.069 15.0455 15.0055 14.9484 14.8745 14.7862 14.6861 14.5784 14.4734 14.3875 14.3615 14.5438 15.3442 18.2809 36.6519 39.0721 19.6798 16.3145 15.1297 14.5883 14.307 14.1492 14.059 14.0106 13.9909 13.9907 13.9943 13.9981 14.0015 14.0009 13.991 13.9657 13.9205 13.8533 13.7648 13.6578 13.5368 13.4088 13.286 13.1856 13.1418 13.2855 13.9948 16.6573 33.3343 35.5117 18.1101 15.025 13.9286 13.4354 13.1913 13.0672 13.0086 12.989 12.9933 13.0041 13.0092 13.0094 13.0074 13.0019 12.9887 12.9614 12.9141 12.8434 12.7486 12.6313 12.4963 12.3517 12.2124 12.0986 12.0413 12.154 12.795 15.2401 30.6855 32.2024 16.6387 13.8025 12.7989 12.3632 12.1616 12.0728 12.0451 12.0516 12.0747 12.0913 12.0966 12.094 12.0878 12.0784 12.0622 12.0329 11.9847 11.9135 11.8177 11.6976 11.5559 11.4 11.2466 11.1206 11.0527 11.1427 11.7356 14.0138 28.5705 29.0642 15.2319 12.6381 11.7436 11.3751 11.2186 11.1639 11.1646 11.1934 11.2261 11.2461 11.2518 11.2474 11.2389 11.228 11.2106 11.1803 11.1315 11.061 10.967 10.8484 10.7053 10.5431 10.379 10.2427 10.1652 10.2337 10.7887 12.9763 26.9177 25.7461 13.9132 11.5447 10.7703 10.4721 10.3591 10.3342 10.3579 10.403 10.4415 10.4642 10.4706 10.4659 10.4575 10.4481 10.4324 10.4029 10.3545 10.2851 10.1934 10.0771 9.93399 9.76826 9.59823 9.45449 9.36564 9.40491 9.91788 12.0571 25.2409 22.3438 12.5884 10.5239 9.88096 9.65127 9.57627 9.57442 9.61347 9.6679 9.71347 9.7407 9.74929 9.74582 9.74033 9.73596 9.7248 9.69768 9.65039 9.5823 9.49226 9.37664 9.23193 9.0643 8.89416 8.74832 8.64946 8.66209 9.12692 11.197 23.1107 19.1253 11.2613 9.57532 9.07081 8.90531 8.86211 8.87723 8.92689 8.98813 9.03922 9.07058 9.0828 9.08294 9.08308 9.08622 9.08137 9.05777 9.01193 8.94486 8.85542 8.7381 8.59017 8.42291 8.25882 8.11844 8.01755 8.01615 8.44402 10.449 21.3871 16.4705 10.0303 8.7115 8.33723 8.22836 8.21115 8.23985 8.29861 8.3647 8.41835 8.45171 8.4671 8.4722 8.47908 8.49032 8.49226 8.47312 8.42972 8.36401 8.27411 8.15316 8.00206 7.83835 7.68499 7.55741 7.46673 7.46327 7.84668 9.75869 19.9 14.537 9.00413 7.95496 7.68324 7.61853 7.62133 7.66136 7.72715 7.79617 7.8499 7.88316 7.90006 7.90899 7.92135 7.93937 7.94822 7.93525 7.89667 7.83266 7.74009 7.6143 7.46227 7.30564 7.16597 7.05608 6.98604 6.99351 7.32515 9.12493 18.494 13.2877 8.23458 7.32433 7.11384 7.07578 7.09138 7.13958 7.20912 7.2785 7.33059 7.36236 7.37916 7.3894 7.40475 7.42787 7.44435 7.43919 7.40542 7.34048 7.24317 7.11415 6.96522 6.8182 6.69252 6.60065 6.5536 6.5807 6.86421 8.51143 17.0984 12.5455 7.71322 6.82562 6.63271 6.59988 6.61835 6.66903 6.73827 6.80507 6.85455 6.88477 6.90043 6.90995 6.92689 6.95502 6.97883 6.97819 6.94461 6.87623 6.77562 6.64741 6.50511 6.36819 6.25388 6.17482 6.14427 6.19261 6.45268 7.9212 15.6926 12.0474 7.39412 6.45792 6.24632 6.19258 6.19887 6.2426 6.30644 6.36796 6.41426 6.44324 6.45763 6.46713 6.48753 6.5212 6.54744 6.54401 6.50619 6.43485 6.33432 6.21071 6.07666 5.94846 5.84122 5.76797 5.74554 5.81054 6.07152 7.34066 14.3749 11.6064 7.21461 6.23355 5.96113 5.85436 5.83067 5.85634 5.90713 5.96014 6.00274 6.03071 6.04541 6.05858 6.08558 6.12169 6.1423 6.13163 6.08956 6.01768 5.91993 5.80267 5.67683 5.5557 5.45214 5.3795 5.35868 5.43236 5.70124 6.7849 13.2197 11.1933 7.23895 6.17414 5.76363 5.57631 5.50949 5.50876 5.53849 5.57979 5.61762 5.64487 5.6627 5.68341 5.71598 5.74757 5.75801 5.74139 5.69709 5.62624 5.5325 5.42199 5.3038 5.18879 5.08808 5.0148 4.99185 5.06583 5.34188 6.3024 12.2823 10.5331 7.39729 6.16686 5.59945 5.33372 5.22466 5.19423 5.20298 5.23045 5.26226 5.28899 5.31204 5.33964 5.37097 5.39258 5.39441 5.37396 5.32854 5.25968 5.17063 5.06683 4.9558 4.84649 4.7489 4.67621 4.65174 4.72214 4.99917 5.90378 11.5667 9.45531 7.35904 6.05702 5.40386 5.10033 4.96315 4.91034 4.90195 4.91696 4.94197 4.96775 4.99399 5.02144 5.04477 5.0569 5.05283 5.02922 4.98363 4.91741 4.83329 4.73593 4.63167 4.52807 4.43435 4.36367 4.33917 4.40537 4.67415 5.54074 11.0616 8.6577 6.88096 5.81724 5.18819 4.8747 4.72299 4.65687 4.63662 4.64135 4.65834 4.68023 4.70264 4.72272 4.73716 4.74206 4.73326 4.70712 4.66195 4.59859 4.51931 4.42807 4.33027 4.23257 4.14363 4.07641 4.05334 4.11628 4.3743 5.23191 10.7723 8.82744 6.31741 5.60549 5.02457 4.69205 4.52016 4.43808 4.40519 4.39878 4.40548 4.41771 4.43058 4.44184 4.44892 4.4479 4.43509 4.40702 4.36254 4.30203 4.22737 4.14193 4.05038 3.95876 3.87533 3.81272 3.79259 3.85448 4.10612 4.97385 10.6012 8.98386 5.87184 5.37415 4.87462 4.54484 4.35079 4.24716 4.19829 4.17804 4.17168 4.17176 4.17468 4.17836 4.17915 4.17332 4.15711 4.12775 4.0841 4.02634 3.95606 3.87611 3.79063 3.70518 3.62772 3.57051 3.55451 3.61767 3.86807 4.74826 10.4404 8.46801 5.37799 4.9989 4.63715 4.35984 4.17307 4.06077 3.99996 3.96683 3.94811 3.93814 3.93347 3.93087 3.92655 3.91673 3.89797 3.86781 3.82512 3.77002 3.70385 3.6291 3.54948 3.47021 3.39891 3.34748 3.3363 3.40225 3.6544 4.54129 10.2224 7.66639 4.97193 4.57665 4.31078 4.11023 3.96298 3.86305 3.79946 3.7581 3.73157 3.71522 3.70518 3.6979 3.68968 3.67687 3.65627 3.62565 3.58402 3.53148 3.46918 3.39934 3.32534 3.25212 3.18701 3.14146 3.13531 3.20471 3.45915 4.34381 9.93321 7.18182 4.57794 4.14796 3.95545 3.83011 3.73099 3.65292 3.594 3.55118 3.52166 3.50206 3.4888 3.47844 3.46747 3.45249 3.43059 3.39982 3.35934 3.30925 3.25058 3.18533 3.11669 3.04934 2.9903 2.95059 2.94946 3.02238 3.27807 4.15192 9.58721 7.1459 4.16514 3.75293 3.62172 3.55379 3.49416 3.43707 3.38734 3.34793 3.31901 3.29863 3.28392 3.27179 3.25904 3.24255 3.21978 3.1891 3.14982 3.10206 3.04677 2.98585 2.92228 2.86056 2.80739 2.77336 2.77697 2.85325 3.10857 3.96512 9.21077 7.33821 3.88228 3.43999 3.33501 3.29797 3.26428 3.22449 3.18483 3.15106 3.12497 3.10552 3.09062 3.07768 3.06384 3.04636 3.02309 2.99269 2.9546 2.90902 2.85688 2.79999 2.74121 2.6848 2.63717 2.60849 2.61641 2.6956 2.94881 3.78278 8.81781 7.16775 3.65591 3.18742 3.08791 3.06452 3.04726 3.02127 2.99104 2.96346 2.94119 2.92373 2.90949 2.89637 2.88195 2.86389 2.84036 2.81032 2.77337 2.7298 2.68056 2.6274 2.57305 2.52155 2.479 2.45518 2.46687 2.54823 2.79788 3.60571 8.42291 6.65045 3.39555 2.95412 2.86604 2.85145 2.84491 2.83025 2.809 2.78773 2.76969 2.75482 2.74184 2.72901 2.71439 2.69601 2.67235 2.64266 2.60675 2.56497 2.51832 2.46849 2.41808 2.37092 2.33282 2.31312 2.32785 2.41042 2.65523 3.43482 8.03119 6.0745 3.12435 2.73195 2.66059 2.65536 2.65784 2.65357 2.64158 2.62696 2.61347 2.60156 2.59023 2.57806 2.5635 2.54494 2.5212 2.49179 2.45672 2.41643 2.37195 2.3249 2.27775 2.23412 2.1995 2.18284 2.19943 2.28176 2.52012 3.27069 7.65871 5.42917 2.85423 2.52125 2.47033 2.47688 2.48979 2.49615 2.4938 2.48632 2.47763 2.46882 2.45929 2.44794 2.43354 2.41486 2.39104 2.3618 2.32733 2.28814 2.24525 2.20025 2.15544 2.11423 2.08179 2.0666 2.08326 2.16307 2.39247 3.11168 7.29767 4.80274 2.60344 2.33561 2.30805 2.32804 2.35208 2.36867 2.37523 2.37464 2.37064 2.36474 2.35686 2.34626 2.33199 2.31317 2.28922 2.26002 2.22584 2.18728 2.14533 2.10148 2.05792 2.01781 1.98598 1.97035 1.98478 2.05904 2.27608 2.96397 6.9773 4.36952 2.43759 2.21438 2.20358 2.23358 2.26571 2.28937 2.30213 2.30651 2.30592 2.30214 2.29541 2.28529 2.27108 2.25212 2.22802 2.19875 2.16461 2.12623 2.08456 2.04104 1.9977 1.95751 1.92498 1.90742 1.91772 1.98318 2.18081 2.81981 6.6827 ) ; boundaryField { inlet { type fixedValue; value uniform 10; } outlet { type inletOutlet; phi phi.air; inletValue uniform 10; value nonuniform List<scalar> 30 ( 4.36952 2.43759 2.21438 2.20358 2.23358 2.26571 2.28937 2.30213 2.30651 2.30592 2.30214 2.29541 2.28529 2.27108 2.25212 2.22802 2.19875 2.16461 2.12623 2.08456 2.04104 1.9977 1.95751 1.92498 1.90742 1.91772 1.98318 2.18081 2.81981 6.6827 ) ; } walls { type epsilonWallFunction; value nonuniform List<scalar> 400 ( 119.206 68.9648 42.9079 34.6759 28.5054 22.77 17.7104 14.1913 14.7063 18.8479 29.3967 40.3737 45.5048 48.478 49.7917 50.1303 50.5238 53.445 51.5682 46.6198 38.5135 32.2263 31.1394 30.9643 29.4002 25.1182 19.389 14.9318 12.7148 11.6685 11.6781 12.5315 15.567 21.8619 34.7239 50.2747 62.4076 68.3516 70.1046 70.4826 69.5105 68.2061 68.3802 69.8714 69.7381 67.1609 70.1559 71.3923 67.7275 60.538 53.4007 47.6934 43.962 40.7059 37.3416 32.1073 24.9806 17.1329 11.0712 8.09176 7.93829 8.90359 11.6352 15.0621 18.3096 20.6469 21.1308 21.3538 22.3852 24.8629 28.6641 33.0871 37.902 42.9987 48.3239 53.8464 59.5522 65.4388 71.476 77.5234 83.5055 89.8376 95.5458 100.291 105.461 110.764 111.045 105.174 91.6547 82.181 79.1988 77.2737 75.0184 72.1025 67.4114 63.7016 63.2972 64.2403 68.1365 77.4268 86.5512 91.1424 92.2655 89.8944 89.2347 88.8392 81.401 62.7812 49.4122 50.4132 57.5117 72.4313 93.8433 127.201 148.134 163.21 175.208 170.774 169.602 188.266 247.643 302.763 301.591 286.537 277.572 274.233 277.512 287.152 299.253 308.791 315.988 325.67 340.953 362.115 385.654 408.725 430.612 451.411 460.297 437.472 410.383 390.036 389.909 397.75 394.597 334.247 291.892 274.686 252.1 229.529 206.696 186.148 168.607 153.376 140.536 129.566 120.107 111.693 103.984 96.7993 90.0081 83.5559 77.4343 71.6291 66.1353 60.8959 55.9254 51.3054 46.959 42.8798 39.0721 35.5117 32.2024 29.0642 25.7461 22.3438 19.1253 16.4705 14.537 13.2877 12.5455 12.0474 11.6064 11.1933 10.5331 9.45531 8.6577 8.82744 8.98386 8.46801 7.66639 7.18182 7.1459 7.33821 7.16775 6.65045 6.0745 5.42917 4.80274 4.36952 119.038 71.2405 45.0584 36.3157 32.5144 28.0823 21.4854 15.8497 14.5044 16.7639 20.6133 19.7693 17.7965 14.0365 10.0857 7.88492 7.66505 8.16866 9.59338 10.9783 12.2375 13.5619 15.108 17.0004 19.4224 22.7377 27.1533 37.0292 51.8661 80.6344 107.171 105.601 102.078 105.217 113.851 119.665 120.968 120.316 118.486 115.87 113.356 110.984 108.64 106.231 103.694 100.686 97.439 93.4219 88.6645 83.4513 77.5502 70.9549 64.0796 57.1887 50.4313 43.9578 37.9103 32.3261 27.414 23.1949 19.5831 16.6989 14.1335 11.2085 8.30028 6.43183 5.00793 4.11864 4.29586 6.15122 11.8637 19.3828 24.4476 25.3999 26.4888 28.2608 28.3156 26.9067 25.9403 27.4364 32.6284 38.6308 44.0534 49.2857 53.0937 55.3895 57.4134 60.3592 63.4424 65.6933 67.7261 69.0161 68.8927 67.6351 66.6698 66.9119 67.6401 70.0542 72.6389 72.4807 71.2628 67.6489 63.4664 63.0176 64.2318 67.3646 71.7838 77.0469 83.3834 91.1276 101.222 114.944 139.155 166.773 215.046 271.053 267.399 254.031 223.143 182.482 139.765 140.682 201.4 271.143 289.667 276.54 258.114 238.987 226.477 236.669 286.55 349.087 325.691 315.88 297.883 268.939 260.092 284.366 331.818 380.631 415.921 446.955 455.019 439.311 402.993 358.481 310.622 264.355 226.96 202.571 187.938 177.259 165.945 152.89 139.04 126.014 115.066 106.218 98.4584 91.3234 84.7369 78.7256 72.7617 66.6646 60.6651 54.9551 49.6751 44.8657 40.5612 36.6519 33.3343 30.6855 28.5705 26.9177 25.2409 23.1107 21.3871 19.9 18.494 17.0984 15.6926 14.3749 13.2197 12.2823 11.5667 11.0616 10.7723 10.6012 10.4404 10.2224 9.93321 9.58721 9.21077 8.81781 8.42291 8.03119 7.65871 7.29767 6.9773 6.6827 ) ; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 400 ( 119.206 68.9648 42.9079 34.6759 28.5054 22.77 17.7104 14.1913 14.7063 18.8479 29.3967 40.3737 45.5048 48.478 49.7917 50.1303 50.5238 53.445 51.5682 46.6198 38.5135 32.2263 31.1394 30.9643 29.4002 25.1182 19.389 14.9318 12.7148 11.6685 11.6781 12.5315 15.567 21.8619 34.7239 50.2747 62.4076 68.3516 70.1046 70.4826 69.5105 68.2061 68.3802 69.8714 69.7381 67.1609 70.1559 71.3923 67.7275 60.538 53.4007 47.6934 43.962 40.7059 37.3416 32.1073 24.9806 17.1329 11.0712 8.09176 7.93829 8.90359 11.6352 15.0621 18.3096 20.6469 21.1308 21.3538 22.3852 24.8629 28.6641 33.0871 37.902 42.9987 48.3239 53.8464 59.5522 65.4388 71.476 77.5234 83.5055 89.8376 95.5458 100.291 105.461 110.764 111.045 105.174 91.6547 82.181 79.1988 77.2737 75.0184 72.1025 67.4114 63.7016 63.2972 64.2403 68.1365 77.4268 86.5512 91.1424 92.2655 89.8944 89.2347 88.8392 81.401 62.7812 49.4122 50.4132 57.5117 72.4313 93.8433 127.201 148.134 163.21 175.208 170.774 169.602 188.266 247.643 302.763 301.591 286.537 277.572 274.233 277.512 287.152 299.253 308.791 315.988 325.67 340.953 362.115 385.654 408.725 430.612 451.411 460.297 437.472 410.383 390.036 389.909 397.75 394.597 334.247 291.892 274.686 252.1 229.529 206.696 186.148 168.607 153.376 140.536 129.566 120.107 111.693 103.984 96.7993 90.0081 83.5559 77.4343 71.6291 66.1353 60.8959 55.9254 51.3054 46.959 42.8798 39.0721 35.5117 32.2024 29.0642 25.7461 22.3438 19.1253 16.4705 14.537 13.2877 12.5455 12.0474 11.6064 11.1933 10.5331 9.45531 8.6577 8.82744 8.98386 8.46801 7.66639 7.18182 7.1459 7.33821 7.16775 6.65045 6.0745 5.42917 4.80274 4.36952 119.038 71.2405 45.0584 36.3157 32.5144 28.0823 21.4854 15.8497 14.5044 16.7639 20.6133 19.7693 17.7965 14.0365 10.0857 7.88492 7.66505 8.16866 9.59338 10.9783 12.2375 13.5619 15.108 17.0004 19.4224 22.7377 27.1533 37.0292 51.8661 80.6344 107.171 105.601 102.078 105.217 113.851 119.665 120.968 120.316 118.486 115.87 113.356 110.984 108.64 106.231 103.694 100.686 97.439 93.4219 88.6645 83.4513 77.5502 70.9549 64.0796 57.1887 50.4313 43.9578 37.9103 32.3261 27.414 23.1949 19.5831 16.6989 14.1335 11.2085 8.30028 6.43183 5.00793 4.11864 4.29586 6.15122 11.8637 19.3828 24.4476 25.3999 26.4888 28.2608 28.3156 26.9067 25.9403 27.4364 32.6284 38.6308 44.0534 49.2857 53.0937 55.3895 57.4134 60.3592 63.4424 65.6933 67.7261 69.0161 68.8927 67.6351 66.6698 66.9119 67.6401 70.0542 72.6389 72.4807 71.2628 67.6489 63.4664 63.0176 64.2318 67.3646 71.7838 77.0469 83.3834 91.1276 101.222 114.944 139.155 166.773 215.046 271.053 267.399 254.031 223.143 182.482 139.765 140.682 201.4 271.143 289.667 276.54 258.114 238.987 226.477 236.669 286.55 349.087 325.691 315.88 297.883 268.939 260.092 284.366 331.818 380.631 415.921 446.955 455.019 439.311 402.993 358.481 310.622 264.355 226.96 202.571 187.938 177.259 165.945 152.89 139.04 126.014 115.066 106.218 98.4584 91.3234 84.7369 78.7256 72.7617 66.6646 60.6651 54.9551 49.6751 44.8657 40.5612 36.6519 33.3343 30.6855 28.5705 26.9177 25.2409 23.1107 21.3871 19.9 18.494 17.0984 15.6926 14.3749 13.2197 12.2823 11.5667 11.0616 10.7723 10.6012 10.4404 10.2224 9.93321 9.58721 9.21077 8.81781 8.42291 8.03119 7.65871 7.29767 6.9773 6.6827 ) ; } frontAndBackPlanes { type empty; } } // ************************************************************************* //
[ "mizuha.watanabe@gmail.com" ]
mizuha.watanabe@gmail.com
d6c361204b501ab495a41b68a59fad13a5cbcc26
ed91c77afaeb0e075da38153aa89c6ee8382d3fc
/mediasoup-client/deps/webrtc/src/video/send_statistics_proxy.cc
a50008c9bef937e46d56598c0f66a2aee391ab7b
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-google-patent-license-webrtc", "LicenseRef-scancode-google-patent-license-webm" ]
permissive
whatisor/mediasoup-client-android
37bf1aeaadc8db642cff449a26545bf15da27539
dc3d812974991d9b94efbc303aa2deb358928546
refs/heads/master
2023-04-26T12:24:18.355241
2023-01-02T16:55:19
2023-01-02T16:55:19
243,833,549
0
0
MIT
2020-02-28T18:56:36
2020-02-28T18:56:36
null
UTF-8
C++
false
false
59,371
cc
/* * Copyright (c) 2013 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. */ #include "video/send_statistics_proxy.h" #include <algorithm> #include <array> #include <cmath> #include <limits> #include <utility> #include "absl/strings/match.h" #include "api/video/video_codec_constants.h" #include "api/video/video_codec_type.h" #include "api/video_codecs/video_codec.h" #include "modules/video_coding/include/video_codec_interface.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/mod_ops.h" #include "rtc_base/strings/string_builder.h" #include "system_wrappers/include/field_trial.h" #include "system_wrappers/include/metrics.h" namespace webrtc { namespace { const float kEncodeTimeWeigthFactor = 0.5f; const size_t kMaxEncodedFrameMapSize = 150; const int64_t kMaxEncodedFrameWindowMs = 800; const uint32_t kMaxEncodedFrameTimestampDiff = 900000; // 10 sec. const int64_t kBucketSizeMs = 100; const size_t kBucketCount = 10; const char kVp8ForcedFallbackEncoderFieldTrial[] = "WebRTC-VP8-Forced-Fallback-Encoder-v2"; const char kVp8SwCodecName[] = "libvpx"; // Used by histograms. Values of entries should not be changed. enum HistogramCodecType { kVideoUnknown = 0, kVideoVp8 = 1, kVideoVp9 = 2, kVideoH264 = 3, kVideoMax = 64, }; const char* kRealtimePrefix = "WebRTC.Video."; const char* kScreenPrefix = "WebRTC.Video.Screenshare."; const char* GetUmaPrefix(VideoEncoderConfig::ContentType content_type) { switch (content_type) { case VideoEncoderConfig::ContentType::kRealtimeVideo: return kRealtimePrefix; case VideoEncoderConfig::ContentType::kScreen: return kScreenPrefix; } RTC_NOTREACHED(); return nullptr; } HistogramCodecType PayloadNameToHistogramCodecType( const std::string& payload_name) { VideoCodecType codecType = PayloadStringToCodecType(payload_name); switch (codecType) { case kVideoCodecVP8: return kVideoVp8; case kVideoCodecVP9: return kVideoVp9; case kVideoCodecH264: return kVideoH264; default: return kVideoUnknown; } } void UpdateCodecTypeHistogram(const std::string& payload_name) { RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.Encoder.CodecType", PayloadNameToHistogramCodecType(payload_name), kVideoMax); } bool IsForcedFallbackPossible(const CodecSpecificInfo* codec_info, int simulcast_index) { return codec_info->codecType == kVideoCodecVP8 && simulcast_index == 0 && (codec_info->codecSpecific.VP8.temporalIdx == 0 || codec_info->codecSpecific.VP8.temporalIdx == kNoTemporalIdx); } absl::optional<int> GetFallbackMaxPixels(const std::string& group) { if (group.empty()) return absl::nullopt; int min_pixels; int max_pixels; int min_bps; if (sscanf(group.c_str(), "-%d,%d,%d", &min_pixels, &max_pixels, &min_bps) != 3) { return absl::optional<int>(); } if (min_pixels <= 0 || max_pixels <= 0 || max_pixels < min_pixels) return absl::optional<int>(); return absl::optional<int>(max_pixels); } absl::optional<int> GetFallbackMaxPixelsIfFieldTrialEnabled() { std::string group = webrtc::field_trial::FindFullName(kVp8ForcedFallbackEncoderFieldTrial); return (absl::StartsWith(group, "Enabled")) ? GetFallbackMaxPixels(group.substr(7)) : absl::optional<int>(); } absl::optional<int> GetFallbackMaxPixelsIfFieldTrialDisabled() { std::string group = webrtc::field_trial::FindFullName(kVp8ForcedFallbackEncoderFieldTrial); return (absl::StartsWith(group, "Disabled")) ? GetFallbackMaxPixels(group.substr(8)) : absl::optional<int>(); } } // namespace const int SendStatisticsProxy::kStatsTimeoutMs = 5000; SendStatisticsProxy::SendStatisticsProxy( Clock* clock, const VideoSendStream::Config& config, VideoEncoderConfig::ContentType content_type) : clock_(clock), payload_name_(config.rtp.payload_name), rtp_config_(config.rtp), fallback_max_pixels_(GetFallbackMaxPixelsIfFieldTrialEnabled()), fallback_max_pixels_disabled_(GetFallbackMaxPixelsIfFieldTrialDisabled()), content_type_(content_type), start_ms_(clock->TimeInMilliseconds()), encode_time_(kEncodeTimeWeigthFactor), quality_limitation_reason_tracker_(clock_), media_byte_rate_tracker_(kBucketSizeMs, kBucketCount), encoded_frame_rate_tracker_(kBucketSizeMs, kBucketCount), last_num_spatial_layers_(0), last_num_simulcast_streams_(0), last_spatial_layer_use_{}, bw_limited_layers_(false), internal_encoder_scaler_(false), uma_container_( new UmaSamplesContainer(GetUmaPrefix(content_type_), stats_, clock)) { } SendStatisticsProxy::~SendStatisticsProxy() { MutexLock lock(&mutex_); uma_container_->UpdateHistograms(rtp_config_, stats_); int64_t elapsed_sec = (clock_->TimeInMilliseconds() - start_ms_) / 1000; RTC_HISTOGRAM_COUNTS_100000("WebRTC.Video.SendStreamLifetimeInSeconds", elapsed_sec); if (elapsed_sec >= metrics::kMinRunTimeInSeconds) UpdateCodecTypeHistogram(payload_name_); } SendStatisticsProxy::FallbackEncoderInfo::FallbackEncoderInfo() = default; SendStatisticsProxy::UmaSamplesContainer::UmaSamplesContainer( const char* prefix, const VideoSendStream::Stats& stats, Clock* const clock) : uma_prefix_(prefix), clock_(clock), input_frame_rate_tracker_(100, 10u), input_fps_counter_(clock, nullptr, true), sent_fps_counter_(clock, nullptr, true), total_byte_counter_(clock, nullptr, true), media_byte_counter_(clock, nullptr, true), rtx_byte_counter_(clock, nullptr, true), padding_byte_counter_(clock, nullptr, true), retransmit_byte_counter_(clock, nullptr, true), fec_byte_counter_(clock, nullptr, true), first_rtcp_stats_time_ms_(-1), first_rtp_stats_time_ms_(-1), start_stats_(stats), num_streams_(0), num_pixels_highest_stream_(0) { InitializeBitrateCounters(stats); static_assert( kMaxEncodedFrameTimestampDiff < std::numeric_limits<uint32_t>::max() / 2, "has to be smaller than half range"); } SendStatisticsProxy::UmaSamplesContainer::~UmaSamplesContainer() {} void SendStatisticsProxy::UmaSamplesContainer::InitializeBitrateCounters( const VideoSendStream::Stats& stats) { for (const auto& it : stats.substreams) { uint32_t ssrc = it.first; total_byte_counter_.SetLast(it.second.rtp_stats.transmitted.TotalBytes(), ssrc); padding_byte_counter_.SetLast(it.second.rtp_stats.transmitted.padding_bytes, ssrc); retransmit_byte_counter_.SetLast( it.second.rtp_stats.retransmitted.TotalBytes(), ssrc); fec_byte_counter_.SetLast(it.second.rtp_stats.fec.TotalBytes(), ssrc); switch (it.second.type) { case VideoSendStream::StreamStats::StreamType::kMedia: media_byte_counter_.SetLast(it.second.rtp_stats.MediaPayloadBytes(), ssrc); break; case VideoSendStream::StreamStats::StreamType::kRtx: rtx_byte_counter_.SetLast(it.second.rtp_stats.transmitted.TotalBytes(), ssrc); break; case VideoSendStream::StreamStats::StreamType::kFlexfec: break; } } } void SendStatisticsProxy::UmaSamplesContainer::RemoveOld(int64_t now_ms) { while (!encoded_frames_.empty()) { auto it = encoded_frames_.begin(); if (now_ms - it->second.send_ms < kMaxEncodedFrameWindowMs) break; // Use max per timestamp. sent_width_counter_.Add(it->second.max_width); sent_height_counter_.Add(it->second.max_height); // Check number of encoded streams per timestamp. if (num_streams_ > static_cast<size_t>(it->second.max_simulcast_idx)) { if (num_streams_ > 1) { int disabled_streams = static_cast<int>(num_streams_ - 1 - it->second.max_simulcast_idx); // Can be limited in resolution or framerate. uint32_t pixels = it->second.max_width * it->second.max_height; bool bw_limited_resolution = disabled_streams > 0 && pixels < num_pixels_highest_stream_; bw_limited_frame_counter_.Add(bw_limited_resolution); if (bw_limited_resolution) { bw_resolutions_disabled_counter_.Add(disabled_streams); } } } encoded_frames_.erase(it); } } bool SendStatisticsProxy::UmaSamplesContainer::InsertEncodedFrame( const EncodedImage& encoded_frame, int simulcast_idx) { int64_t now_ms = clock_->TimeInMilliseconds(); RemoveOld(now_ms); if (encoded_frames_.size() > kMaxEncodedFrameMapSize) { encoded_frames_.clear(); } // Check for jump in timestamp. if (!encoded_frames_.empty()) { uint32_t oldest_timestamp = encoded_frames_.begin()->first; if (ForwardDiff(oldest_timestamp, encoded_frame.Timestamp()) > kMaxEncodedFrameTimestampDiff) { // Gap detected, clear frames to have a sequence where newest timestamp // is not too far away from oldest in order to distinguish old and new. encoded_frames_.clear(); } } auto it = encoded_frames_.find(encoded_frame.Timestamp()); if (it == encoded_frames_.end()) { // First frame with this timestamp. encoded_frames_.insert( std::make_pair(encoded_frame.Timestamp(), Frame(now_ms, encoded_frame._encodedWidth, encoded_frame._encodedHeight, simulcast_idx))); sent_fps_counter_.Add(1); return true; } it->second.max_width = std::max(it->second.max_width, encoded_frame._encodedWidth); it->second.max_height = std::max(it->second.max_height, encoded_frame._encodedHeight); it->second.max_simulcast_idx = std::max(it->second.max_simulcast_idx, simulcast_idx); return false; } void SendStatisticsProxy::UmaSamplesContainer::UpdateHistograms( const RtpConfig& rtp_config, const VideoSendStream::Stats& current_stats) { RTC_DCHECK(uma_prefix_ == kRealtimePrefix || uma_prefix_ == kScreenPrefix); const int kIndex = uma_prefix_ == kScreenPrefix ? 1 : 0; const int kMinRequiredPeriodicSamples = 6; char log_stream_buf[8 * 1024]; rtc::SimpleStringBuilder log_stream(log_stream_buf); int in_width = input_width_counter_.Avg(kMinRequiredMetricsSamples); int in_height = input_height_counter_.Avg(kMinRequiredMetricsSamples); if (in_width != -1) { RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "InputWidthInPixels", in_width); RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "InputHeightInPixels", in_height); log_stream << uma_prefix_ << "InputWidthInPixels " << in_width << "\n" << uma_prefix_ << "InputHeightInPixels " << in_height << "\n"; } AggregatedStats in_fps = input_fps_counter_.GetStats(); if (in_fps.num_samples >= kMinRequiredPeriodicSamples) { RTC_HISTOGRAMS_COUNTS_100(kIndex, uma_prefix_ + "InputFramesPerSecond", in_fps.average); log_stream << uma_prefix_ << "InputFramesPerSecond " << in_fps.ToString() << "\n"; } int sent_width = sent_width_counter_.Avg(kMinRequiredMetricsSamples); int sent_height = sent_height_counter_.Avg(kMinRequiredMetricsSamples); if (sent_width != -1) { RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "SentWidthInPixels", sent_width); RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "SentHeightInPixels", sent_height); log_stream << uma_prefix_ << "SentWidthInPixels " << sent_width << "\n" << uma_prefix_ << "SentHeightInPixels " << sent_height << "\n"; } AggregatedStats sent_fps = sent_fps_counter_.GetStats(); if (sent_fps.num_samples >= kMinRequiredPeriodicSamples) { RTC_HISTOGRAMS_COUNTS_100(kIndex, uma_prefix_ + "SentFramesPerSecond", sent_fps.average); log_stream << uma_prefix_ << "SentFramesPerSecond " << sent_fps.ToString() << "\n"; } if (in_fps.num_samples > kMinRequiredPeriodicSamples && sent_fps.num_samples >= kMinRequiredPeriodicSamples) { int in_fps_avg = in_fps.average; if (in_fps_avg > 0) { int sent_fps_avg = sent_fps.average; int sent_to_in_fps_ratio_percent = (100 * sent_fps_avg + in_fps_avg / 2) / in_fps_avg; // If reported period is small, it may happen that sent_fps is larger than // input_fps briefly on average. This should be treated as 100% sent to // input ratio. if (sent_to_in_fps_ratio_percent > 100) sent_to_in_fps_ratio_percent = 100; RTC_HISTOGRAMS_PERCENTAGE(kIndex, uma_prefix_ + "SentToInputFpsRatioPercent", sent_to_in_fps_ratio_percent); log_stream << uma_prefix_ << "SentToInputFpsRatioPercent " << sent_to_in_fps_ratio_percent << "\n"; } } int encode_ms = encode_time_counter_.Avg(kMinRequiredMetricsSamples); if (encode_ms != -1) { RTC_HISTOGRAMS_COUNTS_1000(kIndex, uma_prefix_ + "EncodeTimeInMs", encode_ms); log_stream << uma_prefix_ << "EncodeTimeInMs " << encode_ms << "\n"; } int key_frames_permille = key_frame_counter_.Permille(kMinRequiredMetricsSamples); if (key_frames_permille != -1) { RTC_HISTOGRAMS_COUNTS_1000(kIndex, uma_prefix_ + "KeyFramesSentInPermille", key_frames_permille); log_stream << uma_prefix_ << "KeyFramesSentInPermille " << key_frames_permille << "\n"; } int quality_limited = quality_limited_frame_counter_.Percent(kMinRequiredMetricsSamples); if (quality_limited != -1) { RTC_HISTOGRAMS_PERCENTAGE(kIndex, uma_prefix_ + "QualityLimitedResolutionInPercent", quality_limited); log_stream << uma_prefix_ << "QualityLimitedResolutionInPercent " << quality_limited << "\n"; } int downscales = quality_downscales_counter_.Avg(kMinRequiredMetricsSamples); if (downscales != -1) { RTC_HISTOGRAMS_ENUMERATION( kIndex, uma_prefix_ + "QualityLimitedResolutionDownscales", downscales, 20); } int cpu_limited = cpu_limited_frame_counter_.Percent(kMinRequiredMetricsSamples); if (cpu_limited != -1) { RTC_HISTOGRAMS_PERCENTAGE( kIndex, uma_prefix_ + "CpuLimitedResolutionInPercent", cpu_limited); } int bw_limited = bw_limited_frame_counter_.Percent(kMinRequiredMetricsSamples); if (bw_limited != -1) { RTC_HISTOGRAMS_PERCENTAGE( kIndex, uma_prefix_ + "BandwidthLimitedResolutionInPercent", bw_limited); } int num_disabled = bw_resolutions_disabled_counter_.Avg(kMinRequiredMetricsSamples); if (num_disabled != -1) { RTC_HISTOGRAMS_ENUMERATION( kIndex, uma_prefix_ + "BandwidthLimitedResolutionsDisabled", num_disabled, 10); } int delay_ms = delay_counter_.Avg(kMinRequiredMetricsSamples); if (delay_ms != -1) RTC_HISTOGRAMS_COUNTS_100000(kIndex, uma_prefix_ + "SendSideDelayInMs", delay_ms); int max_delay_ms = max_delay_counter_.Avg(kMinRequiredMetricsSamples); if (max_delay_ms != -1) { RTC_HISTOGRAMS_COUNTS_100000(kIndex, uma_prefix_ + "SendSideDelayMaxInMs", max_delay_ms); } for (const auto& it : qp_counters_) { int qp_vp8 = it.second.vp8.Avg(kMinRequiredMetricsSamples); if (qp_vp8 != -1) { int spatial_idx = it.first; if (spatial_idx == -1) { RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.Vp8", qp_vp8); } else if (spatial_idx == 0) { RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.Vp8.S0", qp_vp8); } else if (spatial_idx == 1) { RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.Vp8.S1", qp_vp8); } else if (spatial_idx == 2) { RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.Vp8.S2", qp_vp8); } else { RTC_LOG(LS_WARNING) << "QP stats not recorded for VP8 spatial idx " << spatial_idx; } } int qp_vp9 = it.second.vp9.Avg(kMinRequiredMetricsSamples); if (qp_vp9 != -1) { int spatial_idx = it.first; if (spatial_idx == -1) { RTC_HISTOGRAMS_COUNTS_500(kIndex, uma_prefix_ + "Encoded.Qp.Vp9", qp_vp9); } else if (spatial_idx == 0) { RTC_HISTOGRAMS_COUNTS_500(kIndex, uma_prefix_ + "Encoded.Qp.Vp9.S0", qp_vp9); } else if (spatial_idx == 1) { RTC_HISTOGRAMS_COUNTS_500(kIndex, uma_prefix_ + "Encoded.Qp.Vp9.S1", qp_vp9); } else if (spatial_idx == 2) { RTC_HISTOGRAMS_COUNTS_500(kIndex, uma_prefix_ + "Encoded.Qp.Vp9.S2", qp_vp9); } else { RTC_LOG(LS_WARNING) << "QP stats not recorded for VP9 spatial layer " << spatial_idx; } } int qp_h264 = it.second.h264.Avg(kMinRequiredMetricsSamples); if (qp_h264 != -1) { int spatial_idx = it.first; if (spatial_idx == -1) { RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.H264", qp_h264); } else if (spatial_idx == 0) { RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.H264.S0", qp_h264); } else if (spatial_idx == 1) { RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.H264.S1", qp_h264); } else if (spatial_idx == 2) { RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.H264.S2", qp_h264); } else { RTC_LOG(LS_WARNING) << "QP stats not recorded for H264 spatial idx " << spatial_idx; } } } if (first_rtp_stats_time_ms_ != -1) { quality_adapt_timer_.Stop(clock_->TimeInMilliseconds()); int64_t elapsed_sec = quality_adapt_timer_.total_ms / 1000; if (elapsed_sec >= metrics::kMinRunTimeInSeconds) { int quality_changes = current_stats.number_of_quality_adapt_changes - start_stats_.number_of_quality_adapt_changes; // Only base stats on changes during a call, discard initial changes. int initial_changes = initial_quality_changes_.down + initial_quality_changes_.up; if (initial_changes <= quality_changes) quality_changes -= initial_changes; RTC_HISTOGRAMS_COUNTS_100(kIndex, uma_prefix_ + "AdaptChangesPerMinute.Quality", quality_changes * 60 / elapsed_sec); } cpu_adapt_timer_.Stop(clock_->TimeInMilliseconds()); elapsed_sec = cpu_adapt_timer_.total_ms / 1000; if (elapsed_sec >= metrics::kMinRunTimeInSeconds) { int cpu_changes = current_stats.number_of_cpu_adapt_changes - start_stats_.number_of_cpu_adapt_changes; RTC_HISTOGRAMS_COUNTS_100(kIndex, uma_prefix_ + "AdaptChangesPerMinute.Cpu", cpu_changes * 60 / elapsed_sec); } } if (first_rtcp_stats_time_ms_ != -1) { int64_t elapsed_sec = (clock_->TimeInMilliseconds() - first_rtcp_stats_time_ms_) / 1000; if (elapsed_sec >= metrics::kMinRunTimeInSeconds) { int fraction_lost = report_block_stats_.FractionLostInPercent(); if (fraction_lost != -1) { RTC_HISTOGRAMS_PERCENTAGE( kIndex, uma_prefix_ + "SentPacketsLostInPercent", fraction_lost); log_stream << uma_prefix_ << "SentPacketsLostInPercent " << fraction_lost << "\n"; } // The RTCP packet type counters, delivered via the // RtcpPacketTypeCounterObserver interface, are aggregates over the entire // life of the send stream and are not reset when switching content type. // For the purpose of these statistics though, we want new counts when // switching since we switch histogram name. On every reset of the // UmaSamplesContainer, we save the initial state of the counters, so that // we can calculate the delta here and aggregate over all ssrcs. RtcpPacketTypeCounter counters; for (uint32_t ssrc : rtp_config.ssrcs) { auto kv = current_stats.substreams.find(ssrc); if (kv == current_stats.substreams.end()) continue; RtcpPacketTypeCounter stream_counters = kv->second.rtcp_packet_type_counts; kv = start_stats_.substreams.find(ssrc); if (kv != start_stats_.substreams.end()) stream_counters.Subtract(kv->second.rtcp_packet_type_counts); counters.Add(stream_counters); } RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "NackPacketsReceivedPerMinute", counters.nack_packets * 60 / elapsed_sec); RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "FirPacketsReceivedPerMinute", counters.fir_packets * 60 / elapsed_sec); RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "PliPacketsReceivedPerMinute", counters.pli_packets * 60 / elapsed_sec); if (counters.nack_requests > 0) { RTC_HISTOGRAMS_PERCENTAGE( kIndex, uma_prefix_ + "UniqueNackRequestsReceivedInPercent", counters.UniqueNackRequestsInPercent()); } } } if (first_rtp_stats_time_ms_ != -1) { int64_t elapsed_sec = (clock_->TimeInMilliseconds() - first_rtp_stats_time_ms_) / 1000; if (elapsed_sec >= metrics::kMinRunTimeInSeconds) { RTC_HISTOGRAMS_COUNTS_100(kIndex, uma_prefix_ + "NumberOfPauseEvents", target_rate_updates_.pause_resume_events); log_stream << uma_prefix_ << "NumberOfPauseEvents " << target_rate_updates_.pause_resume_events << "\n"; int paused_time_percent = paused_time_counter_.Percent(metrics::kMinRunTimeInSeconds * 1000); if (paused_time_percent != -1) { RTC_HISTOGRAMS_PERCENTAGE(kIndex, uma_prefix_ + "PausedTimeInPercent", paused_time_percent); log_stream << uma_prefix_ << "PausedTimeInPercent " << paused_time_percent << "\n"; } } } if (fallback_info_.is_possible) { // Double interval since there is some time before fallback may occur. const int kMinRunTimeMs = 2 * metrics::kMinRunTimeInSeconds * 1000; int64_t elapsed_ms = fallback_info_.elapsed_ms; int fallback_time_percent = fallback_active_counter_.Percent(kMinRunTimeMs); if (fallback_time_percent != -1 && elapsed_ms >= kMinRunTimeMs) { RTC_HISTOGRAMS_PERCENTAGE( kIndex, uma_prefix_ + "Encoder.ForcedSwFallbackTimeInPercent.Vp8", fallback_time_percent); RTC_HISTOGRAMS_COUNTS_100( kIndex, uma_prefix_ + "Encoder.ForcedSwFallbackChangesPerMinute.Vp8", fallback_info_.on_off_events * 60 / (elapsed_ms / 1000)); } } AggregatedStats total_bytes_per_sec = total_byte_counter_.GetStats(); if (total_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) { RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "BitrateSentInKbps", total_bytes_per_sec.average * 8 / 1000); log_stream << uma_prefix_ << "BitrateSentInBps " << total_bytes_per_sec.ToStringWithMultiplier(8) << "\n"; } AggregatedStats media_bytes_per_sec = media_byte_counter_.GetStats(); if (media_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) { RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "MediaBitrateSentInKbps", media_bytes_per_sec.average * 8 / 1000); log_stream << uma_prefix_ << "MediaBitrateSentInBps " << media_bytes_per_sec.ToStringWithMultiplier(8) << "\n"; } AggregatedStats padding_bytes_per_sec = padding_byte_counter_.GetStats(); if (padding_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) { RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "PaddingBitrateSentInKbps", padding_bytes_per_sec.average * 8 / 1000); log_stream << uma_prefix_ << "PaddingBitrateSentInBps " << padding_bytes_per_sec.ToStringWithMultiplier(8) << "\n"; } AggregatedStats retransmit_bytes_per_sec = retransmit_byte_counter_.GetStats(); if (retransmit_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) { RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "RetransmittedBitrateSentInKbps", retransmit_bytes_per_sec.average * 8 / 1000); log_stream << uma_prefix_ << "RetransmittedBitrateSentInBps " << retransmit_bytes_per_sec.ToStringWithMultiplier(8) << "\n"; } if (!rtp_config.rtx.ssrcs.empty()) { AggregatedStats rtx_bytes_per_sec = rtx_byte_counter_.GetStats(); int rtx_bytes_per_sec_avg = -1; if (rtx_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) { rtx_bytes_per_sec_avg = rtx_bytes_per_sec.average; log_stream << uma_prefix_ << "RtxBitrateSentInBps " << rtx_bytes_per_sec.ToStringWithMultiplier(8) << "\n"; } else if (total_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) { rtx_bytes_per_sec_avg = 0; // RTX enabled but no RTX data sent, record 0. } if (rtx_bytes_per_sec_avg != -1) { RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "RtxBitrateSentInKbps", rtx_bytes_per_sec_avg * 8 / 1000); } } if (rtp_config.flexfec.payload_type != -1 || rtp_config.ulpfec.red_payload_type != -1) { AggregatedStats fec_bytes_per_sec = fec_byte_counter_.GetStats(); if (fec_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) { RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "FecBitrateSentInKbps", fec_bytes_per_sec.average * 8 / 1000); log_stream << uma_prefix_ << "FecBitrateSentInBps " << fec_bytes_per_sec.ToStringWithMultiplier(8) << "\n"; } } log_stream << "Frames encoded " << current_stats.frames_encoded << "\n" << uma_prefix_ << "DroppedFrames.Capturer " << current_stats.frames_dropped_by_capturer << "\n"; RTC_HISTOGRAMS_COUNTS_1000(kIndex, uma_prefix_ + "DroppedFrames.Capturer", current_stats.frames_dropped_by_capturer); log_stream << uma_prefix_ << "DroppedFrames.EncoderQueue " << current_stats.frames_dropped_by_encoder_queue << "\n"; RTC_HISTOGRAMS_COUNTS_1000(kIndex, uma_prefix_ + "DroppedFrames.EncoderQueue", current_stats.frames_dropped_by_encoder_queue); log_stream << uma_prefix_ << "DroppedFrames.Encoder " << current_stats.frames_dropped_by_encoder << "\n"; RTC_HISTOGRAMS_COUNTS_1000(kIndex, uma_prefix_ + "DroppedFrames.Encoder", current_stats.frames_dropped_by_encoder); log_stream << uma_prefix_ << "DroppedFrames.Ratelimiter " << current_stats.frames_dropped_by_rate_limiter << "\n"; RTC_HISTOGRAMS_COUNTS_1000(kIndex, uma_prefix_ + "DroppedFrames.Ratelimiter", current_stats.frames_dropped_by_rate_limiter); log_stream << uma_prefix_ << "DroppedFrames.CongestionWindow " << current_stats.frames_dropped_by_congestion_window; RTC_LOG(LS_INFO) << log_stream.str(); } void SendStatisticsProxy::OnEncoderReconfigured( const VideoEncoderConfig& config, const std::vector<VideoStream>& streams) { // Called on VideoStreamEncoder's encoder_queue_. MutexLock lock(&mutex_); if (content_type_ != config.content_type) { uma_container_->UpdateHistograms(rtp_config_, stats_); uma_container_.reset(new UmaSamplesContainer( GetUmaPrefix(config.content_type), stats_, clock_)); content_type_ = config.content_type; } uma_container_->encoded_frames_.clear(); uma_container_->num_streams_ = streams.size(); uma_container_->num_pixels_highest_stream_ = streams.empty() ? 0 : (streams.back().width * streams.back().height); } void SendStatisticsProxy::OnEncodedFrameTimeMeasured(int encode_time_ms, int encode_usage_percent) { RTC_DCHECK_GE(encode_time_ms, 0); MutexLock lock(&mutex_); uma_container_->encode_time_counter_.Add(encode_time_ms); encode_time_.Apply(1.0f, encode_time_ms); stats_.avg_encode_time_ms = std::round(encode_time_.filtered()); stats_.total_encode_time_ms += encode_time_ms; stats_.encode_usage_percent = encode_usage_percent; } void SendStatisticsProxy::OnSuspendChange(bool is_suspended) { int64_t now_ms = clock_->TimeInMilliseconds(); MutexLock lock(&mutex_); stats_.suspended = is_suspended; if (is_suspended) { // Pause framerate (add min pause time since there may be frames/packets // that are not yet sent). const int64_t kMinMs = 500; uma_container_->input_fps_counter_.ProcessAndPauseForDuration(kMinMs); uma_container_->sent_fps_counter_.ProcessAndPauseForDuration(kMinMs); // Pause bitrate stats. uma_container_->total_byte_counter_.ProcessAndPauseForDuration(kMinMs); uma_container_->media_byte_counter_.ProcessAndPauseForDuration(kMinMs); uma_container_->rtx_byte_counter_.ProcessAndPauseForDuration(kMinMs); uma_container_->padding_byte_counter_.ProcessAndPauseForDuration(kMinMs); uma_container_->retransmit_byte_counter_.ProcessAndPauseForDuration(kMinMs); uma_container_->fec_byte_counter_.ProcessAndPauseForDuration(kMinMs); // Stop adaptation stats. uma_container_->cpu_adapt_timer_.Stop(now_ms); uma_container_->quality_adapt_timer_.Stop(now_ms); } else { // Start adaptation stats if scaling is enabled. if (adaptation_limitations_.MaskedCpuCounts() .resolution_adaptations.has_value()) uma_container_->cpu_adapt_timer_.Start(now_ms); if (adaptation_limitations_.MaskedQualityCounts() .resolution_adaptations.has_value()) uma_container_->quality_adapt_timer_.Start(now_ms); // Stop pause explicitly for stats that may be zero/not updated for some // time. uma_container_->rtx_byte_counter_.ProcessAndStopPause(); uma_container_->padding_byte_counter_.ProcessAndStopPause(); uma_container_->retransmit_byte_counter_.ProcessAndStopPause(); uma_container_->fec_byte_counter_.ProcessAndStopPause(); } } VideoSendStream::Stats SendStatisticsProxy::GetStats() { MutexLock lock(&mutex_); PurgeOldStats(); stats_.input_frame_rate = round(uma_container_->input_frame_rate_tracker_.ComputeRate()); stats_.frames = uma_container_->input_frame_rate_tracker_.TotalSampleCount(); stats_.content_type = content_type_ == VideoEncoderConfig::ContentType::kRealtimeVideo ? VideoContentType::UNSPECIFIED : VideoContentType::SCREENSHARE; stats_.encode_frame_rate = round(encoded_frame_rate_tracker_.ComputeRate()); stats_.media_bitrate_bps = media_byte_rate_tracker_.ComputeRate() * 8; stats_.quality_limitation_durations_ms = quality_limitation_reason_tracker_.DurationsMs(); for (auto& substream : stats_.substreams) { uint32_t ssrc = substream.first; if (encoded_frame_rate_trackers_.count(ssrc) > 0) { substream.second.encode_frame_rate = encoded_frame_rate_trackers_[ssrc]->ComputeRate(); } } return stats_; } void SendStatisticsProxy::PurgeOldStats() { int64_t old_stats_ms = clock_->TimeInMilliseconds() - kStatsTimeoutMs; for (std::map<uint32_t, VideoSendStream::StreamStats>::iterator it = stats_.substreams.begin(); it != stats_.substreams.end(); ++it) { uint32_t ssrc = it->first; if (update_times_[ssrc].resolution_update_ms <= old_stats_ms) { it->second.width = 0; it->second.height = 0; } } } VideoSendStream::StreamStats* SendStatisticsProxy::GetStatsEntry( uint32_t ssrc) { std::map<uint32_t, VideoSendStream::StreamStats>::iterator it = stats_.substreams.find(ssrc); if (it != stats_.substreams.end()) return &it->second; bool is_media = rtp_config_.IsMediaSsrc(ssrc); bool is_flexfec = rtp_config_.flexfec.payload_type != -1 && ssrc == rtp_config_.flexfec.ssrc; bool is_rtx = rtp_config_.IsRtxSsrc(ssrc); if (!is_media && !is_flexfec && !is_rtx) return nullptr; // Insert new entry and return ptr. VideoSendStream::StreamStats* entry = &stats_.substreams[ssrc]; if (is_media) { entry->type = VideoSendStream::StreamStats::StreamType::kMedia; } else if (is_rtx) { entry->type = VideoSendStream::StreamStats::StreamType::kRtx; } else if (is_flexfec) { entry->type = VideoSendStream::StreamStats::StreamType::kFlexfec; } else { RTC_NOTREACHED(); } switch (entry->type) { case VideoSendStream::StreamStats::StreamType::kMedia: break; case VideoSendStream::StreamStats::StreamType::kRtx: entry->referenced_media_ssrc = rtp_config_.GetMediaSsrcAssociatedWithRtxSsrc(ssrc); break; case VideoSendStream::StreamStats::StreamType::kFlexfec: entry->referenced_media_ssrc = rtp_config_.GetMediaSsrcAssociatedWithFlexfecSsrc(ssrc); break; } return entry; } void SendStatisticsProxy::OnInactiveSsrc(uint32_t ssrc) { MutexLock lock(&mutex_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (!stats) return; stats->total_bitrate_bps = 0; stats->retransmit_bitrate_bps = 0; stats->height = 0; stats->width = 0; } void SendStatisticsProxy::OnSetEncoderTargetRate(uint32_t bitrate_bps) { MutexLock lock(&mutex_); if (uma_container_->target_rate_updates_.last_ms == -1 && bitrate_bps == 0) return; // Start on first non-zero bitrate, may initially be zero. int64_t now = clock_->TimeInMilliseconds(); if (uma_container_->target_rate_updates_.last_ms != -1) { bool was_paused = stats_.target_media_bitrate_bps == 0; int64_t diff_ms = now - uma_container_->target_rate_updates_.last_ms; uma_container_->paused_time_counter_.Add(was_paused, diff_ms); // Use last to not include update when stream is stopped and video disabled. if (uma_container_->target_rate_updates_.last_paused_or_resumed) ++uma_container_->target_rate_updates_.pause_resume_events; // Check if video is paused/resumed. uma_container_->target_rate_updates_.last_paused_or_resumed = (bitrate_bps == 0) != was_paused; } uma_container_->target_rate_updates_.last_ms = now; stats_.target_media_bitrate_bps = bitrate_bps; } void SendStatisticsProxy::UpdateEncoderFallbackStats( const CodecSpecificInfo* codec_info, int pixels, int simulcast_index) { UpdateFallbackDisabledStats(codec_info, pixels, simulcast_index); if (!fallback_max_pixels_ || !uma_container_->fallback_info_.is_possible) { return; } if (!IsForcedFallbackPossible(codec_info, simulcast_index)) { uma_container_->fallback_info_.is_possible = false; return; } FallbackEncoderInfo* fallback_info = &uma_container_->fallback_info_; const int64_t now_ms = clock_->TimeInMilliseconds(); bool is_active = fallback_info->is_active; if (encoder_changed_) { // Implementation changed. const bool last_was_vp8_software = encoder_changed_->previous_encoder_implementation == kVp8SwCodecName; is_active = encoder_changed_->new_encoder_implementation == kVp8SwCodecName; encoder_changed_.reset(); if (!is_active && !last_was_vp8_software) { // First or not a VP8 SW change, update stats on next call. return; } if (is_active && (pixels > *fallback_max_pixels_)) { // Pixels should not be above `fallback_max_pixels_`. If above skip to // avoid fallbacks due to failure. fallback_info->is_possible = false; return; } stats_.has_entered_low_resolution = true; ++fallback_info->on_off_events; } if (fallback_info->last_update_ms) { int64_t diff_ms = now_ms - *(fallback_info->last_update_ms); // If the time diff since last update is greater than `max_frame_diff_ms`, // video is considered paused/muted and the change is not included. if (diff_ms < fallback_info->max_frame_diff_ms) { uma_container_->fallback_active_counter_.Add(fallback_info->is_active, diff_ms); fallback_info->elapsed_ms += diff_ms; } } fallback_info->is_active = is_active; fallback_info->last_update_ms.emplace(now_ms); } void SendStatisticsProxy::UpdateFallbackDisabledStats( const CodecSpecificInfo* codec_info, int pixels, int simulcast_index) { if (!fallback_max_pixels_disabled_ || !uma_container_->fallback_info_disabled_.is_possible || stats_.has_entered_low_resolution) { return; } if (!IsForcedFallbackPossible(codec_info, simulcast_index) || stats_.encoder_implementation_name == kVp8SwCodecName) { uma_container_->fallback_info_disabled_.is_possible = false; return; } if (pixels <= *fallback_max_pixels_disabled_ || uma_container_->fallback_info_disabled_.min_pixel_limit_reached) { stats_.has_entered_low_resolution = true; } } void SendStatisticsProxy::OnMinPixelLimitReached() { MutexLock lock(&mutex_); uma_container_->fallback_info_disabled_.min_pixel_limit_reached = true; } void SendStatisticsProxy::OnSendEncodedImage( const EncodedImage& encoded_image, const CodecSpecificInfo* codec_info) { // Simulcast is used for VP8, H264 and Generic. int simulcast_idx = (codec_info && (codec_info->codecType == kVideoCodecVP8 || codec_info->codecType == kVideoCodecH264 || codec_info->codecType == kVideoCodecGeneric)) ? encoded_image.SpatialIndex().value_or(0) : 0; MutexLock lock(&mutex_); ++stats_.frames_encoded; // The current encode frame rate is based on previously encoded frames. double encode_frame_rate = encoded_frame_rate_tracker_.ComputeRate(); // We assume that less than 1 FPS is not a trustworthy estimate - perhaps we // just started encoding for the first time or after a pause. Assuming frame // rate is at least 1 FPS is conservative to avoid too large increments. if (encode_frame_rate < 1.0) encode_frame_rate = 1.0; double target_frame_size_bytes = stats_.target_media_bitrate_bps / (8.0 * encode_frame_rate); // `stats_.target_media_bitrate_bps` is set in // SendStatisticsProxy::OnSetEncoderTargetRate. stats_.total_encoded_bytes_target += round(target_frame_size_bytes); if (codec_info) { UpdateEncoderFallbackStats( codec_info, encoded_image._encodedWidth * encoded_image._encodedHeight, simulcast_idx); } if (static_cast<size_t>(simulcast_idx) >= rtp_config_.ssrcs.size()) { RTC_LOG(LS_ERROR) << "Encoded image outside simulcast range (" << simulcast_idx << " >= " << rtp_config_.ssrcs.size() << ")."; return; } uint32_t ssrc = rtp_config_.ssrcs[simulcast_idx]; VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (!stats) return; if (encoded_frame_rate_trackers_.count(ssrc) == 0) { encoded_frame_rate_trackers_[ssrc] = std::make_unique<rtc::RateTracker>(kBucketSizeMs, kBucketCount); } stats->frames_encoded++; stats->total_encode_time_ms += encoded_image.timing_.encode_finish_ms - encoded_image.timing_.encode_start_ms; // Report resolution of the top spatial layer. bool is_top_spatial_layer = codec_info == nullptr || codec_info->end_of_picture; if (!stats->width || !stats->height || is_top_spatial_layer) { stats->width = encoded_image._encodedWidth; stats->height = encoded_image._encodedHeight; update_times_[ssrc].resolution_update_ms = clock_->TimeInMilliseconds(); } uma_container_->key_frame_counter_.Add(encoded_image._frameType == VideoFrameType::kVideoFrameKey); if (encoded_image.qp_ != -1) { if (!stats->qp_sum) stats->qp_sum = 0; *stats->qp_sum += encoded_image.qp_; if (codec_info) { if (codec_info->codecType == kVideoCodecVP8) { int spatial_idx = (rtp_config_.ssrcs.size() == 1) ? -1 : simulcast_idx; uma_container_->qp_counters_[spatial_idx].vp8.Add(encoded_image.qp_); } else if (codec_info->codecType == kVideoCodecVP9) { int spatial_idx = encoded_image.SpatialIndex().value_or(-1); uma_container_->qp_counters_[spatial_idx].vp9.Add(encoded_image.qp_); } else if (codec_info->codecType == kVideoCodecH264) { int spatial_idx = (rtp_config_.ssrcs.size() == 1) ? -1 : simulcast_idx; uma_container_->qp_counters_[spatial_idx].h264.Add(encoded_image.qp_); } } } // If any of the simulcast streams have a huge frame, it should be counted // as a single difficult input frame. // https://w3c.github.io/webrtc-stats/#dom-rtcvideosenderstats-hugeframessent if (encoded_image.timing_.flags & VideoSendTiming::kTriggeredBySize) { ++stats->huge_frames_sent; if (!last_outlier_timestamp_ || *last_outlier_timestamp_ < encoded_image.capture_time_ms_) { last_outlier_timestamp_.emplace(encoded_image.capture_time_ms_); ++stats_.huge_frames_sent; } } media_byte_rate_tracker_.AddSamples(encoded_image.size()); if (uma_container_->InsertEncodedFrame(encoded_image, simulcast_idx)) { // First frame seen with this timestamp, track overall fps. encoded_frame_rate_tracker_.AddSamples(1); } // is_top_spatial_layer pertains only to SVC, will always be true for // simulcast. if (is_top_spatial_layer) encoded_frame_rate_trackers_[ssrc]->AddSamples(1); absl::optional<int> downscales = adaptation_limitations_.MaskedQualityCounts().resolution_adaptations; stats_.bw_limited_resolution |= (downscales.has_value() && downscales.value() > 0); if (downscales.has_value()) { uma_container_->quality_limited_frame_counter_.Add(downscales.value() > 0); if (downscales.value() > 0) uma_container_->quality_downscales_counter_.Add(downscales.value()); } } void SendStatisticsProxy::OnEncoderImplementationChanged( const std::string& implementation_name) { MutexLock lock(&mutex_); encoder_changed_ = EncoderChangeEvent{stats_.encoder_implementation_name, implementation_name}; stats_.encoder_implementation_name = implementation_name; } int SendStatisticsProxy::GetInputFrameRate() const { MutexLock lock(&mutex_); return round(uma_container_->input_frame_rate_tracker_.ComputeRate()); } int SendStatisticsProxy::GetSendFrameRate() const { MutexLock lock(&mutex_); return round(encoded_frame_rate_tracker_.ComputeRate()); } void SendStatisticsProxy::OnIncomingFrame(int width, int height) { MutexLock lock(&mutex_); uma_container_->input_frame_rate_tracker_.AddSamples(1); uma_container_->input_fps_counter_.Add(1); uma_container_->input_width_counter_.Add(width); uma_container_->input_height_counter_.Add(height); if (adaptation_limitations_.MaskedCpuCounts() .resolution_adaptations.has_value()) { uma_container_->cpu_limited_frame_counter_.Add( stats_.cpu_limited_resolution); } if (encoded_frame_rate_tracker_.TotalSampleCount() == 0) { // Set start time now instead of when first key frame is encoded to avoid a // too high initial estimate. encoded_frame_rate_tracker_.AddSamples(0); } } void SendStatisticsProxy::OnFrameDropped(DropReason reason) { MutexLock lock(&mutex_); switch (reason) { case DropReason::kSource: ++stats_.frames_dropped_by_capturer; break; case DropReason::kEncoderQueue: ++stats_.frames_dropped_by_encoder_queue; break; case DropReason::kEncoder: ++stats_.frames_dropped_by_encoder; break; case DropReason::kMediaOptimization: ++stats_.frames_dropped_by_rate_limiter; break; case DropReason::kCongestionWindow: ++stats_.frames_dropped_by_congestion_window; break; } } void SendStatisticsProxy::ClearAdaptationStats() { MutexLock lock(&mutex_); adaptation_limitations_.set_cpu_counts(VideoAdaptationCounters()); adaptation_limitations_.set_quality_counts(VideoAdaptationCounters()); UpdateAdaptationStats(); } void SendStatisticsProxy::UpdateAdaptationSettings( VideoStreamEncoderObserver::AdaptationSettings cpu_settings, VideoStreamEncoderObserver::AdaptationSettings quality_settings) { MutexLock lock(&mutex_); adaptation_limitations_.UpdateMaskingSettings(cpu_settings, quality_settings); SetAdaptTimer(adaptation_limitations_.MaskedCpuCounts(), &uma_container_->cpu_adapt_timer_); SetAdaptTimer(adaptation_limitations_.MaskedQualityCounts(), &uma_container_->quality_adapt_timer_); UpdateAdaptationStats(); } void SendStatisticsProxy::OnAdaptationChanged( VideoAdaptationReason reason, const VideoAdaptationCounters& cpu_counters, const VideoAdaptationCounters& quality_counters) { MutexLock lock(&mutex_); MaskedAdaptationCounts receiver = adaptation_limitations_.MaskedQualityCounts(); adaptation_limitations_.set_cpu_counts(cpu_counters); adaptation_limitations_.set_quality_counts(quality_counters); switch (reason) { case VideoAdaptationReason::kCpu: ++stats_.number_of_cpu_adapt_changes; break; case VideoAdaptationReason::kQuality: TryUpdateInitialQualityResolutionAdaptUp( receiver.resolution_adaptations, adaptation_limitations_.MaskedQualityCounts().resolution_adaptations); ++stats_.number_of_quality_adapt_changes; break; } UpdateAdaptationStats(); } void SendStatisticsProxy::UpdateAdaptationStats() { auto cpu_counts = adaptation_limitations_.MaskedCpuCounts(); auto quality_counts = adaptation_limitations_.MaskedQualityCounts(); bool is_cpu_limited = cpu_counts.resolution_adaptations > 0 || cpu_counts.num_framerate_reductions > 0; bool is_bandwidth_limited = quality_counts.resolution_adaptations > 0 || quality_counts.num_framerate_reductions > 0 || bw_limited_layers_ || internal_encoder_scaler_; if (is_bandwidth_limited) { // We may be both CPU limited and bandwidth limited at the same time but // there is no way to express this in standardized stats. Heuristically, // bandwidth is more likely to be a limiting factor than CPU, and more // likely to vary over time, so only when we aren't bandwidth limited do we // want to know about our CPU being the bottleneck. quality_limitation_reason_tracker_.SetReason( QualityLimitationReason::kBandwidth); } else if (is_cpu_limited) { quality_limitation_reason_tracker_.SetReason(QualityLimitationReason::kCpu); } else { quality_limitation_reason_tracker_.SetReason( QualityLimitationReason::kNone); } stats_.cpu_limited_resolution = cpu_counts.resolution_adaptations > 0; stats_.cpu_limited_framerate = cpu_counts.num_framerate_reductions > 0; stats_.bw_limited_resolution = quality_counts.resolution_adaptations > 0; stats_.bw_limited_framerate = quality_counts.num_framerate_reductions > 0; // If bitrate allocator has disabled some layers frame-rate or resolution are // limited depending on the encoder configuration. if (bw_limited_layers_) { switch (content_type_) { case VideoEncoderConfig::ContentType::kRealtimeVideo: { stats_.bw_limited_resolution = true; break; } case VideoEncoderConfig::ContentType::kScreen: { stats_.bw_limited_framerate = true; break; } } } if (internal_encoder_scaler_) { stats_.bw_limited_resolution = true; } stats_.quality_limitation_reason = quality_limitation_reason_tracker_.current_reason(); // `stats_.quality_limitation_durations_ms` depends on the current time // when it is polled; it is updated in SendStatisticsProxy::GetStats(). } void SendStatisticsProxy::OnBitrateAllocationUpdated( const VideoCodec& codec, const VideoBitrateAllocation& allocation) { int num_spatial_layers = 0; for (int i = 0; i < kMaxSpatialLayers; i++) { if (codec.spatialLayers[i].active) { num_spatial_layers++; } } int num_simulcast_streams = 0; for (int i = 0; i < kMaxSimulcastStreams; i++) { if (codec.simulcastStream[i].active) { num_simulcast_streams++; } } std::array<bool, kMaxSpatialLayers> spatial_layers; for (int i = 0; i < kMaxSpatialLayers; i++) { spatial_layers[i] = (allocation.GetSpatialLayerSum(i) > 0); } MutexLock lock(&mutex_); bw_limited_layers_ = allocation.is_bw_limited(); UpdateAdaptationStats(); if (spatial_layers != last_spatial_layer_use_) { // If the number of spatial layers has changed, the resolution change is // not due to quality limitations, it is because the configuration // changed. if (last_num_spatial_layers_ == num_spatial_layers && last_num_simulcast_streams_ == num_simulcast_streams) { ++stats_.quality_limitation_resolution_changes; } last_spatial_layer_use_ = spatial_layers; } last_num_spatial_layers_ = num_spatial_layers; last_num_simulcast_streams_ = num_simulcast_streams; } // Informes observer if an internal encoder scaler has reduced video // resolution or not. `is_scaled` is a flag indicating if the video is scaled // down. void SendStatisticsProxy::OnEncoderInternalScalerUpdate(bool is_scaled) { MutexLock lock(&mutex_); internal_encoder_scaler_ = is_scaled; UpdateAdaptationStats(); } // TODO(asapersson): Include fps changes. void SendStatisticsProxy::OnInitialQualityResolutionAdaptDown() { MutexLock lock(&mutex_); ++uma_container_->initial_quality_changes_.down; } void SendStatisticsProxy::TryUpdateInitialQualityResolutionAdaptUp( absl::optional<int> old_quality_downscales, absl::optional<int> updated_quality_downscales) { if (uma_container_->initial_quality_changes_.down == 0) return; if (old_quality_downscales.has_value() && old_quality_downscales.value() > 0 && updated_quality_downscales.value_or(-1) < old_quality_downscales.value()) { // Adapting up in quality. if (uma_container_->initial_quality_changes_.down > uma_container_->initial_quality_changes_.up) { ++uma_container_->initial_quality_changes_.up; } } } void SendStatisticsProxy::SetAdaptTimer(const MaskedAdaptationCounts& counts, StatsTimer* timer) { if (counts.resolution_adaptations || counts.num_framerate_reductions) { // Adaptation enabled. if (!stats_.suspended) timer->Start(clock_->TimeInMilliseconds()); return; } timer->Stop(clock_->TimeInMilliseconds()); } void SendStatisticsProxy::RtcpPacketTypesCounterUpdated( uint32_t ssrc, const RtcpPacketTypeCounter& packet_counter) { MutexLock lock(&mutex_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (!stats) return; stats->rtcp_packet_type_counts = packet_counter; if (uma_container_->first_rtcp_stats_time_ms_ == -1) uma_container_->first_rtcp_stats_time_ms_ = clock_->TimeInMilliseconds(); } void SendStatisticsProxy::OnReportBlockDataUpdated( ReportBlockData report_block_data) { MutexLock lock(&mutex_); VideoSendStream::StreamStats* stats = GetStatsEntry(report_block_data.report_block().source_ssrc); if (!stats) return; const RTCPReportBlock& report_block = report_block_data.report_block(); uma_container_->report_block_stats_.Store( /*ssrc=*/report_block.source_ssrc, /*packets_lost=*/report_block.packets_lost, /*extended_highest_sequence_number=*/ report_block.extended_highest_sequence_number); stats->report_block_data = std::move(report_block_data); } void SendStatisticsProxy::DataCountersUpdated( const StreamDataCounters& counters, uint32_t ssrc) { MutexLock lock(&mutex_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); RTC_DCHECK(stats) << "DataCountersUpdated reported for unknown ssrc " << ssrc; if (stats->type == VideoSendStream::StreamStats::StreamType::kFlexfec) { // The same counters are reported for both the media ssrc and flexfec ssrc. // Bitrate stats are summed for all SSRCs. Use fec stats from media update. return; } stats->rtp_stats = counters; if (uma_container_->first_rtp_stats_time_ms_ == -1) { int64_t now_ms = clock_->TimeInMilliseconds(); uma_container_->first_rtp_stats_time_ms_ = now_ms; uma_container_->cpu_adapt_timer_.Restart(now_ms); uma_container_->quality_adapt_timer_.Restart(now_ms); } uma_container_->total_byte_counter_.Set(counters.transmitted.TotalBytes(), ssrc); uma_container_->padding_byte_counter_.Set(counters.transmitted.padding_bytes, ssrc); uma_container_->retransmit_byte_counter_.Set( counters.retransmitted.TotalBytes(), ssrc); uma_container_->fec_byte_counter_.Set(counters.fec.TotalBytes(), ssrc); switch (stats->type) { case VideoSendStream::StreamStats::StreamType::kMedia: uma_container_->media_byte_counter_.Set(counters.MediaPayloadBytes(), ssrc); break; case VideoSendStream::StreamStats::StreamType::kRtx: uma_container_->rtx_byte_counter_.Set(counters.transmitted.TotalBytes(), ssrc); break; case VideoSendStream::StreamStats::StreamType::kFlexfec: break; } } void SendStatisticsProxy::Notify(uint32_t total_bitrate_bps, uint32_t retransmit_bitrate_bps, uint32_t ssrc) { MutexLock lock(&mutex_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (!stats) return; stats->total_bitrate_bps = total_bitrate_bps; stats->retransmit_bitrate_bps = retransmit_bitrate_bps; } void SendStatisticsProxy::FrameCountUpdated(const FrameCounts& frame_counts, uint32_t ssrc) { MutexLock lock(&mutex_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (!stats) return; stats->frame_counts = frame_counts; } void SendStatisticsProxy::SendSideDelayUpdated(int avg_delay_ms, int max_delay_ms, uint64_t total_delay_ms, uint32_t ssrc) { MutexLock lock(&mutex_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (!stats) return; stats->avg_delay_ms = avg_delay_ms; stats->max_delay_ms = max_delay_ms; stats->total_packet_send_delay_ms = total_delay_ms; uma_container_->delay_counter_.Add(avg_delay_ms); uma_container_->max_delay_counter_.Add(max_delay_ms); } void SendStatisticsProxy::StatsTimer::Start(int64_t now_ms) { if (start_ms == -1) start_ms = now_ms; } void SendStatisticsProxy::StatsTimer::Stop(int64_t now_ms) { if (start_ms != -1) { total_ms += now_ms - start_ms; start_ms = -1; } } void SendStatisticsProxy::StatsTimer::Restart(int64_t now_ms) { total_ms = 0; if (start_ms != -1) start_ms = now_ms; } void SendStatisticsProxy::SampleCounter::Add(int sample) { sum += sample; ++num_samples; } int SendStatisticsProxy::SampleCounter::Avg( int64_t min_required_samples) const { if (num_samples < min_required_samples || num_samples == 0) return -1; return static_cast<int>((sum + (num_samples / 2)) / num_samples); } void SendStatisticsProxy::BoolSampleCounter::Add(bool sample) { if (sample) ++sum; ++num_samples; } void SendStatisticsProxy::BoolSampleCounter::Add(bool sample, int64_t count) { if (sample) sum += count; num_samples += count; } int SendStatisticsProxy::BoolSampleCounter::Percent( int64_t min_required_samples) const { return Fraction(min_required_samples, 100.0f); } int SendStatisticsProxy::BoolSampleCounter::Permille( int64_t min_required_samples) const { return Fraction(min_required_samples, 1000.0f); } int SendStatisticsProxy::BoolSampleCounter::Fraction( int64_t min_required_samples, float multiplier) const { if (num_samples < min_required_samples || num_samples == 0) return -1; return static_cast<int>((sum * multiplier / num_samples) + 0.5f); } SendStatisticsProxy::MaskedAdaptationCounts SendStatisticsProxy::Adaptations::MaskedCpuCounts() const { return Mask(cpu_counts_, cpu_settings_); } SendStatisticsProxy::MaskedAdaptationCounts SendStatisticsProxy::Adaptations::MaskedQualityCounts() const { return Mask(quality_counts_, quality_settings_); } void SendStatisticsProxy::Adaptations::set_cpu_counts( const VideoAdaptationCounters& cpu_counts) { cpu_counts_ = cpu_counts; } void SendStatisticsProxy::Adaptations::set_quality_counts( const VideoAdaptationCounters& quality_counts) { quality_counts_ = quality_counts; } VideoAdaptationCounters SendStatisticsProxy::Adaptations::cpu_counts() const { return cpu_counts_; } VideoAdaptationCounters SendStatisticsProxy::Adaptations::quality_counts() const { return quality_counts_; } void SendStatisticsProxy::Adaptations::UpdateMaskingSettings( VideoStreamEncoderObserver::AdaptationSettings cpu_settings, VideoStreamEncoderObserver::AdaptationSettings quality_settings) { cpu_settings_ = std::move(cpu_settings); quality_settings_ = std::move(quality_settings); } SendStatisticsProxy::MaskedAdaptationCounts SendStatisticsProxy::Adaptations::Mask( const VideoAdaptationCounters& counters, const VideoStreamEncoderObserver::AdaptationSettings& settings) const { MaskedAdaptationCounts masked_counts; if (settings.resolution_scaling_enabled) { masked_counts.resolution_adaptations = counters.resolution_adaptations; } if (settings.framerate_scaling_enabled) { masked_counts.num_framerate_reductions = counters.fps_adaptations; } return masked_counts; } } // namespace webrtc
[ "wuhaiyang1213@gmail.com" ]
wuhaiyang1213@gmail.com
0d1a331a892e08afefe3438fa53483d4e088b313
24b9c758a13a39ae7baba08cf1af1360dba2bb80
/src/utests/include/utests/baselib/UtfCrypto.h
f33dd38a884bead967378da96c6cae3dcd1d68e9
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
thisisdos1984/swblocks-baselib
67a339f44ed63d0170e3f08ccf8ba032643b4c6f
fdab5d0c4f076c361d4d8d35ebb3efd64594b0d0
refs/heads/master
2021-08-14T19:02:32.716949
2017-11-16T14:34:06
2017-11-16T14:34:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,336
h
/* * This file is part of the swblocks-baselib library. * * 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. */ #ifndef __TEST_UTFCRYPTO_H_ #define __TEST_UTFCRYPTO_H_ #include <baselib/crypto/CryptoBase.h> #include <baselib/core/OS.h> #include <baselib/core/Logging.h> #include <baselib/core/BaseIncludes.h> namespace test { template < typename E = void > class UtfCryptoT { BL_DECLARE_STATIC( UtfCryptoT ) public: static auto getDevRootCA() -> const char* { /* * This is from following file: "certs/test-root-ca.pem" */ return "-----BEGIN CERTIFICATE-----\n" "MIIDaDCCAlACCQDWlKTpe/DKXjANBgkqhkiG9w0BAQsFADB2MQswCQYDVQQGEwJV\n" "UzERMA8GA1UECAwITmV3IFlvcmsxDDAKBgNVBAcMA05ZQzEXMBUGA1UECgwOTXkg\n" "Q29tcGFueSBMdGQxLTArBgNVBAMMJE15IENvbXBhbnkgTHRkIFRlc3QgUm9vdCBD\n" "ZXJ0aWZpY2F0ZTAeFw0xNzEwMjAwMzUwNDFaFw0yNzA4MjkwMzUwNDFaMHYxCzAJ\n" "BgNVBAYTAlVTMREwDwYDVQQIDAhOZXcgWW9yazEMMAoGA1UEBwwDTllDMRcwFQYD\n" "VQQKDA5NeSBDb21wYW55IEx0ZDEtMCsGA1UEAwwkTXkgQ29tcGFueSBMdGQgVGVz\n" "dCBSb290IENlcnRpZmljYXRlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC\n" "AQEAslipXTEu/Tf2YsVx50D1bZRbksk+6jl0LVyJtjuhlcJS+SwWXEH03prTXoYu\n" "+ocEzVvhkA+gmwpt0tqwewdbip42JCT7mrALn82VngTLuwX99jKsBvkzM0NlwK6F\n" "++d6yb561Aq84jTumL33tCh83TdOPI5x3giAx8fVNh2Mt8dhj9DgLXnwyMQTeluG\n" "ABruWna9gUPlYOeZzBrqaio+nSFFTw7shE6lPltTCb/0LRNPhGWhBUqy0JioRseP\n" "VAvbOKffW8veV5WnUTFdP8yBh0dWt4rA3bQIjJK4M6SEx2FJ2xc7D2yVED3uzV5G\n" "BF3Fm/8syl6lctpGOmSZtAUxbQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQBS2x4n\n" "xVyLM8gPhBgufheSfcv04XZDSDGnMFXyNYBiRmWjoR11jHhRt6z8Chc+08yuPxM1\n" "JnYbczf3MRQVIwLnPaU83C9hNvyx8Haneavb2csHnbVV43Lqxt58hARL1h+loOxs\n" "Ef/4eWspyTl6Gne0dwF7nvaASRjGUDJkIsAFPnGD045UH6OLKl4p8zlHblW4B1es\n" "j2ebkKwTGJYKIcO7dZHcxtosZsJ8sRHKKlFyIDSKzVDrdRFTnPRR06zTBZ83KfYy\n" "p5mWNQQHsQp0wtUTLdYWjMnJBvo1JtAKeYv76ZoBvYcJiJWlnjYCtRq5hOD5Y6ct\n" "X7k2o4k7mtEpT5+B\n" "-----END CERTIFICATE-----\n"; } static auto getDefaultServerKey() -> const char* { /* * This is from following file: "certs/test-server-key.pem" */ return "-----BEGIN PRIVATE KEY-----\n" "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDF04YyIhEtTecw\n" "51Xy9Z9kyVsdS7Tr19fTsUVCaFJiDL7KfR9loVSQzlvT/M1xZhePkZISZzQ0Ixi+\n" "CTLwF+SzSSCD81KjDHqeRcuRetJgz4afnAq9QsgtET7cIeVyBk6sz+CheBJmOyii\n" "TDfgZBaPjN1tVqTN4Hz+whavXeXw0kTqrEPuR1ba0kbCjyU3jjFg75iu1nfwEo+K\n" "kizgBSbBdWreiZJQf25q5c9yrPqBe/WSx2/QZfYs24Nehm2jCAUZyk0bh4cr4aRJ\n" "QoFUzpAo15Vl8kD2msUJnS5Y5a9wc/8u1Q3OJotvJ2AN45g0xGyqSwCjIiXnBFeT\n" "/estF/VPAgMBAAECggEAdoXp0+WHRw5yomEnpJ42tmrRVTcDmX3DSIjgBw57tVUP\n" "hj/67KgBA5UvfU3sRLG3EgRUcQQ2SbpxW4Ila6XVFvmMKqJA84FJgcQtV+cvXmNX\n" "tA8IfCYjyqSXdco1LuDKiE0vt246D9gH210w6RbuUWlDTPvpV5PVL8lXUBBA8Mvr\n" "CJus47wq58U0WK2AF6CABcGFnSY9JiJavdZpAlgaO54sIq5YdZORJ8pbk5IjXybR\n" "TGTL3IBpuB8RIo4zO9dDvuE1zxBj2FgSTNoo3IsGoIrpInaT2SWGtv04sBrMIbFl\n" "B/mkkEzONf2OOmZ0NLPfnZdj4tejyxGq4woYgbLUkQKBgQD45bEHBIHBtKHuIv0d\n" "1Y20OVfjQJOTc2bQUNj7f8WeHrINYBYes3jRuf9LDAFDUYZyesOMGjEUcAnpWuha\n" "4mHJJqj5r1R9dIpaW8L1ABcV931t1j7aEnq1E/VdRTM+iUR+rUHRzYid+p3CgqLx\n" "SMEnDomeDjRGCw8LKcAuVSwaJwKBgQDLeLxglju0Rm21tRE0oSEYwStkkVhmP4gL\n" "nDeRMvephgPDTTXWrP4eV2mvynH0/+t+pwbDWHM1q4XrCBnVX/bGpqqOgoPuAj2x\n" "wY1BMTDoUlG9VO7koJWM0SN3gyZeOicykpMKszYfWkOoETQ1U49LrOIFJRx192xR\n" "WIvpvXmMmQKBgQC6ZYnF76IdJuF+LcXRafTNW4RuNBZQ/sOojmNxNacRW3uMeMEY\n" "DOAWcGy4Dy2C9LLzWOzJJ3RKEf3aPLJ2HcONmN5C3wMvUO+r67x9LqwbT1UnxKMd\n" "PWmX4nKGfyR5WONq2uXH8Vy2stEisiLE/+9nCIQXUhvjuLRzb7j0+eQlUQKBgDCF\n" "6X6rNS/Hv/Aebyz65BawMnX4R3mS2xHRvlqtKezOneUca6N3e96mf/jBMa34viNl\n" "F7LMTCVXc0daljaRfRtgsbnsnCPNewMCInqSjZRJ1V5ue84gEaoUUf31U9gSzDg+\n" "Rjy+AkE12H6jI6038Std3kTV1dS4HafEkxE581u5AoGAIgoxxG5L1tOq7FOycPgJ\n" "EeN2e81PgAVesy0fsemlXxoobXpnftT3uPn5Zpo/yVwUXbmCzRahblgljAMK19TY\n" "HNieCuaJCnml/NQz4Atzq+AhOczo3eK1v6wgkWBDDSqu7CahEu0ndarDI6Xfa3Pc\n" "RIGnam24+CSu1F4r2xiy2XA=\n" "-----END PRIVATE KEY-----\n"; } static auto getDefaultServerCertificate() -> const char* { /* * This is from following file: "certs/test-server-cert.pem" */ return "-----BEGIN CERTIFICATE-----\n" "MIIDlzCCAn+gAwIBAgIBATANBgkqhkiG9w0BAQsFADB2MQswCQYDVQQGEwJVUzER\n" "MA8GA1UECAwITmV3IFlvcmsxDDAKBgNVBAcMA05ZQzEXMBUGA1UECgwOTXkgQ29t\n" "cGFueSBMdGQxLTArBgNVBAMMJE15IENvbXBhbnkgTHRkIFRlc3QgUm9vdCBDZXJ0\n" "aWZpY2F0ZTAeFw0xNzEwMjAwMzUyMzRaFw0yNzA4MjkwMzUyMzRaMGMxCzAJBgNV\n" "BAYTAlVTMREwDwYDVQQIDAhOZXcgWW9yazEMMAoGA1UEBwwDTllDMRcwFQYDVQQK\n" "DA5NeSBDb21wYW55IEx0ZDEaMBgGA1UEAwwRKi4qLm15Y29tcGFueS5jb20wggEi\n" "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDF04YyIhEtTecw51Xy9Z9kyVsd\n" "S7Tr19fTsUVCaFJiDL7KfR9loVSQzlvT/M1xZhePkZISZzQ0Ixi+CTLwF+SzSSCD\n" "81KjDHqeRcuRetJgz4afnAq9QsgtET7cIeVyBk6sz+CheBJmOyiiTDfgZBaPjN1t\n" "VqTN4Hz+whavXeXw0kTqrEPuR1ba0kbCjyU3jjFg75iu1nfwEo+KkizgBSbBdWre\n" "iZJQf25q5c9yrPqBe/WSx2/QZfYs24Nehm2jCAUZyk0bh4cr4aRJQoFUzpAo15Vl\n" "8kD2msUJnS5Y5a9wc/8u1Q3OJotvJ2AN45g0xGyqSwCjIiXnBFeT/estF/VPAgMB\n" "AAGjQzBBMAkGA1UdEwQCMAAwCwYDVR0PBAQDAgXgMCcGA1UdEQQgMB6CESouKi5t\n" "eWNvbXBhbnkuY29tgglsb2NhbGhvc3QwDQYJKoZIhvcNAQELBQADggEBAC2ewdhS\n" "ZN7SOABj+X/ISgmOouo9sewyL0X5OGR+mbmTwTDMTqJciDD38TLGv6Y842xK2zz0\n" "y6ham7T4gsWyJ+nkvdAj+st92JOj7ToLRiVRQXyq9jKSd4i4k//30zJ1x5jbZ8Gm\n" "RbJG38Lh1YC+yMpGekQ+MLoThMR0AqCiFN71bfgobWjRltiAfSX1T6liryAZxTis\n" "KtfHPQA83pLPP+IOJK4ntzVZ0QEgoEb9oXKGQyRBMaEYgFEvEuG7yxoBgzDz6hlA\n" "zk1qQnfoZVIurDq5N+g2hyeWJY/Uo+IkOoeB+EC4LXFav7bvPI7MBSCseie7IC8E\n" "fK6Vl0UXcuz5VIU=\n" "-----END CERTIFICATE-----\n"; } }; typedef UtfCryptoT<> UtfCrypto; } // test #endif /* __TEST_UTFCRYPTO_H_ */
[ "lazar.i.ivanov@jpmorgan.com" ]
lazar.i.ivanov@jpmorgan.com
b526ecf0f70cbf5661d5dbfebb7c1c13fa2aa1a1
fc47d7e4c8462f646a5cb3428be1d22ea61fb531
/worker_calculations.cpp
a05f200f98aba0e64c02b6214b8cf2bcf6788be1
[]
no_license
alperenunuvar/Cpp-Exercises
180ec783db09735deb6824e94f179781a081100d
8d67d8ce55dd6042205cb2a16ef9abe94159b3fd
refs/heads/master
2020-03-28T08:36:01.265105
2019-03-29T23:02:00
2019-03-29T23:02:00
147,975,962
2
0
null
null
null
null
UTF-8
C++
false
false
340
cpp
#include <iostream> using namespace std; int main() { // Variables int day; int numOfWorker; int total; cout << "Enter number of day = " << endl; cin >> day; cout << "Enter number of worker = " << endl; cin >> numOfWorker; total = day / numOfWorker; cout << "Time of work = " << total << endl; return 0; }
[ "noreply@github.com" ]
alperenunuvar.noreply@github.com
3e550d22f1f76cf44cc08207e7bd7845dff9f9e4
8fe2e38fd3f23f58dd0f35d1f351601f8a723e07
/3party/boost/boost/fusion/container/vector/detail/cpp03/vector50.hpp
45a1fc9bbc9f9ada8f081cead0d9410cb77c5ff2
[ "BSL-1.0", "Apache-2.0" ]
permissive
ruilin/RLMap
cb139b7fb3020b163a6857cfa6b98f0c930f2a45
e16b52f77d165e719b3af20b097f227959e8e374
refs/heads/master
2022-10-06T10:11:39.760428
2019-11-22T01:03:27
2019-11-22T01:03:27
97,201,756
2
1
Apache-2.0
2022-10-04T23:29:25
2017-07-14T06:39:33
C++
UTF-8
C++
false
false
3,086
hpp
/*============================================================================= 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) ==============================================================================*/ #if !defined(FUSION_VECTOR50_05052005_0207) #define FUSION_VECTOR50_05052005_0207 #include <boost/fusion/support/config.hpp> #include <boost/fusion/container/vector/detail/cpp03/vector50_fwd.hpp> #include <boost/fusion/support/sequence_base.hpp> #include <boost/fusion/support/is_sequence.hpp> #include <boost/fusion/support/detail/access.hpp> #include <boost/fusion/iterator/next.hpp> #include <boost/fusion/iterator/deref.hpp> #include <boost/fusion/sequence/intrinsic/begin.hpp> #include <boost/fusion/container/vector/detail/at_impl.hpp> #include <boost/fusion/container/vector/detail/value_at_impl.hpp> #include <boost/fusion/container/vector/detail/begin_impl.hpp> #include <boost/fusion/container/vector/detail/end_impl.hpp> #include <boost/mpl/void.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/at.hpp> #include <boost/mpl/bool.hpp> #include <boost/mpl/vector/vector50.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/utility/enable_if.hpp> #include <boost/preprocessor/dec.hpp> #include <boost/preprocessor/iteration/iterate.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/preprocessor/repetition/enum_shifted.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_binary_params.hpp> #include <boost/preprocessor/repetition/repeat_from_to.hpp> #if !defined(BOOST_FUSION_DONT_USE_PREPROCESSED_FILES) #include <boost/fusion/container/vector/detail/cpp03/preprocessed/vector50.hpp> #else #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 2, line: 0, output: "preprocessed/vector50.hpp") #endif /*============================================================================= 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 namespace boost { namespace fusion { struct vector_tag; struct fusion_sequence_tag; struct random_access_traversal_tag; #define FUSION_HASH # // expand vector41 to vector50 #define BOOST_PP_FILENAME_1 <boost/fusion/container/vector/detail/cpp03/vector_n.hpp> #define BOOST_PP_ITERATION_LIMITS (41, 50) #include BOOST_PP_ITERATE() #undef FUSION_HASH }} #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(output: null) #endif #endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES #endif
[ "zruilin@126.com" ]
zruilin@126.com
d25196095ed93244886ddcf926219a0afa8db43a
92c0acf18263a4a0711f956de5e0878609dbe510
/Concerts/src/Recinto.cpp
225ed2313588cce45d070de896fd15b6f1422455
[]
no_license
Gianca98alv/University-projects
54f6faaade63aa87562b29da794e45cf4c98a5e3
3367a7c601b4eeb2068d39bd6c70af94b3e515fb
refs/heads/master
2022-11-17T05:09:51.405249
2020-07-09T22:23:33
2020-07-09T22:23:33
278,002,384
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,412
cpp
#include "Recinto.h" Recinto::Recinto(string o, string d, int du) : lugar(o), telonero(d), duracion(du) {}//Constructor con parámetros void Recinto::col(int c){ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), c); }//Recibe un número al cual le corresponde un color y lo muestra en el texto. //Sets y Gets de los Atributos void Recinto::setLugar(string o) { lugar = o; } void Recinto::setTelonero(string d) { telonero = d; } void Recinto::setDuracion(int d) { duracion = d; } string Recinto::getLugar() { return lugar; } string Recinto::getTelonero() { return telonero; } int Recinto::getDuracion() { return duracion; } //Une la cadena(string) que se encuentre en el atributo lugar con la del atributo telonero y devuelve una nueva cadena (string) conformada por estas dos. Además las coloca en mayúscula. string Recinto::sumaRecinto(){ string cadena = lugar + "-" + telonero; for (int i = 0; cadena[i]; i++) cadena[i] = toupper(cadena[i]); return cadena; } //Muestra los valores de los atributos. string Recinto::toString() { stringstream s; s << "\nLugar del Concierto: \n"; s << lugar << "\n"; s << "Nombre del Telonero:\n"; s << telonero << "\n"; s << "Duracion del show:\n"; if (duracion == 1) { s << duracion << " hora\n"; } else { s << duracion << " horas\n"; } return s.str(); } //Destructor Recinto::~Recinto(){ lugar = " "; telonero = " "; duracion = 0; }
[ "Giak98cr@users.noreply.github.com" ]
Giak98cr@users.noreply.github.com
f1bcf63dc93a38c4b7d518d0e59adb555f77eb95
d9498efe82438a1c74d45f5c9b826985bd6f0fe7
/1253 A. Single Push.cpp
908f06f860aff58078316fed3adff6768eddc8b7
[ "Apache-2.0" ]
permissive
upadrastaharshavardhan/programing_quections-_c-
c7476d4ea416aca5c83388254d1930de2ef3604a
7aa1669e3b39e91c681b6b9e1e3b47f4cfecb780
refs/heads/main
2023-08-23T10:45:28.933927
2021-10-28T13:31:17
2021-10-28T13:31:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,598
cpp
#include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define pb push_back #define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL)); using namespace std; int main() { fastread(); //freopen("input.txt","r", stdin); ll t,n,a[100001],b[100001]; cin>>t; while(t--){ cin>>n; for(ll i=0; i<n; i++){ cin>>a[i]; } for(ll i=0; i<n; i++) cin>>b[i]; ll l = 100001,r = 0; bool flag = false; for(ll i=0; i<n; i++){ if(a[i] == b[i])continue; else if(a[i] > b[i]){ flag = true; break; } else if(a[i] < b[i]){ l = min(l,i); r = max(r,i); } } if(flag){ cout<<"NO"<<endl; } else if( (flag == false) && (l == 100001 && r == 0)){ cout<<"YES"<<endl; } else{ set<ll>s; for(ll i=l; i<=r; i++){ if(a[i] > b[i] || a[i] == b[i]){ flag = true; break; } else{ ll dif = abs(a[i] - b[i]); s.insert(dif); } } if(flag == true || s.size() > 1){ cout<<"NO"<<endl; } else{ cout<<"YES"<<endl; } } } return 0; }
[ "noreply@github.com" ]
upadrastaharshavardhan.noreply@github.com
b943dac84f80aebc463b2fda7a8dee8188a767e8
20e9c4fae9489f336ffd2c1a2fa5b458909c9963
/utils/communication/protocol.h
eac5be5c2bd4feb53951138691ef8ec1c35c3529
[]
no_license
illini-robomaster/iRM_Autonomy_2020
94e937054e687c54b4678baaf2fbf5310a0c6eb8
a12993ce3df876a99e18503555352b09dbc9e402
refs/heads/master
2022-01-19T23:06:59.482609
2021-01-15T03:06:01
2021-01-15T03:06:01
216,278,270
7
4
null
2021-01-15T03:08:03
2019-10-19T22:29:43
Jupyter Notebook
UTF-8
C++
false
false
1,381
h
#pragma once #include <vector> #include <cinttypes> namespace communication { typedef struct { uint8_t sof; uint16_t data_length; uint8_t sequence_id; } __attribute__((packed)) header_t; typedef struct { uint16_t command_id; uint8_t data[1]; } __attribute__((packed)) body_t; /** * @brief calculate full size of encoded packet given data length * * @param data_length length of the actual message data [in bytes] * * @return full size [in bytes] of the encoded packet */ size_t get_packet_size(uint16_t data_length); /** * @brief encode data based on protocol * * @param command_id command id * @param data start address of the data stream * @param length length of data [in bytes] * * @return encoded byte array */ std::vector<uint8_t> encode(uint16_t command_id, void *data, uint16_t length); /** * @brief decode header data * * @param data start address of the entire encoded packet * * @return pointer to a header struct if valid, otherwise NULL */ header_t* decode_header(uint8_t *data); /** * @brief decode body data * * @param data start address of the entire encoded packet * @param data_length length of the actual message data [in bytes] * * @return pointer to a body struct if valid, otherwise NULL */ body_t* decode_body(uint8_t *data, uint16_t data_length); } /* namespace communication */
[ "alvinsunyixiao@gmail.com" ]
alvinsunyixiao@gmail.com
e72ae1bc1fb0dc3f568fac0a6f4e5704b35e5ade
12baf55322ef4582d5e0f895365bd8789086c4da
/src/libraries/Adafruit_Circuit_Playground/utility/IRLib_HashRaw.h
e675ff9bffb50dd695bc4d6bfc4b04b3fcaae47b
[ "MIT", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference", "GPL-3.0-only" ]
permissive
Corfucinas/arduino-sketchbook
056ede8c112b528ca7a731ebf05a1207b94b993a
6cc2f1da8cbbe50c471ca9568d9379ff39f37d72
refs/heads/master
2023-03-31T16:22:36.625447
2021-04-09T13:12:51
2021-04-09T13:12:51
291,946,220
2
0
MIT
2021-04-09T13:12:52
2020-09-01T08:50:42
C++
UTF-8
C++
false
false
3,546
h
/* IRLib_P00_HashRaw.h * Part of IRLib Library for Arduino receiving, decoding, and sending * infrared signals. See COPYRIGHT.txt and LICENSE.txt for more information. */ /* * If you have a protocol which is unsupported by this library, you can still receive * and transmit the data. You can store the raw data values in a buffer and retransmit the * data exactly as you received it. Of course it takes a lot of memory to store such data * so it is inefficient but it is better than nothing. * If all you need to do is detect a unique value for an unsupported protocol and you do * not need to resend the data, you can use the hash code decoder. It looks at the * array of raw timing values and create a 32 bit value based on the data. It is * highly likely to be unique however you cannot reverse engineer the process. * You cannot re-create the original data stream for 32 bit hash code. * This module also implements the raw send method. You have to have the original * timing values. */ #ifndef IRLIB_HASHRAW_H #define IRLIB_HASHRAW_H #define IR_SEND_RAW case 0: IRsendRaw::send((uint16_t*)data,data2,khz); break; #define IR_DECODE_HASH if(IRdecodeHash::decode()) return true; #ifdef IRLIB_HAVE_COMBO #define PV_IR_DECODE_HASH ,public virtual IRdecodeHash #define PV_IR_SEND_RAW ,public virtual IRsendRaw #else #define PV_IR_DECODE_HASH public virtual IRdecodeHash #define PV_IR_SEND_RAW public virtual IRsendRaw #endif #ifdef IRLIBSENDBASE_H /* The first parameter to the "IRendRaw" method is a pointer to the first element of an * array of uint16_t values. These values are the raw timing values in microseconds. Note * it is possible to simply pass "(uint16_t*) &My_Decoder.decodeBuffer[1]" if you have just * received a code and wish to echo it. You have to point to the index "1" because index "0" * of that buffer contains the gap between successive frames data and it should be ignored. * If the frequency to be used in transmission is not specified, it defaults to 38kHz. */ class IRsendRaw: public virtual IRsendBase { public: void send(uint16_t *buf, uint8_t len, uint8_t khz) { enableIROut(khz); for (uint8_t i = 0; i < len; i++) { if (i & 1) { space(buf[i]); } else { mark(buf[i]); } } space(0); // Just to be sure } }; #endif //IRLIBSENDBASE_H #ifdef IRLIBDECODEBASE_H /* This Hash decoder is based on IRhashcode Copyright 2010 Ken Shirriff * For details see http://www.righto.com/2010/01/using-arbitrary-remotes-with-arduino.html * Use FNV hash algorithm: http://isthe.com/chongo/tech/comp/fnv/#FNV-param * Converts the raw code values into a 32-bit hash code. * Hopefully this code is unique for each button. */ #define FNV_PRIME_32 16777619 #define FNV_BASIS_32 2166136261 // Compare two tick values, return 0 if v1 is lower, 1 if equal, and 2 if v2 is higher #define TICKS_COMPARE(v1,v2) ( (v2< v1*0.8)?0:( (v1< v2*0.8)?2:1) ) class IRdecodeHash: public virtual IRdecodeBase { public: bool decode(void) { value = FNV_BASIS_32; for (int i = 1; i+2 < recvGlobal.decodeLength; i++) { value = (value * FNV_PRIME_32) ^ TICKS_COMPARE(recvGlobal.decodeBuffer[i], recvGlobal.decodeBuffer[i+2]); } protocolNum = UNKNOWN; bits= (recvGlobal.decodeLength-3)/2;//Estimated number of bits of unknown protocol //Note that value is always 32 bit hash code. return true; } }; #endif //IRLIBDECODEBASE_H #define IRLIB_HAVE_COMBO #endif //IRLIB_HASHRAW_H
[ "53630064+Corfucinas@users.noreply.github.com" ]
53630064+Corfucinas@users.noreply.github.com