blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
6dd924f8ba9d5a4799ae262172e744a4f11861f3
35be95e5e4ef306a1203a173bed12599f62db7b6
/SlimDXc_Jun2010(VC++2008)/source/direct2d/RadialGradientBrushProperties.cpp
0f10650a2fba0d82ceb731e87438d688c1740db5
[ "MIT" ]
permissive
Orz5566/RandomTest
dd0ec2eb7a0db3993409c2a647658a175a3b4027
2884f99d29dda603c646d464a60d7bce3346b74d
refs/heads/master
2021-09-06T01:10:29.460192
2018-02-01T06:56:53
2018-02-01T06:56:53
118,869,777
0
0
null
null
null
null
UTF-8
C++
false
false
1,313
cpp
/* * Copyright (c) 2007-2012 SlimDX Group * * 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 <d2d1.h> #include <d2d1helper.h> #include "Direct2DException.h" #include "RadialGradientBrushProperties.h" using namespace System; namespace SlimDX { namespace Direct2D { } }
[ "32087037+Orz5566@users.noreply.github.com" ]
32087037+Orz5566@users.noreply.github.com
fa1cfa689e6819698c70c315799e7a5ff5d017f4
08b7ded786a247113dca43938f253b2568a935d3
/gui/widget/notification_info_widget.h
ff633ad98993e9c62efdc0c789d9e83b96b5ffa7
[]
no_license
QtWorks/SmartHome
8be750595f2b94a8306439adba6a76983b9d8125
f83cc5516cc2fe9933d7b50266be41e6aad00afa
refs/heads/master
2021-01-24T02:47:48.703728
2017-11-17T15:01:12
2017-11-17T15:01:12
122,862,654
1
1
null
2018-02-25T18:16:22
2018-02-25T18:16:22
null
UTF-8
C++
false
false
772
h
#ifndef NOTIFICATION_INFO_WIDGET_H #define NOTIFICATION_INFO_WIDGET_H #include "scalable_widget.h" #include <QTimer> class NotificationInfoWidget : public ScalableWidget { Q_OBJECT QPixmap m_icon; QString m_date_time; QString m_information; int m_border_roudness{10}; QTimer* m_blink_timer; bool m_toggled{true}; bool m_severe{false}; private slots: void toggleBlink(); public: explicit NotificationInfoWidget(QWidget* parent, QSize base_size); void setIcon(const QPixmap& icon); void setDateTime(const QString& date_time); void setInformation(const QString& information); void setBorderRoundess(int border_roundess); void setSevere(bool severe); protected: void paintEvent(QPaintEvent*); }; #endif
[ "rskrobo1@etf.unsa.ba" ]
rskrobo1@etf.unsa.ba
81a9177dc8bfc7319280eb81b48041f970414c2d
edda021b328841d86973f09e7b7278f7629d0380
/IM/IM_TV/imm_baseline/im_benchmarking-master/sidm029_im_benchmark/Codes/TIM_test/src/tim.cpp
568e6d28fac3d34929709f0bf1fe53483b4f85a4
[]
no_license
wenyixue/GCOMB
b5ad36dd9e55131169c1ef10a18f2323c4732001
ee2ed06b8db8fa66bab52f6c7026b3cc4bd0a289
refs/heads/master
2023-05-13T23:54:57.123031
2021-05-18T03:20:36
2021-05-18T03:20:36
368,171,392
0
0
null
2021-05-17T12:07:58
2021-05-17T12:07:57
null
UTF-8
C++
false
false
3,917
cpp
//#define HEAD_TRACE #define HEAD_INFO #define HEAD_INFO //#define HEAD_TRACE #include "sfmt/SFMT.h" #include "head.h" #include "memoryusage.h" #include "graph.h" #include <string> void run(TimGraph & m, string dataset, string outdir, int k, double epsilon, string model ){ ofstream seedFile, outputFile, statFile; string outputFilename, statFilename, seedFilename; //double epsilonPrint = floor(epsilon *100.)/100.; char epsilonConvert[64]; double epsilonPrint; sprintf(epsilonConvert, "%.*g", 2, epsilon); epsilonPrint = strtod(epsilonConvert, 0); outputFilename = outdir + "/" + "output_TIM_" + model + "_" + to_string(k)+"_"+epsilonConvert + ".txt"; outputFile.open (outputFilename.c_str()); outputFile << "dataste:" << dataset << " k:" << k << " epsilon:"<< epsilonPrint << " model:" << model << endl; m.k=k; if(model=="IC") m.setInfuModel(InfGraph::IC); else if(model=="LT") m.setInfuModel(InfGraph::LT); else ASSERT(false); outputFile<<"Finish Read Graph, Start Influecne Maximization"<<endl; clock_t time_start = clock(); m.EstimateOPT(epsilon); clock_t time_end = clock(); outputFile<<"Time used: " << Timer::timeUsed[100]/TIMES_PER_SEC << "s" <<endl; outputFile<<"Selected k SeedSet: "; for(auto item:m.seedSet) outputFile<< item << " "; cout<<endl; outputFile<<"Estimated Influence: " << m.InfluenceHyperGraph() << endl; Counter::show(); //Added by Sigdata statFilename = outdir + "/" + "stat_TIM_" + model + "_" + to_string(k)+"_"+epsilonConvert + ".txt"; seedFilename = outdir + "/" + "seeds_TIM_" + model + "_" + to_string(k)+"_"+epsilonConvert + ".txt"; statFile.open (statFilename.c_str()); seedFile.open (seedFilename.c_str()); for(auto item:m.seedSet) seedFile<< item << endl; //statFile<<m.InfluenceHyperGraph()<<" "<<Timer::timeUsed[100]/TIMES_PER_SEC<<" "<< disp_mem_usage("")<<endl;//Add memory usage and check time statFile<<m.InfluenceHyperGraph()<<" "<<(float)(time_end - time_start) / CLOCKS_PER_SEC<<" "<< disp_mem_usage("")<<endl;//Add memory usage and check time statFile.close(); seedFile.close(); outputFile.close(); } void parseArg(int argn, char ** argv) { string dataset=""; double epsilon=0; string model=""; int k=0; string outdir=""; for(int i=0; i<argn; i++) { if(argv[i]==string("-dataset")) dataset=string(argv[i+1]);//Modified by Sigdata +"/"; if(argv[i]==string("-outdir")) outdir=string(argv[i+1]);//Added by Sigdata +"/"; if(argv[i]==string("-epsilon")) epsilon=atof(argv[i+1]); if(argv[i]==string("-k")) k=atoi(argv[i+1]); if(argv[i]==string("-model")) { if(argv[i+1]==string("LT")) { model=argv[i+1]; } else if(argv[i+1]==string("IC")) { model=argv[i+1]; } else ExitMessage("model should be IC or LT"); } } if (dataset=="") ExitMessage("argument dataset missing"); if (k==0) ExitMessage("argument k missing"); if (epsilon==0) ExitMessage("argument epsilon missing"); if (model=="") ExitMessage("argument model missing"); string graph_file; /*if(model=="IC") graph_file=dataset + "graph_ic.inf"; else if(model=="LT") graph_file=dataset + "graph_lt.inf"; */ graph_file =dataset; //Extract folder from dataset to get the folder std::size_t found = dataset.find_last_of("/"); dataset = dataset.substr(0,found+1); //cout<<"folder is "<<dataset<<" "<<found<<endl; TimGraph m(dataset, graph_file); run(m, dataset, outdir, k , epsilon, model ); } int main(int argn, char ** argv) { OutputInfo info(argn, argv); parseArg( argn, argv ); }
[ "sahilm1992@gmail.com" ]
sahilm1992@gmail.com
c7dee16e5425a029d2ac10b403d1369c19193875
0af9965de7527f4ca341833a5831dacd3fb8373f
/LeetCode/range-sum-query-immutable.cpp
296d8efce91b7909bfab1d9e042fb131c9f94faa
[]
no_license
pcw109550/problem-solving
e69c6b1896cedf40ec50d24c061541035ba30dfc
333d850a5261b49f32350b6a723c731156b24b8a
refs/heads/master
2022-09-18T08:25:16.940647
2022-09-12T10:29:55
2022-09-12T10:29:55
237,185,788
11
1
null
2022-09-12T10:18:49
2020-01-30T10:05:42
C++
UTF-8
C++
false
false
931
cpp
// 303. Range Sum Query - Immutable #include <iostream> #include <vector> class NumArray { public: std::vector<int> D; NumArray(std::vector<int>& nums) { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); // O(N) D.emplace_back(0); for (int i = 0; i < nums.size(); i++) { D.emplace_back(D.back() + nums[i]); } } int sumRange(int i, int j) { // O(1) return D[j + 1] - D[i]; } }; int main(void) { std::vector<int> nums {-2, 0, 3, -5, 2, -1}; NumArray *obj = new NumArray(nums); int param_1 = obj->sumRange(0, 2); std::cout << param_1 << std::endl; int param_2 = obj->sumRange(2, 5); std::cout << param_2 << std::endl; int param_3 = obj->sumRange(0, 5); std::cout << param_3 << std::endl; }
[ "pcw109550@gmail.com" ]
pcw109550@gmail.com
7208812ace4f7a2d45f417a66cdee2da1204ddbb
14cc4da540a1bec830aaa5d1f822785195ce632c
/ip2016/image.h
69e836d60fa135e23ece2b6ccc38002a285c6f02
[]
no_license
Dannnno/RealTimeHatching
0cc94d105c9d79ef0c7dc1cc42f1abcd9ee933b7
699cbb80daf971e7388848b17fad0190d07f3a80
refs/heads/master
2016-09-12T20:24:00.132760
2016-05-11T22:30:46
2016-05-11T22:30:46
56,352,838
0
0
null
null
null
null
UTF-8
C++
false
false
3,302
h
class Image; #ifndef IMAGE_H #define IMAGE_H #include <fstream> #include "common.h" using namespace std; /* * definitions for channel values. for example, * image->getPixel(0,0,GREEN); * gets the green value at pixel 0,0 in image. */ #define RED 0 #define GREEN 1 #define BLUE 2 /* * struct to contain an entire pixel's data, up to three channels. if * only one channel then all bur r values in * this struct will be ignored. */ class Pixel { public: Pixel (); Pixel (double r, double g, double b); Pixel (const Pixel& toCopy); Pixel& operator=(const Pixel& toCopy); ~Pixel (); double getColor(int chan); void setColor(int chan, double value); private: double col[3]; }; ostream &operator<<(ostream &out_file, Pixel& thePixel); /* * generic multi channel 8-bit max image class. can read and write * 8 and 24 bit uncompressed BMP files and supports some useful OpenGL * calls. * * get and set pixel methods use doubles from 0.0 to 1.0. these * values are mapped to integer values from 0 to the maximum value * allowed by the number of bits per channel in the image. */ class Image { public: Image (); ~Image (); // create empty image with specified characteristics Image (int width_, int height_); Image (int width_, int height_, int bits_); // create image and read data from filename // use good() or bad() to check success Image (const char* filename); // copy constructor and assignment operator // _deep_ copy! Image (const Image& image); Image& operator= (const Image& image); // accessors int getWidth () { return width; } int getHeight () { return height; } int getBits () { return bits; } // check if the image is valid bool good (); bool bad (); // set all the pixel data to zero void clear (); // retrieve pixel data. methods with _ at the // end of their name return 0.0 if the x and y // coordinates are out of range. the functions // without a _ give an assertion failur for out // of bounds coordinates double getPixel (int x, int y, int channel); double getPixel_ (int x, int y, int channel); Pixel getPixel (int x, int y); Pixel getPixel_ (int x, int y); Pixel& getPixel (int x, int y, Pixel& pixel); Pixel& getPixel_ (int x, int y, Pixel& pixel); // set pixel data. set is ignored by functions with a _ // at the end of the name when the coordinates or the pixel // value are out of bounds. the functions without an _ // after the name give an assertion failure for out of // bounds // void setPixel (int x, int y, int channel, double value); void setPixel_ (int x, int y, int channel, double value); void setPixel (int x, int y, Pixel& pixel); void setPixel_ (int x, int y, Pixel& pixel); void fillImage(Pixel p); double getTone(); // OpenGL call wrappers void glDrawPixelsWrapper (); void glTexImage2DWrapper (); void glReadPixelsWrapper (); // file read and write calls, // determines file type int readBMP (const char* filename); int writeBMP (const char* filename); private: int index(int x, int y, int c); int width; int height; int bits; // number of bits per pixel per channel int maxValue; // max that can be stored in bits unsigned char* pixels; // image data }; #endif // IMAGE_H
[ "samuel.l.warren@gmail.com" ]
samuel.l.warren@gmail.com
1639fba156624763923f997702a4555793619058
a8e5517df264ca12e84c377270574a3cc378f0c1
/LAVIDA/1183/solution.cpp
fb49bba0cf5e2cb051f01ed3674bf1c09c56a67a
[]
no_license
wowoto9772/Hungry-Algorithm
cb94edc0d8a4a3518dd1996feafada9774767ff0
4be3d0e2f07d01e55653c277870d93b73ec917de
refs/heads/master
2021-05-04T23:28:12.443915
2019-08-11T08:11:39
2019-08-11T08:11:39
64,544,872
1
1
null
null
null
null
UTF-8
C++
false
false
858
cpp
#include <stdio.h> #include <limits.h> #include <algorithm> #define ll long long using namespace std; int I[5003]; ll A(ll a){ return a < -a ? -a : a; } ll mm(ll a, ll b){ return a < b ? a : b; } int main() { int n; while (scanf("%d", &n) == 1){ for (int i = 1; i <= n; i++)scanf("%d", &I[i]); sort(I + 1, I + 1 + n); int L = 1, R = n; ll ans = INT_MAX * 3LL; int x = -1, y = -1, z = -1; for (int L = 1; ans && L <= n - 2; L++){ for (int R = L + 2; ans && R <= n; R++){ int l = L + 1, r = R - 1, m; ll cmp = I[L] + I[R]; while (l <= r && ans){ m = (l + r) / 2; ll cnt = cmp + I[m]; ll k = A(cnt); if (cnt < 0)l = m + 1; else if (cnt > 0){ r = m - 1; } if (k < ans){ ans = k; x = L, y = m, z = R; } } } } printf("%d %d %d\n", I[x], I[y], I[z]); } }
[ "csjaj9772@gmail.com" ]
csjaj9772@gmail.com
4e4592cbe92f46f7a8fb6f9980b624b599219b83
50a52a038a9ba758dc0b413b182ee402c8cd8b93
/vn-spoj/baove/main.cpp
8ebe235fe5ad89b86a22c799999d82909329a207
[]
no_license
tranvansang/online-judge
233572fc74b8e96e27376e21558cb0122f5419ba
368983a461ee71225d8e41d27d21accf45245566
refs/heads/master
2022-07-06T07:25:38.194765
2022-06-22T01:23:11
2022-06-22T01:23:11
91,287,489
0
0
null
null
null
null
UTF-8
C++
false
false
2,046
cpp
#include <bits/stdc++.h> using namespace std; #define PII pair<int,int> #define VI vector<int> #define For(i,a,b) for(auto i = (a); i < (b); i++) #define rep(i,n) For(i,0,(n)) #define fi first #define se second #define mp make_pair #define pb push_back #define all(a) (a).begin(), (a).end() #define trav(it,x) for(auto it = (x).begin(); it != (x).end(); it++) #define ll long long #define MAXN 5000 #define MAXS 65000 #define MAXM 10000 int start[MAXN], nxt[MAXM * 2], adj[MAXM * 2], c[MAXM * 2], f[MAXM * 2], trace[MAXN], v[MAXM * 2]; bool visited[MAXN]; int n, m(0); int reverseEdge(int k) { return k ^ 1; } void addEdge(int a, int b, int s) { nxt[m] = start[a]; adj[m] = b; v[m] = a; c[m] = s; start[a] = m; m++; } bool bfs(int init) { queue<int> q; q.push(init); visited[init] = true; while (!q.empty()) { int x = q.front(); q.pop(); if (x == 0) return true; for(int k = start[x]; k!= -1; k = nxt[k]) { int y = adj[k]; if (!visited[y]) { int cost = c[k]; if (cost > 0 ? cost > f[k] : f[k]) { trace[y] = k; visited[y] = true; q.push(y); } } } } return false; } int main(){ ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); scanf("%d", &n); fill_n(start, n, -1); int a, b, s; while (scanf("%d%d%d", &a, &b, &s) == 3) { if (s) { a--;b--; addEdge(a, b, s); addEdge(b, a, -s); } }; fill_n(f, m, 0); fill_n(visited, n, false); while (bfs(n - 1)) { int minCost = -1; for (int y = 0; y != n - 1; y = v[trace[y]]) { int k = trace[y]; int cost = c[k]; int augment = cost > 0 ? cost - f[k] : f[k]; if (minCost == -1 || minCost > augment) minCost = augment; } for (int y = 0; y != n - 1; y = v[trace[y]]) { int k = trace[y]; if (c[k] > 0) { f[k] += minCost; f[reverseEdge(k)] += minCost; } else { f[k] -= minCost; f[reverseEdge(k)] -= minCost; } } fill_n(visited, n, false); } int sum = 0; for (int k = start[n - 1]; k != -1; k = nxt[k]) { if (c[k] > 0) sum += f[k]; } cout << sum; return 0; }
[ "me@transa.ng" ]
me@transa.ng
6a79f41f4b124d1db10416ebcec8d0c5ba2f032a
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chrome/browser/extensions/chrome_kiosk_delegate.cc
1ddbeaa91644e9b6c430bf7dfea7c6008aa073f6
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
473
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/chrome_kiosk_delegate.h" namespace extensions { ChromeKioskDelegate::ChromeKioskDelegate() {} ChromeKioskDelegate::~ChromeKioskDelegate() {} bool ChromeKioskDelegate::IsAutoLaunchedKioskApp(const ExtensionId& id) const { return false; } } // namespace extensions
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
b1a533bf84b3bd6d3be145b6e07867e28e7aac56
3f8c632fe1b97d85a754b6ed031d154ef5dbfa2f
/llvm_profile_reader.h
13e44a97facae625b245cea86e731a54d93199f2
[]
no_license
grajer/autofdo
9464338dc1cc085950c562724a1c1a2da360e38a
5ec7b699dfe2ebc58d608afff8c668ab358a2da9
refs/heads/master
2023-06-04T10:41:33.973535
2021-06-21T22:46:43
2021-06-21T22:46:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,238
h
// Read symbol_map from the llvm sample profile. #ifndef AUTOFDO_LLVM_PROFILE_READER_H_ #define AUTOFDO_LLVM_PROFILE_READER_H_ #include "base_profile_reader.h" #include "source_info.h" #include "third_party/abseil/absl/container/node_hash_set.h" #include "llvm/ProfileData/SampleProf.h" namespace llvm { class StringRef; namespace sampleprof { class FunctionSamples; } } // namespace llvm namespace devtools_crosstool_autofdo { class SymbolMap; struct SpecialSyms { SpecialSyms(const char *strip_all_p[], unsigned strip_all_len, const char *keep_sole_p[], unsigned keep_sole_len, const char *keep_cold_p[], unsigned keep_cold_len) { for (int i = 0; i < strip_all_len; i++) strip_all.insert(strip_all_p[i]); for (int i = 0; i < keep_sole_len; i++) keep_sole.insert(keep_sole_p[i]); for (int i = 0; i < keep_cold_len; i++) keep_cold.insert(keep_cold_p[i]); } absl::node_hash_set<std::string> strip_all; absl::node_hash_set<std::string> keep_sole; absl::node_hash_set<std::string> keep_cold; absl::node_hash_set<std::string> skip_set; }; class LLVMProfileReader : public ProfileReader { public: explicit LLVMProfileReader(SymbolMap *symbol_map, absl::node_hash_set<std::string>& names, SpecialSyms *special_syms = nullptr) : symbol_map_(symbol_map), names_(names), special_syms_(special_syms) {} bool ReadFromFile(const std::string &output_file) override; bool shouldMergeProfileForSym(const std::string name); void SetProfileSymbolList( std::unique_ptr<llvm::sampleprof::ProfileSymbolList> list) { prof_sym_list_ = std::move(list); } llvm::sampleprof::ProfileSymbolList *GetProfileSymbolList() { return prof_sym_list_.get(); } private: const char *GetName(const llvm::StringRef &N); void ReadFromFunctionSamples(const SourceStack &stack, const llvm::sampleprof::FunctionSamples &fs); SymbolMap *symbol_map_; absl::node_hash_set<std::string>& names_; SpecialSyms *special_syms_; std::unique_ptr<llvm::sampleprof::ProfileSymbolList> prof_sym_list_; }; } // namespace devtools_crosstool_autofdo #endif // AUTOFDO_LLVM_PROFILE_READER_H_
[ "wmi@google.com" ]
wmi@google.com
c6956d0c9ca2bff1fea7c523303d4ded57219f9b
27c2e5277bac7ba627f461d52e6c59dd23731e86
/sugar/engine/su_sg_scenegraph.h
d00f6e7aadec45b7710d0b5a17a06931328abe8d
[]
no_license
magicfoo/atonce
4c70fbc753fbc9bc1e32b14317ddf4bc61cafd66
7561af1c477e107ee9cdd1bcb82a8f7b753bc6ab
refs/heads/master
2022-12-23T10:10:42.602545
2020-09-23T20:18:42
2020-09-23T20:18:42
298,083,714
0
0
null
null
null
null
UTF-8
C++
false
false
3,854
h
/*LIC-HDR******************************************************************** ** ** Copyright (C) 2005-2011 AtOnce Technologies ** ** This file is part of the Sugar core-system framework. ** ** This file and the associated product may be used and distributed ** under the terms of a current License as defined by AtOnce Technologies ** and appearing in the file LICENSE.TXT included in the packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.atonce-technologies.com or email info@atonce-technologies.com ** for informations about Sugar Framework and AtOnce Technologies others products ** License Agreements. ** ** Contact info@atonce-technologies.com if any conditions of this license ** are not clear to you. ** *****************************************************************LIC-HDR*/ #ifndef _su_sg_scenegraph_h_ #define _su_sg_scenegraph_h_ #include "su_sg_scenegraph_enum.h" namespace su{ struct IDirectDraw; } namespace su { namespace sg { struct SceneGraph { public: static SceneGraph* Create ( Pool* inPool, IDirectDraw* inDD ); void Release ( ); void SetView ( uint inViewPbi, const Vec2& inViewSize ); uint GetView ( ); bool Draw ( ); Pool* GetPool ( ); Handle* GetRoot ( ); byte GetLayerId ( ); IDirectDraw* GetDirectDraw ( ); Matrix* BuildWorldTR ( Matrix* outTR, Handle* inHandle ); Box3* BuildBBox ( Box3* outBox, Handle* inHandle ); Handle* Pick ( Viewport* inViewport, const Vec2& inCoord ); void Pick ( vector<Handle*>* ioHandleA, Viewport* inViewport, const Vec2& inCoord, const Vec2& inSize ); void SetRenderMode ( RenderMode inRenderMode ); RenderMode GetRenderMode ( ); enum PostFxValue { PFV_BlurRadius, PFV_BlurBlendFactor, }; void EnablePostFx ( bool inOnOff ); void SetPostFxValuef ( PostFxValue inOpt, float inVal ); void SetPostFxCode ( pcstr inPixelCode ); bool SetCameraVideoMode ( bool inOnOff ); struct PostProcessUtil { Pool* pool; IDirectDraw* dd; uint w, h; struct Mip // start to w/2, h/2 { int rt; uint w, h; }; Mip* mipA; uint mipCount; }; struct BackQuad { uint w, h; uint quad; }; protected: virtual void OnEvent ( Handle* inHandle, EventReason inReason ); virtual void OnEvent ( Core* inCore, EventReason inReason ); Pool* pool; Root* root; byte layerid; IDirectDraw* ddraw; uint viewPbi; Vec2 viewSize; RenderMode renderMode; vector<uint> opCodeA; vector<Viewport*> viewportA; // // --- resources ( warp, grid, cube... ) uint noisePbi; uint gridSrf; uint warpSrf; uint abSrfA[2]; uint abVboRect; int abRectHL; uint cubeSrf; uint cubePbi; uint cubeHLSrfA[3]; uint cubeHLVboA[3]; uint pickRT; uint handleCount; bool pFxEnable; uint pFxProgId; float pFxBlurBlendFactor; float pFxBlurRadius; bool pFxBlurOpCodeDirty; uint pFxBlurOpCodeA[256]; float pFxBlurMipBlend_int; uint pFxBlurPbi_int; int mainRT; uint quadSS; uint quadFS; vector<BackQuad> backQuadA; PostProcessUtil ppu; bool onCameraVideoMode; friend struct Handle; friend struct Root; friend struct Core; }; } } #endif // _su_sg_scenegraph_h_
[ "ggainant@roblox.com" ]
ggainant@roblox.com
30f3e2d3f3bac3314f7a89799e0b4ea345902acb
5a19e6dfde1ddd1ffa98c341e4f5b412d710c42c
/mve/mistl/mistl/include/mistl/Quality.h
d39db93a4331adf895030333753339579ab735c0
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
jtpils/MVE_3D_SemanticSegmentation
dfb10f361f39995d5b36be90194bf639b2a19eb8
77fcaecd7f4b8e8ab7695b67596fd4e0858cc995
refs/heads/master
2020-08-29T07:19:33.845907
2019-10-08T14:27:24
2019-10-08T14:27:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,840
h
// // INTEL CORPORATION PROPRIETARY INFORMATION // // This software is supplied under the terms of a license agreement or // nondisclosure agreement with Intel Corporation and may not be copied // or disclosed except in accordance with the terms of that agreement. // Copyright (C) 2014 Intel Corporation. All Rights Reserved. // // ## specifics // // Mistl - Multi-camera Image STructure Library // Author: Oliver Grau // #ifndef Quality_incl_ #define Quality_incl_ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "mistl/Error.h" #include "opencv2/core/core.hpp" namespace mistl { /*! \class Quality Quality.h \brief Base class for quality and confidence \author O.Grau */ class Quality { public: Quality() {} ~Quality(){} public: //! Compute quality and confidence // virtual void Compute() =0; void Info() const; float GetQuality() const { if(quality<0.0f) return 0.0f; if(quality>1.0f) return 1.0f; return quality;} float GetConfidence() const { if(confidence<0.0f) return 0.0f; if(confidence>1.0f) return 1.0f; return confidence;} float quality; float confidence; private: }; /*! \class TrackQuality Quality.h \brief Class for quality and confidence of tracking results \author O.Grau */ class TrackQuality : public Quality { public: TrackQuality(){} ~TrackQuality(){} void Info() const; // virtual void Compute(); public: float match; unsigned n; //!< number of total correspondences unsigned ncam; //!< number of cameras unsigned min_n; //!< lowest number of correspondences in one camera private: }; } #endif
[ "syed.qutub@intel.com" ]
syed.qutub@intel.com
b7b55d384ff29a74b978cd57436cc8f961a3e946
400fd356eb75d95ab35e8dcce2f5b03b3d272e83
/Smjy/src/server/process/test.cpp
bb8ef94cad7ae81a5454282307bab51c9e3c685c
[]
no_license
shandaming/Martial_arts
4eba4c3856d0fbbcddc460790b4a06ba79a9c3ed
896f10a7c457a9f166e7991e54943d46b6a953b5
refs/heads/master
2022-11-11T08:05:21.439745
2022-10-22T05:55:23
2022-10-22T05:55:23
116,259,077
0
0
null
null
null
null
UTF-8
C++
false
false
3,258
cpp
#include <algorithm> #include <vector> #include <tuple> #include <utility> #include <tuple> template<typename F, typename T, typename... Args> void for_each(F&& f, T&& t, Args&&... args) { f(t); for_each(f, args...); } template<typename F, typename T> void for_each(F&& f, T&& t) { f(t); } struct child { explicit child(int p) : pid(p) {} int pid; }; struct initializer_base { template<typename T> void on_fork_setup(T&) const {} template<typename T> void on_fork_error(T&) const {} template<typename T> void on_fork_success(T&) const {} template<typename T> void on_exec_setup(T&) const {} template<typename T> void on_exec_error(T&) const {} }; class bind_stdin : public initializer_base { public: explicit bind_stdin(const int fd) : fd_(fd) {} template<typename T> void on_exec_setup(T&) const { //::dup2(fd_, STDIN_FILENO); } private: const int fd_; }; class bind_stdout : public initializer_base { public: explicit bind_stdout(const int fd) : fd_(fd) {} template<typename T> void on_exec_setup(T&) const { //::dunp2(fd_, STDOUT_FILENO); } private: int fd_; }; class bind_stderr : public initializer_base { public: explicit bind_stderr(const int fd) : fd_(fd) {} template<typename T> void on_exec_setup(T&) const { //::dup2(fd_, STDERR_FILENO); } private: const int fd_; }; struct executor { executor() : exe(0), cmd_line(0), env(0) {} struct call_on_fork_setup { call_on_fork_setup(executor& e) : e(e) {} template<typename T> void operator()(const T& arg) const { arg.on_fork_setup(e); } executor& e; }; struct call_on_fork_error { call_on_fork_error(executor& e) : e(e) {} template<typename T> void operator()(T& arg) const { arg.on_fork_error(e); } executor& e; }; struct call_on_fork_success { call_on_fork_success(executor& e) : e(e) {} template<typename T> void operator()(const T& arg) const { arg.on_fork_success(e); } executor& e; }; struct call_on_exec_setup { call_on_exec_setup(executor& e) : e(e) {} template<typename T> void operator()(T& arg) const { arg.on_exec_setup(e); } executor& e; }; struct call_on_exec_error { call_on_exec_error(executor& e) : e(e) {} template<typename T> void operator()(T& arg) const { arg.on_exec_error(e); } executor& e; }; template<typename... Args> child operator()(Args&&... seq) { for_each(call_on_fork_setup(*this), std::forward<Args>(seq)...); // inherit_env有 pid_t pid = 1;// = ::fork(); #if 0 if(pid == -1) { for_each(seq..., call_on_fork_error(*this)); // 都没有 } else if(pid == 0) { for_each(seq..., call_on_exec_setup(*this)); // 除inherit_env其他都有 //::execve(exe, cmd_line, env); for_each(seq..., call_on_exec_error(*this)); // 都没有 //_exit(EXIT_FAILURE); } for_each(seq..., call_on_fork_success(*this)); // 都没有 #endif return child(pid); } const char* exe; char** cmd_line; char** env; }; template<typename... Args> child execute(Args&&... args) { return executor()(std::forward<Args>(args)...); } int main() { child c = execute(bind_stdin(1), bind_stdout(2), bind_stderr(3)); //child c = executor()(bind_stdin(1), bind_stdout(2), bind_stderr(3)); return 0; }
[ "shandaming@hotmail.com" ]
shandaming@hotmail.com
b1097ce0ce9b4ff70b37baf4d2a76425e145ed79
76261aae39cfc15a2b3444665ebcb23a657db361
/Production/Source/Ripley/DNAArray.h
58236b8572497cb63b938838c697add9f02739b9
[]
no_license
rocketeerbkw/DNA
d208c72690ccfae261beb531fb52d1c2647783e3
de5993d6d0f8dd735085ebca4c86f4363c498615
refs/heads/master
2021-01-21T13:29:52.930616
2015-10-01T17:05:40
2015-10-01T17:05:40
43,528,993
1
0
null
2015-10-02T00:43:08
2015-10-02T00:43:08
null
UTF-8
C++
false
false
1,277
h
// // DNAArray.h // #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 /********************************************************************************* class CDNAIntArray Author: Mark Howitt Created: 10/03/2004 Purpose: New Int Array class with minimum functionality *********************************************************************************/ class CDNAIntArray { public: CDNAIntArray(); CDNAIntArray(int iInitialSize, int iGrowBy = -1); virtual ~CDNAIntArray(void); public: bool IsEmpty(void) { return m_iSize <= 0; } // Removes all elements from the array void RemoveAll(void); bool RemoveAt(int iIndex); void RemoveEnd(void); // Returns the number of elements in the array int GetSize(void) { return m_iSize; } // Sets the overall allocated memory for the arry int SetSize(int iSize,int iGrowBy = -1); void SetGrowBy(int iGrowBy); int FreeExtra(void); // Get Functions int operator[](int iIndex) const; int GetAt(int iIndex); // Add Function bool Add(int iValue); // Set Function bool SetAt(int iIndex, int iValue); int& operator[](int iIndex); private: int* m_pData; int m_iSize; int m_iMaxSize; int m_iGrowBy; int m_iInvalid; };
[ "VP-DEV-DNA-1\\NevesM31" ]
VP-DEV-DNA-1\NevesM31
653ec4328714b9a4e5c1cd43c4cf834720804a12
194840d144b77f3b662db6e3663c820db0807a46
/ProductLuaIdeCAPI/main.cpp
8877ad4c30da183f40e8d0e3579e4346f42ba8ef
[]
no_license
ToTPeople/my_own_tools
7cac7d84854b58d92f2ef4a538aea4ec06f5992c
d2509e7b399e076234162b8d757910627beec4b6
refs/heads/master
2020-03-24T03:46:05.723395
2018-07-26T12:15:49
2018-07-26T12:15:49
142,432,314
0
0
null
null
null
null
UTF-8
C++
false
false
377
cpp
#include <stdio.h> #include <string> #include <stdlib.h> #include "product_lua_ide_api.h" int main(int argc, char **argv) { // if (argc != 3) { // printf("----- please input ./a.out need_to_trans_dir out_dir ----\n"); // return 0; // } return parser_dir("./need_trans", "./after_trans"); // return parser_dir(argv[1], argv[2]); return 0; }
[ "lfs1@meitu.com" ]
lfs1@meitu.com
15aaef364c6c3e40fcb202b95a10b7d953dc7e07
2d361696ad060b82065ee116685aa4bb93d0b701
/src/util/test/test_thread_pool_old.cpp
f12decefa401a73d906ecb9ad76e8011857a247b
[ "LicenseRef-scancode-public-domain" ]
permissive
AaronNGray/GenomeWorkbench
5151714257ce73bdfb57aec47ea3c02f941602e0
7156b83ec589e0de8f7b0a85699d2a657f3e1c47
refs/heads/master
2022-11-16T12:45:40.377330
2020-07-10T00:54:19
2020-07-10T00:54:19
278,501,064
1
1
null
null
null
null
UTF-8
C++
false
false
5,199
cpp
/* $Id: test_thread_pool_old.cpp 605875 2020-04-16 11:24:47Z ivanov $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Aaron Ucko * * File Description: * thread pool test * * =========================================================================== */ #include <ncbi_pch.hpp> #include <util/thread_pool.hpp> #include <corelib/ncbi_process.hpp> #include <corelib/ncbi_system.hpp> #include <corelib/ncbiapp.hpp> #include <util/random_gen.hpp> #include <corelib/ncbimtx.hpp> #include <common/test_assert.h> // This header must go last USING_NCBI_SCOPE; CRandom s_RNG; DEFINE_STATIC_MUTEX(s_RNG_Mutex); #define RNG_LOCK CMutexGuard LOCK(s_RNG_Mutex) class CThreadPoolTester : public CNcbiApplication { protected: void Init(void); int Run (void); }; void CThreadPoolTester::Init(void) { unique_ptr<CArgDescriptions> arg_desc(new CArgDescriptions); arg_desc->SetUsageContext(GetArguments().GetProgramBasename(), "test of thread pool correctness"); arg_desc->AddDefaultKey("init_threads", "N", "how many worker threads to spawn initially", CArgDescriptions::eInteger, "3"); arg_desc->AddDefaultKey("max_threads", "N", "how many worker threads to allow total", CArgDescriptions::eInteger, "5"); arg_desc->AddDefaultKey("requests", "N", "how many jobs to submit", CArgDescriptions::eInteger, "10"); arg_desc->AddDefaultKey("queue_size", "N", "how many jobs to allow in the queue", CArgDescriptions::eInteger, "2"); arg_desc->AddDefaultKey("thread_pool_timeout", "N", "WaitForRoom() timeout argument (in ms)", CArgDescriptions::eInteger, "30"); arg_desc->AddDefaultKey("max_processing_time", "N", "maximum request processing time in ms", CArgDescriptions::eInteger, "5"); SetupArgDescriptions(arg_desc.release()); RNG_LOCK; s_RNG.SetSeed(CCurrentProcess::GetPid()); } class CTestRequest : public CStdRequest { public: CTestRequest(int serial, int max_processing_time) : m_Serial(serial), m_MaxProcessingTime(max_processing_time) { } protected: void Process(void); private: int m_Serial; int m_MaxProcessingTime; }; void CTestRequest::Process(void) { int duration; {{ RNG_LOCK; duration = s_RNG.GetRand(0, m_MaxProcessingTime); }} //LOG_POST("Request " << m_Serial << ": " << duration); SleepMilliSec(duration); //LOG_POST("Request " << m_Serial << " complete"); } int CThreadPoolTester::Run(void) { int status = 0; const CArgs& args = GetArgs(); CStdPoolOfThreads pool(args["max_threads"].AsInteger(), args["queue_size"].AsInteger()); pool.Spawn(args["init_threads"].AsInteger()); unsigned wait_timeout_ms = (unsigned) args["thread_pool_timeout"].AsInteger(); unsigned wait_timeout_s = wait_timeout_ms / 1000; unsigned wait_timeout_ns = (wait_timeout_ms % 1000) * 1000 * 1000; int max_processing_time = args["max_processing_time"].AsInteger(); try { for (int i = 0; i < args["requests"].AsInteger(); ++i) { try { pool.WaitForRoom(wait_timeout_s, wait_timeout_ns); } catch (CBlockingQueueException&) { continue; } //LOG_POST("Request " << (i + 1) << " to be queued"); pool.AcceptRequest(CRef<CStdRequest>(new CTestRequest(i + 1, max_processing_time))); } } STD_CATCH_ALL("CThreadPoolTester: status " << (status = 1)) pool.KillAllThreads(CStdPoolOfThreads::fKill_Wait); return status; } int main(int argc, const char* argv[]) { return CThreadPoolTester().AppMain(argc, argv); }
[ "aaronngray@gmail.com" ]
aaronngray@gmail.com
4c48b64b11fc148c0139c9b50c957bec8da1ae3a
44564fafb4624d7c3d3f96d243eb7702f80f5c1e
/tests/YGNodeChildTest.cpp
cce9f33b5150f497ad04dc6988feea97f32d037a
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
Finger-Ink/yoga
14cb62d8cd5216eb58fa4d1432d0f2bcc16abdfc
0daf361c60fef66c75992a06db6a86c227d2407c
refs/heads/master
2023-03-17T01:14:10.426201
2022-12-12T11:58:35
2022-12-12T11:58:35
203,693,690
0
0
MIT
2022-12-05T20:32:09
2019-08-22T01:47:17
C++
UTF-8
C++
false
false
1,093
cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <gtest/gtest.h> #include <yoga/Yoga.h> TEST(YogaTest, reset_layout_when_child_removed) { const YGNodeRef root = YGNodeNew(); const YGNodeRef root_child0 = YGNodeNew(); YGNodeStyleSetWidth(root_child0, 100); YGNodeStyleSetHeight(root_child0, 100); YGNodeInsertChild(root, root_child0, 0); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_EQ(0, YGNodeLayoutGetLeft(root_child0)); ASSERT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_EQ(100, YGNodeLayoutGetWidth(root_child0)); ASSERT_EQ(100, YGNodeLayoutGetHeight(root_child0)); YGNodeRemoveChild(root, root_child0); ASSERT_EQ(0, YGNodeLayoutGetLeft(root_child0)); ASSERT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_TRUE(YGFloatIsUndefined(YGNodeLayoutGetWidth(root_child0))); ASSERT_TRUE(YGFloatIsUndefined(YGNodeLayoutGetHeight(root_child0))); YGNodeFreeRecursive(root); }
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
aea875abef8aef583be65916a7490b525717446e
30874a1295d700427f7775d89a74ff5c4836dbe9
/libraries/ChLCD_MCP230xx/MCP230xxLCD.h
7a021eacee68dac5c9d0547354615285c0256fdc
[]
no_license
una1veritas/Arduino-public
f9b445bffe493e1c5b72f6587946b3fa3c5335ac
381cbd5193961534b910f1cfeb3a83bc273889a0
refs/heads/master
2021-01-19T15:20:21.300335
2020-10-15T12:08:24
2020-10-15T12:08:24
100,960,464
0
0
null
null
null
null
UTF-8
C++
false
false
2,338
h
/* * MCP2300xLCD.h * * Created on: 2012/04/18 * Author: sin */ #ifndef MCP2300xLCD_H_ #define MCP2300xLCD_H_ #if ARDUINO >= 100 #include "Arduino.h" #else #include "WPrograms.h" #endif //#include "Print.h" #include "IOExpander.h" #include "MCP230xx.h" #include "CharacterLCD.h" // from LiquidCrystal.h // commands #define LCD_CLEARDISPLAY 0x01 #define LCD_RETURNHOME 0x02 #define LCD_ENTRYMODESET 0x04 #define LCD_DISPLAYCONTROL 0x08 #define LCD_CURSORSHIFT 0x10 #define LCD_FUNCTIONSET 0x20 #define LCD_SETCGRAMADDR 0x40 #define LCD_SETDDRAMADDR 0x80 // flags for display entry mode #define LCD_ENTRYRIGHT 0x00 #define LCD_ENTRYLEFT 0x02 #define LCD_ENTRYSHIFTINCREMENT 0x01 #define LCD_ENTRYSHIFTDECREMENT 0x00 // flags for display on/off control #define LCD_DISPLAYON 0x04 #define LCD_DISPLAYOFF 0x00 #define LCD_CURSORON 0x02 #define LCD_CURSOROFF 0x00 #define LCD_BLINKON 0x01 #define LCD_BLINKOFF 0x00 // flags for display/cursor shift #define LCD_DISPLAYMOVE 0x08 #define LCD_CURSORMOVE 0x00 #define LCD_MOVERIGHT 0x04 #define LCD_MOVELEFT 0x00 // flags for function set #define LCD_8BITMODE 0x10 #define LCD_4BITMODE 0x00 #define LCD_2LINE 0x08 #define LCD_1LINE 0x00 #define LCD_5x10DOTS 0x04 #define LCD_5x8DOTS 0x00 class MCP230xxLCD: public CharacterLCD { MCP230xx xpander; uint8_t _rs_pin, _rw_pin, _enable_pin; uint8_t _data_pins[4]; uint8_t _bklight_pin; uint8_t _numcolumns; uint8_t _numlines; /* uint8_t cursorRow, cursorColumn; */ void write4bits(uint8_t); void pulseEnable(uint8_t); void pulseEnable(void); void init_xtender(); public: MCP230xxLCD(uint8_t addr, uint8_t rs, uint8_t wr, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t bklight = -1); // ~xLCD() {} void reset() { init_xtender(); } void begin(uint8_t cols = 16, uint8_t rows = 2, uint8_t dotsize = LCD_5x8DOTS); void init() { begin(); } void send(byte value, byte dcswitch); // void command(uint8_t); //#if ARDUINO >= 100 size_t write(uint8_t); //#else // void write(uint8_t); //#endif const byte displayRows() { return _numlines; } const byte displayColumns() { return _numcolumns; } void backlightOn(); void backlightOff(); }; #endif /* XLCD_H_ */
[ "una.veritas@me.com" ]
una.veritas@me.com
9843333381e8b78b55bf780d8ecf94aace2e9ccc
cc0b7d50a3c6e6b329aab5b0aa0a349580bddbdd
/constant/impp23/polyMesh/boundary
9463e5b708c4903bdb076b802d0a0a2dc0dc1ffa
[]
no_license
AndrewLindsay/OpenFoamFieldJoint
32eede3593516b550358673a01b7b442f69eb706
7940373dcc021225f2a7ff88e850a1dd51c62e36
refs/heads/master
2020-09-25T16:59:18.478368
2019-12-05T08:16:14
2019-12-05T08:16:14
226,048,923
0
0
null
null
null
null
UTF-8
C++
false
false
2,122
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1906 | | \\ / A nd | Web: www.OpenFOAM.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class polyBoundaryMesh; location "constant/impp23/polyMesh"; object boundary; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 6 ( front { type wedge; inGroups 1(wedge); nFaces 2500; startFace 4900; } back { type wedge; inGroups 1(wedge); nFaces 2500; startFace 7400; } wedgeright { type patch; nFaces 50; startFace 9900; } impp23_to_adh19 { type mappedWall; inGroups 1(wall); nFaces 50; startFace 9950; sampleMode nearestPatchFace; sampleRegion adh19; samplePatch adh19_to_impp23; } impp23_to_pps22 { type mappedWall; inGroups 1(wall); nFaces 50; startFace 10000; sampleMode nearestPatchFace; sampleRegion pps22; samplePatch pps22_to_impp23; } impp23_to_impp27 { type mappedWall; inGroups 1(wall); nFaces 50; startFace 10050; sampleMode nearestPatchFace; sampleRegion impp27; samplePatch impp27_to_impp23; } ) // ************************************************************************* //
[ "andrew.lindsay@westnet.com.au" ]
andrew.lindsay@westnet.com.au
8d3a2d224576cdcc0b763e02c7c1239612d0f9ad
f6876d46645bcb235f93a4263254a35657083990
/LED_SOUND/v0.1/v0.1.ino
2ab31a9f28d5d7d2d91df26e2b013ba729a076c9
[]
no_license
ckhurana/arduino-codes
8f950cf11ba3420de6b61a6e379f59b18beed45d
ede6b8ecda9ff52035ca1fb8e16499f4e2b061be
refs/heads/master
2020-03-25T22:07:08.986158
2018-09-10T00:10:37
2018-09-10T00:10:37
144,206,573
0
0
null
null
null
null
UTF-8
C++
false
false
3,390
ino
#include <FastLED.h> #define NUM_LEDS 16 // Data pin that led data will be written out over #define DATA_PIN 6 #define SOUND_PIN A0 CRGB leds[NUM_LEDS]; int soundVal = 0; void setup() { Serial.begin(9600); // sanity check delay - allows reprogramming if accidently blowing power w/leds pinMode(SOUND_PIN, INPUT); delay(2000); FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS); } void loop() { soundVal = analogRead(SOUND_PIN); // Serial.println(soundVal); // audio_1(soundVal); int wait=random(10,30); int dim=random(4,6); int max_cycles=8; int cycles=random(1,max_cycles+1); rainbowCycle(wait, cycles, dim); // for (int i = 0; i < NUM_LEDS; i++) { // leds[i] = CRGB(255,0,0); // FastLED.show(); // delay(500); // } // // for (int i = NUM_LEDS - 1; i >= 0; i--) { // leds[i] = CRGB(0,255,0); // FastLED.show(); // delay(500); // } // lightning(CRGB::White,20,50,250); } void audio_1(int sVal) { Serial.println(sVal); if (sVal < 250) { for (int i = 0; i < NUM_LEDS; i++) { leds[i] = CRGB(0, 0, 0); } } else if (sVal >= 250 && sVal < 450) { for (int i = 0; i < NUM_LEDS; i++) { if (i < 1) leds[i] = CRGB(0, 255, 255); else leds[i] = CRGB(0, 0, 0); } } else if (sVal >= 450 && sVal < 650) { for (int i = 0; i < NUM_LEDS; i++) { if (i < 2) leds[i] = CRGB(255, 0, 255); else leds[i] = CRGB(0, 0, 0); } } else { for (int i = 0; i < NUM_LEDS; i++) { leds[i] = CRGB(255, 255, 0); } } FastLED.show(); delay(10); } void lightning(CRGB c, int simultaneous, int cycles, int speed){ int flashes[simultaneous]; for(int i=0; i<cycles; i++){ for(int j=0; j<simultaneous; j++){ int idx = random(NUM_LEDS); flashes[j] = idx; leds[idx] = c ? c : randomColor(); } FastLED.show(); delay(speed); for(int s=0; s<simultaneous; s++){ leds[flashes[s]] = CRGB::Black; } delay(speed); } } void rainbowCycle(int wait, int cycles, int dim) { //loop several times with same configurations and same delay for(int cycle=0; cycle < cycles; cycle++){ byte dir=random(0,2); int k=255; //loop through all colors in the wheel for (int j=0; j < 256; j++,k--) { if(k<0) { k=255; } //Set RGB color of each LED for(int i=0; i<NUM_LEDS; i++) { CRGB ledColor = wheel(((i * 256 / NUM_LEDS) + (dir==0?j:k)) % 256,dim); leds[i]=ledColor; } FastLED.show(); FastLED.delay(wait); } } } CRGB wheel(int WheelPos, int dim) { CRGB color; if (85 > WheelPos) { color.r=0; color.g=WheelPos * 3/dim; color.b=(255 - WheelPos * 3)/dim;; } else if (170 > WheelPos) { color.r=WheelPos * 3/dim; color.g=(255 - WheelPos * 3)/dim; color.b=0; } else { color.r=(255 - WheelPos * 3)/dim; color.g=0; color.b=WheelPos * 3/dim; } return color; } CRGB Wheel(byte WheelPos) { if(WheelPos < 85) { return CRGB(WheelPos * 3, 255 - WheelPos * 3, 0); } else if(WheelPos < 170) { WheelPos -= 85; return CRGB(255 - WheelPos * 3, 0, WheelPos * 3); } else { WheelPos -= 170; return CRGB(0, WheelPos * 3, 255 - WheelPos * 3); } } CRGB randomColor(){ return Wheel(random(256)); }
[ "khuranachirag95@gmail.com" ]
khuranachirag95@gmail.com
acca10ddff67ddc4be42297ec92c4dbcec7b7d31
d57a25c0dd59b71801e7b9633dcb85029b12bb36
/include/dll/generators/inmemory_data_generator.hpp
5414ee048543d419bc32365d1aa81a94b201c644
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
xinsuinizhuan/dll
c391a81b53b790484d0b7abcad5c401af61605b1
df1fcae4bdf14fbc73290214cc6dbf4578ac1efe
refs/heads/master
2022-12-12T15:26:53.208901
2020-09-04T16:32:04
2020-09-04T16:32:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,721
hpp
//======================================================================= // Copyright (c) 2014-2020 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Implementation of an in-memory data generator */ #pragma once #include <atomic> #include <thread> namespace dll { /*! * \brief a in-memory data generator */ template <typename Iterator, typename LIterator, typename Desc, typename Enable = void> struct inmemory_data_generator; /*! * \copydoc inmemory_data_generator */ template <typename Iterator, typename LIterator, typename Desc> struct inmemory_data_generator<Iterator, LIterator, Desc, std::enable_if_t<!is_augmented<Desc>>> { using desc = Desc; ///< The generator descriptor using weight = etl::value_t<typename std::iterator_traits<Iterator>::value_type>; ///< The data type using data_cache_helper_t = cache_helper<Desc, Iterator>; ///< The helper for the data cache using label_cache_helper_t = label_cache_helper<Desc, weight, LIterator>; ///< The helper for the label cache using data_cache_type = typename data_cache_helper_t::cache_type; ///< The type of the data cache using label_cache_type = typename label_cache_helper_t::cache_type; ///< The type of the label cache static constexpr bool dll_generator = true; ///< Simple flag to indicate that the class is a DLL generator static inline constexpr size_t batch_size = desc::BatchSize; ///< The size of the generated batches data_cache_type input_cache; ///< The input cache label_cache_type label_cache; ///< The label cache size_t current = 0; ///< The current index bool is_safe = false; ///< Indicates if the generator is safe to reclaim memory from template <typename Input, typename Label> inmemory_data_generator(const Input& input, const Label& label, size_t n, size_t n_classes){ // Initialize both caches for enough elements data_cache_helper_t::init(n, &input, input_cache); label_cache_helper_t::init(n, n_classes, &label, label_cache); } /*! * \brief Construct an inmemory data generator */ inmemory_data_generator(Iterator first, Iterator last, LIterator lfirst, [[maybe_unused]] LIterator llast, size_t n_classes){ const size_t n = std::distance(first, last); data_cache_helper_t::init(n, first, input_cache); label_cache_helper_t::init(n, n_classes, lfirst, label_cache); // Fill the cache size_t i = 0; while (first != last) { input_cache(i) = *first; label_cache_helper_t::set(i, lfirst, label_cache); ++i; ++first; ++lfirst; } // Transform if necessary pre_scaler<desc>::transform_all(input_cache); pre_normalizer<desc>::transform_all(input_cache); pre_binarizer<desc>::transform_all(input_cache); // In case of auto-encoders, the label images also need to be transformed if constexpr (desc::AutoEncoder) { pre_scaler<desc>::transform_all(label_cache); pre_normalizer<desc>::transform_all(label_cache); pre_binarizer<desc>::transform_all(label_cache); } } inmemory_data_generator(const inmemory_data_generator& rhs) = delete; inmemory_data_generator operator=(const inmemory_data_generator& rhs) = delete; inmemory_data_generator(inmemory_data_generator&& rhs) = delete; inmemory_data_generator operator=(inmemory_data_generator&& rhs) = delete; /*! * \brief Display a description of the generator in the given stream * \param stream The stream to print to * \return stream */ std::ostream& display(std::ostream& stream) const { stream << "In-Memory Data Generator" << std::endl; stream << " Size: " << size() << std::endl; stream << " Batches: " << batches() << std::endl; if (augmented_size() != size()) { stream << " Augmented Size: " << augmented_size() << std::endl; } return stream; } /*! * \brief Display a description of the generator in the standard output. */ void display() const { display(std::cout); } /*! * \brief Indicates that it is safe to destroy the memory of the generator * when not used by the pretraining phase */ void set_safe() { is_safe = true; } /*! * \brier Clear the memory of the generator. * * This is only done if the generator is marked as safe it is safe. */ void clear() { if (is_safe) { input_cache.clear(); label_cache.clear(); } } /*! * brief Sets the generator in test mode */ void set_test() { // Nothing to do } /*! * brief Sets the generator in train mode */ void set_train() { // Nothing to do } /*! * \brief Reset the generator to the beginning */ void reset() { current = 0; } /*! * \brief Reset the generator and shuffle the order of samples */ void reset_shuffle() { current = 0; shuffle(); } /*! * \brief Shuffle the order of the samples. * * This should only be done when the generator is at the beginning. */ void shuffle() { cpp_assert(!current, "Shuffle should only be performed on start of generation"); etl::parallel_shuffle(input_cache, label_cache, dll::rand_engine()); } /*! * \brief Prepare the dataset for an epoch */ void prepare_epoch(){ input_cache.ensure_gpu_up_to_date(); label_cache.ensure_gpu_up_to_date(); } /*! * \brief Return the index of the current batch in the generation * \return The current batch index */ size_t current_batch() const { return current / batch_size; } /*! * \brief Returns the number of elements in the generator * \return The number of elements in the generator */ size_t size() const { return etl::dim<0>(input_cache); } /*! * \brief Returns the augmented number of elements in the generator. * * This number may be an estimate, depending on which augmentation * techniques are enabled. * * \return The augmented number of elements in the generator */ size_t augmented_size() const { return etl::dim<0>(input_cache); } /*! * \brief Returns the number of batches in the generator. * \return The number of batches in the generator */ size_t batches() const { return size() / batch_size + (size() % batch_size == 0 ? 0 : 1); } /*! * \brief Indicates if the generator has a next batch or not * \return true if the generator has a next batch, false otherwise */ bool has_next_batch() const { return current < size(); } /*! * \brief Moves to the next batch. * * This should only be called if the generator has a next batch. */ void next_batch() { current += batch_size; } /*! * \brief Returns the current data batch * \return a a batch of data. */ auto data_batch() const { return etl::slice(input_cache, current, std::min(current + batch_size, size())); } /*! * \brief Returns the current label batch * \return a a batch of label. */ auto label_batch() const { return etl::slice(label_cache, current, std::min(current + batch_size, size())); } /*! * \brief Set some part of the data to a new set of value * \param i The beginning at which to start storing the new data * \param input_batch An input batch */ template <typename Input> void set_data_batch(size_t i, Input&& input_batch) { etl::slice(input_cache, i, i + etl::dim<0>(input_batch)) = input_batch; } /*! * \brief Set some part of the labels to a new set of value * \param i The beginning at which to start storing the new data * \param input_batch A label batch */ template <typename Input> void set_label_batch(size_t i, Input&& input_batch) { etl::slice(label_cache, i, i + etl::dim<0>(input_batch)) = input_batch; } /*! * \brief Finalize the dataset if it was filled directly after having being prepared. */ void finalize_prepared_data() { pre_scaler<desc>::transform_all(input_cache); pre_normalizer<desc>::transform_all(input_cache); pre_binarizer<desc>::transform_all(input_cache); // In case of auto-encoders, the label images also need to be transformed if constexpr (desc::AutoEncoder) { pre_scaler<desc>::transform_all(label_cache); pre_normalizer<desc>::transform_all(label_cache); pre_binarizer<desc>::transform_all(label_cache); } } /*! * \brief Returns the number of dimensions of the input. * \return The number of dimensions of the input. */ static constexpr size_t dimensions() { return etl::dimensions<data_cache_type>() - 1; } }; /*! * \copydoc inmemory_data_generator */ template <typename Iterator, typename LIterator, typename Desc> struct inmemory_data_generator<Iterator, LIterator, Desc, std::enable_if_t<is_augmented<Desc>>> { using desc = Desc; ///< The generator descriptor using weight = etl::value_t<typename Iterator::value_type>; ///< The data type using data_cache_helper_t = cache_helper<desc, Iterator>; ///< The helper for the data cache using label_cache_helper_t = label_cache_helper<desc, weight, LIterator>; ///< The helper for the label cache using data_cache_type = typename data_cache_helper_t::cache_type; ///< The type of the data cache using big_cache_type = typename data_cache_helper_t::big_cache_type; ///< The type of big data cache using label_cache_type = typename label_cache_helper_t::cache_type; ///< The type of the label cache static constexpr bool dll_generator = true; ///< Simple flag to indicate that the class is a DLL generator static constexpr inline size_t batch_size = desc::BatchSize; ///< The size of the generated batches static constexpr inline size_t big_batch_size = desc::BigBatchSize; ///< The number of batches kept in cache data_cache_type input_cache; ///< The data cache big_cache_type batch_cache; ///< The data batch cache label_cache_type label_cache; ///< The label cache random_cropper<Desc> cropper; ///< The random cropper random_mirrorer<Desc> mirrorer; ///< The random mirrorer elastic_distorter<Desc> distorter; ///< The elastic distorter random_noise<Desc> noiser; ///< The random noiser size_t current = 0; ///< The current index bool is_safe = false; ///< Indicates if the generator is safe to reclaim memory from mutable volatile bool status[big_batch_size]; ///< Status of each batch mutable volatile size_t indices[big_batch_size]; ///< Indices of each batch mutable std::mutex main_lock; ///< The main lock mutable std::condition_variable condition; ///< The condition variable for the thread to wait for some space mutable std::condition_variable ready_condition; ///< The condition variable for a reader to wait for ready data volatile bool stop_flag = false; ///< Boolean flag indicating to the thread to stop std::thread main_thread; ///< The main thread bool train_mode = false; ///< The train mode status /*! * \brief Construct an inmemory data generator */ inmemory_data_generator(Iterator first, Iterator last, LIterator lfirst, [[maybe_unused]] LIterator llast, size_t n_classes) : cropper(*first), mirrorer(*first), distorter(*first), noiser(*first) { const size_t n = std::distance(first, last); data_cache_helper_t::init(n, first, input_cache); data_cache_helper_t::init_big(first, batch_cache); label_cache_helper_t::init(n, n_classes, lfirst, label_cache); // Fill the cache size_t i = 0; while (first != last) { input_cache(i) = *first; label_cache_helper_t::set(i, lfirst, label_cache); ++i; ++first; ++lfirst; } // Transform if necessary pre_scaler<desc>::transform_all(input_cache); pre_normalizer<desc>::transform_all(input_cache); pre_binarizer<desc>::transform_all(input_cache); // In case of auto-encoders, the label images also need to be transformed if constexpr (desc::AutoEncoder) { pre_scaler<desc>::transform_all(label_cache); pre_normalizer<desc>::transform_all(label_cache); pre_binarizer<desc>::transform_all(label_cache); } for (size_t b = 0; b < big_batch_size; ++b) { status[b] = false; indices[b] = b; } main_thread = std::thread([this] { while (true) { // The index of the batch inside the batch cache size_t index = 0; { std::unique_lock<std::mutex> ulock(main_lock); bool found = false; // Try to find a read batch first for (size_t b = 0; b < big_batch_size; ++b) { if (!status[b] && indices[b] * batch_size < size()) { index = b; found = true; break; } } // if not found, wait for a ready to compute batch if (!found) { // Wait for the end or for some work condition.wait(ulock, [this, &index] { if (stop_flag) { return true; } for (size_t b = 0; b < big_batch_size; ++b) { if (!status[b] && indices[b] * batch_size < size()) { index = b; return true; } } return false; }); // If there is no more thread for the thread, exit if (stop_flag) { return; } } } // Get the batch that needs to be read const size_t batch = indices[index]; // Get the index from where to read inside the input cache const size_t input_n = batch * batch_size; for (size_t i = 0; i < batch_size && input_n + i < size(); ++i) { if (train_mode) { // Random crop the image cropper.transform_first(batch_cache(index)(i), input_cache(input_n + i)); // Mirror the image mirrorer.transform(batch_cache(index)(i)); // Distort the image distorter.transform(batch_cache(index)(i)); // Noise the image noiser.transform(batch_cache(index)(i)); } else { // Center crop the image cropper.transform_first_test(batch_cache(index)(i), input_cache(input_n + i)); } } // Notify a waiter that one batch is ready { std::unique_lock<std::mutex> ulock(main_lock); status[index] = true; ready_condition.notify_one(); } } }); } inmemory_data_generator(const inmemory_data_generator& rhs) = delete; inmemory_data_generator operator=(const inmemory_data_generator& rhs) = delete; inmemory_data_generator(inmemory_data_generator&& rhs) = delete; inmemory_data_generator operator=(inmemory_data_generator&& rhs) = delete; /*! * \brief Display a description of the generator in the given stream * \param stream The stream to print to * \return stream */ std::ostream& display(std::ostream& stream) const { stream << "In-Memory Data Generator" << std::endl; stream << " Size: " << size() << std::endl; stream << " Batches: " << batches() << std::endl; if (augmented_size() != size()) { stream << " Augmented Size: " << augmented_size() << std::endl; } return stream; } /*! * \brief Display a description of the generator in the standard output. */ void display() const { display(std::cout); } /*! * \brief Indicates that it is safe to destroy the memory of the generator * when not used by the pretraining phase */ void set_safe() { is_safe = true; } /*! * \brier Clear the memory of the generator. * * This is only done if the generator is marked as safe it is safe. */ void clear() { if (is_safe) { input_cache.clear(); batch_cache.clear(); label_cache.clear(); } } /*! * brief Sets the generator in test mode */ void set_test() { train_mode = false; } /*! * brief Sets the generator in train mode */ void set_train() { train_mode = true; } /*! * \brief Destructs the inmemory_data_generator */ ~inmemory_data_generator() { cpp::with_lock(main_lock, [this] { stop_flag = true; }); condition.notify_all(); main_thread.join(); } /*! * \brief Reset the generation to its beginning */ void reset_generation() { std::unique_lock<std::mutex> ulock(main_lock); for (size_t b = 0; b < big_batch_size; ++b) { status[b] = false; indices[b] = b; } condition.notify_one(); } /*! * \brief Reset the generator to the beginning */ void reset() { current = 0; reset_generation(); } /*! * \brief Reset the generator and shuffle the order of samples */ void reset_shuffle() { current = 0; shuffle(); reset_generation(); } /*! * \brief Shuffle the order of the samples. * * This should only be done when the generator is at the beginning. */ void shuffle() { cpp_assert(!current, "Shuffle should only be performed on start of generation"); etl::parallel_shuffle(input_cache, label_cache, dll::rand_engine()); } /*! * \brief Prepare the dataset for an epoch */ void prepare_epoch(){ // Nothing can be done here } /*! * \brief Return the index of the current batch in the generation * \return The current batch index */ size_t current_batch() const { return current / batch_size; } /*! * \brief Returns the number of elements in the generator * \return The number of elements in the generator */ size_t size() const { return etl::dim<0>(input_cache); } /*! * \brief Returns the augmented number of elements in the generator. * * This number may be an estimate, depending on which augmentation * techniques are enabled. * * \return The augmented number of elements in the generator */ size_t augmented_size() const { return cropper.scaling() * mirrorer.scaling() * noiser.scaling() * distorter.scaling() * etl::dim<0>(input_cache); } /*! * \brief Returns the number of batches in the generator. * \return The number of batches in the generator */ size_t batches() const { return size() / batch_size + (size() % batch_size == 0 ? 0 : 1); } /*! * \brief Indicates if the generator has a next batch or not * \return true if the generator has a next batch, false otherwise */ bool has_next_batch() const { return current < size(); } /*! * \brief Moves to the next batch. * * This should only be called if the generator has a next batch. */ void next_batch() { // Get information from batch that has been consumed const auto batch = current / batch_size; const auto b = batch % big_batch_size; { std::unique_lock<std::mutex> ulock(main_lock); status[b] = false; indices[b] += big_batch_size; condition.notify_one(); } current += batch_size; } /*! * \brief Returns the current data batch * \return a a batch of data. */ auto data_batch() const { std::unique_lock<std::mutex> ulock(main_lock); const auto batch = current / batch_size; const auto b = batch % big_batch_size; if (status[b]) { const auto input_n = indices[b] * batch_size + batch_size; if (input_n > size()) { return etl::slice(batch_cache(b), 0, batch_size - (input_n - size())); } else { return etl::slice(batch_cache(b), 0, batch_size); } } ready_condition.wait(ulock, [this, b] { return status[b]; }); const auto input_n = indices[b] * batch_size + batch_size; if (input_n > size()) { return etl::slice(batch_cache(b), 0, batch_size - (input_n - size())); } else { return etl::slice(batch_cache(b), 0, batch_size); } } /*! * \brief Returns the current label batch * \return a a batch of label. */ auto label_batch() const { return etl::slice(label_cache, current, std::min(current + batch_size, size())); } /*! * \brief Returns the number of dimensions of the input. * \return The number of dimensions of the input. */ static constexpr size_t dimensions() { return etl::dimensions<data_cache_type>() - 1; } }; /*! * \brief Display the given generator on the given stream * \param os The output stream * \param generator The generator to display * \return os */ template <typename Iterator, typename LIterator, typename Desc> std::ostream& operator<<(std::ostream& os, inmemory_data_generator<Iterator, LIterator, Desc>& generator) { return generator.display(os); } /*! * \brief Descriptor for a inmemory_data_generator */ template <typename... Parameters> struct inmemory_data_generator_desc { /*! * A list of all the parameters of the descriptor */ using parameters = cpp::type_list<Parameters...>; /*! * \brief The size of a batch */ static constexpr size_t BatchSize = detail::get_value_v<batch_size<1>, Parameters...>; /*! * \brief The number of batch in cache */ static constexpr size_t BigBatchSize = detail::get_value_v<big_batch_size<1>, Parameters...>; /*! * \brief Indicates if the generators must make the labels categorical */ static constexpr bool Categorical = parameters::template contains<categorical>(); /*! * \brief Indicates if horizontal mirroring should be used as augmentation. */ static constexpr bool HorizontalMirroring = parameters::template contains<horizontal_mirroring>(); /*! * \brief Indicates if vertical mirroring should be used as augmentation. */ static constexpr bool VerticalMirroring = parameters::template contains<vertical_mirroring>(); /*! * \brief The random cropping X */ static constexpr size_t random_crop_x = detail::get_value_1_v<random_crop<0, 0>, Parameters...>; /*! * \brief The random cropping Y */ static constexpr size_t random_crop_y = detail::get_value_2_v<random_crop<0, 0>, Parameters...>; /*! * \brief The elastic distortion kernel */ static constexpr size_t ElasticDistortion = detail::get_value_v<elastic_distortion<0>, Parameters...>; /*! * \brief The noise */ static constexpr size_t Noise = detail::get_value_v<noise<0>, Parameters...>; /*! * \brief The scaling */ static constexpr size_t ScalePre = detail::get_value_v<scale_pre<0>, Parameters...>; /*! * \brief The scaling */ static constexpr size_t BinarizePre = detail::get_value_v<binarize_pre<0>, Parameters...>; /*! * \brief Indicates if input are normalized */ static constexpr bool NormalizePre = parameters::template contains<normalize_pre>(); /*! * \brief Indicates if this is an auto-encoder task */ static constexpr bool AutoEncoder = parameters::template contains<autoencoder>(); static_assert(BatchSize > 0, "The batch size must be larger than one"); static_assert(BigBatchSize > 0, "The big batch size must be larger than one"); static_assert(!(AutoEncoder && (random_crop_x || random_crop_y)), "autoencoder mode is not compatible with random crop"); //Make sure only valid types are passed to the configuration list static_assert( detail::is_valid_v< cpp::type_list< batch_size_id, big_batch_size_id, horizontal_mirroring_id, vertical_mirroring_id, random_crop_id, elastic_distortion_id, categorical_id, noise_id, nop_id, normalize_pre_id, binarize_pre_id, scale_pre_id, autoencoder_id>, Parameters...>, "Invalid parameters type for rbm_desc"); /*! * The generator type */ template <typename Iterator, typename LIterator> using generator_t = inmemory_data_generator<Iterator, LIterator, inmemory_data_generator_desc<Parameters...>>; }; /*! * \brief Make an out of memory data generator from iterators */ template <typename Iterator, typename LIterator, typename... Parameters> auto make_generator(Iterator first, Iterator last, LIterator lfirst, LIterator llast, size_t n_classes, const inmemory_data_generator_desc<Parameters...>& /*desc*/) { using generator_t = typename inmemory_data_generator_desc<Parameters...>::template generator_t<Iterator, LIterator>; return std::make_unique<generator_t>(first, last, lfirst, llast, n_classes); } /*! * \brief Make an out of memory data generator from containers */ template <typename Container, typename LContainer, typename... Parameters> auto make_generator(const Container& container, const LContainer& lcontainer, size_t n_classes, const inmemory_data_generator_desc<Parameters...>& /*desc*/) { using generator_t = typename inmemory_data_generator_desc<Parameters...>::template generator_t<typename Container::const_iterator, typename LContainer::const_iterator>; return std::make_unique<generator_t>(container.begin(), container.end(), lcontainer.begin(), lcontainer.end(), n_classes); } // The following are simply helpers for creating generic generators /*! * \brief Make an out of memory data generator from iterators */ template <typename Iterator, typename LIterator, typename... Parameters> auto make_generator(Iterator first, Iterator last, LIterator lfirst, LIterator llast, [[maybe_unused]] size_t n, size_t n_classes, const inmemory_data_generator_desc<Parameters...>& /*desc*/) { using generator_t = typename inmemory_data_generator_desc<Parameters...>::template generator_t<Iterator, LIterator>; return std::make_unique<generator_t>(first, last, lfirst, llast, n_classes); } /*! * \brief Make an out of memory data generator from containers */ template <typename Container, typename LContainer, typename... Parameters> auto make_generator(const Container& container, const LContainer& lcontainer, [[maybe_unused]] size_t n, size_t n_classes, const inmemory_data_generator_desc<Parameters...>& /*desc*/) { using generator_t = typename inmemory_data_generator_desc<Parameters...>::template generator_t<typename Container::const_iterator, typename LContainer::const_iterator>; return std::make_unique<generator_t>(container.begin(), container.end(), lcontainer.begin(), lcontainer.end(), n_classes); } /*! * \brief Prepare an in-memory data generator from an example. The generator * will be constructed to hold the given size and can then be filled. */ template <typename Input, typename Label, typename... Parameters> auto prepare_generator(const Input& input, const Label& label, size_t n, size_t n_classes, const inmemory_data_generator_desc<Parameters...>& /*desc*/) { // Create fake iterators for the type (won't be iterated using Iterator = const Input*; using LIterator = const Label*; // The generator type using generator_t = typename inmemory_data_generator_desc<Parameters...>::template generator_t<Iterator, LIterator>; return std::make_unique<generator_t>(input, label, n, n_classes); } } //end of dll namespace
[ "baptiste.wicht@gmail.com" ]
baptiste.wicht@gmail.com
04ebc2070e7ac69bd5099eee9cd8a6911eb4c179
22fa5261c962bdfb7bb0ae0a03d8ea984bcb71d5
/nov/1/859C.cpp
ae436f40bdcf5939f676b69a18faa2aaa8628f37
[]
no_license
Ashish-uzumaki/cp
21f03ddf6971cde10278af296734907a3a4d5996
2798de8429f934393b927f8beea3ac37d7a2a0aa
refs/heads/master
2020-04-11T17:40:56.645606
2018-12-27T04:04:27
2018-12-27T04:04:27
161,970,092
0
0
null
null
null
null
UTF-8
C++
false
false
890
cpp
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define lli long long int #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); ordered_set<lli>root,nom;//nom.order_of_key(x); lli visit[100001]; vector<pair<lli,lli> >v1,v2; // vector<lli>v1,v2; vector<lli>v; map<lli,lli>m; lli n; const lli MOD = 1e9+7; const lli k=16; const lli N=1e5; lli dp[51][N+1]; int main(){ cin>>n; lli sum=0; for(lli i=0;i<n;i++){ cin>>x; v.pb(x); sum+=x; } lli w=sum/2; for(lli i=1;i<n;i++){ dp[i][0]=max(dp[i-1][0],dp[i-1][1]); dp[i][1]=max(v[i]+dp[i-1][0],v[i]+dp[i-1][1]); } }
[ "1998ashishsingh@gmail.com" ]
1998ashishsingh@gmail.com
fbdb362116e4288d3946e034ecb4698574ad8d07
1a9002206db75270137e8dc896113d49ae3f8cf9
/GeeksForGeeks/Check if Linked List is Palindrome(Using vectors).cpp
10df3297e796de02b8ffc3f3fbb9df2742db1115
[]
no_license
manthankhorwal/Competitive-programming
8d2baaeb1ef049175f309756f5f30bb4015b7e41
95aa35b3dfe487249de13c04c275be7440590bd2
refs/heads/master
2020-05-27T17:23:50.666813
2019-06-14T17:30:52
2019-06-14T17:30:52
188,718,937
0
0
null
null
null
null
UTF-8
C++
false
false
396
cpp
#include<bits/stdc++.h> bool isPalindrome(Node *head) { Node* temp=head; vector<int> v; while(temp!=NULL) { v.push_back(temp->data); temp=temp->next; } Node *temp1=head; while(temp1!=NULL) { if(temp1->data!=v.back()) { return false; } temp1=temp1->next; v.pop_back(); } return true; }
[ "manthankhorwal502@gmail.com" ]
manthankhorwal502@gmail.com
1737c71e235f2108e03e5c40eab1eceadfae0f20
d4c0b7fd40ddd8be34cb092cb7fd173f381dba65
/ZeroBiasStudies/Utilities/PlottingTools/interface/PlottingTools.h
8323253147a587bcd5cf8897adee88676fa687aa
[]
no_license
ForwardGroupBrazil/ForwardAnalysis
8dceaacb1707c0769296f3c7b2e37c15a4a30ff7
5572335f19d1e0d385f73945e55e42fb4ed49761
refs/heads/master
2021-01-16T01:02:02.286181
2013-09-12T20:54:02
2013-09-12T20:54:02
12,787,581
1
4
null
null
null
null
UTF-8
C++
false
false
3,199
h
#ifndef UtilitiesPlottingTools_PlottingTools_h #define UtilitiesPlottingTools_PlottingTools_h class TFile; class TDirectory; #include "TH1F.h" #include <vector> #include <string> #include <map> #include <exception> class DefaultNorm{ public: /*DefaultNorm() {} double GetNormFactor(const TH1F* hist) {return hist->GetSumOfWeights();} double operator()(const TH1F* hist) {return GetNormFactor(hist);}*/ static double GetNorm(const TH1F* hist) {return hist->GetSumOfWeights();} private: }; class ConstNorm{ public: /*ConstNorm(double norm=1.):normalization_(norm) {} double GetNormFactor(const TH1F* hist) {return normalization_;} double operator()(const TH1F* hist) {return GetNormFactor(hist);}*/ static double GetNorm(const TH1F* hist) {return normalization;} private: //double normalization_; static double normalization; }; class NumberEntriesNorm{ public: /*NumberEntriesNorm() {} double operator()(const TH1F* hist) {return hist->GetSumOfWeights()/hist->GetEntries();}*/ static double GetNorm(const TH1F* hist) {return hist->GetSumOfWeights()/hist->GetEntries();} private: }; /*template <typename T> class Sum{ public: typedef T value_type; Sum(T const& init): sum_(init) {} void operator()(T const& x) {sum_ += x;} T const value() const {return sum_;} private: T sum_; }; template <typename T> class Mult{ public: typedef T value_type; Mult(T const& x): val_(x) {} T const operator()(T const& x) {return x*val_;} private: T val_; };*/ class RootException: public std::exception{ public: RootException(std::string const& msg = ""): message_(msg) {} ~RootException() throw() {} virtual char const* what() const throw() { return message_.c_str(); } private: std::string message_; }; //TH1F* getHisto(TFile*, const std::string&); TH1F* getHisto(TDirectory const*, std::string const&); void scaleHisto(TH1F* histo, double scale = 1., int line = 1, int color = 1, int rebin = 1); TH1F* rebinHisto(TH1F const* histo, std::vector<int> const& groups); std::map<std::string,std::vector<std::string> > buildVarMap(const std::vector<std::string>& varNames,const std::vector<std::string>& triggerBits); template<typename KeyType,typename ValueType> std::map<KeyType,ValueType> makeMap(const std::vector<KeyType>& keys,const std::vector<ValueType>& values){ std::map<KeyType,ValueType> res; typename std::vector<KeyType>::const_iterator key = keys.begin(); typename std::vector<ValueType>::const_iterator value = values.begin(); typename std::vector<KeyType>::const_iterator keys_end = keys.end(); typename std::vector<ValueType>::const_iterator values_end = values.end(); for(; key != keys_end && value != values_end; ++key,++value) res[*key] = *value; return res; } void plot(std::map<std::string,std::vector<std::string> >& variablesMap, TDirectory* dir, bool Norm = false); //template <class NormPolicy> //void plot(std::vector<std::string>& variables, std::vector<std::pair<std::string,TDirectory*> >& directories, NormPolicy& norm); #endif
[ "" ]
d20eabc867c77ad8b9215fa00a544b4624cc5ec5
83195bb76eb33ed93ab36c3782295e4a2df6f005
/Source/AtomicWebView/WebKeyboardWindows.cpp
8ff812b7e75d87d3601aed27e33cb0564927d1ee
[ "MIT", "BSD-3-Clause", "Zlib", "LicenseRef-scancode-openssl", "LicenseRef-scancode-khronos", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "NTP" ]
permissive
MrRefactoring/AtomicGameEngine
ff227c054d3758bc1fbd5e502c382d7de81b0d47
9cd1bf1d4ae7503794cc3b84b980e4da17ad30bb
refs/heads/master
2020-12-09T07:24:48.735251
2020-01-11T14:03:29
2020-01-11T14:03:29
233,235,105
0
0
NOASSERTION
2020-01-11T13:21:19
2020-01-11T13:21:18
null
UTF-8
C++
false
false
4,452
cpp
// // Copyright (c) 2014-2016, THUNDERBEAST GAMES LLC All rights reserved // // 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. // #ifdef ATOMIC_PLATFORM_WINDOWS #include <include/cef_client.h> #include <ThirdParty/SDL/include/SDL.h> #include <ThirdParty/SDL/include/SDL_syswm.h> #include <ThirdParty/SDL/src/events/scancodes_windows.h> #include <Atomic/Core/Variant.h> #include <Atomic/Input/InputEvents.h> #include <Atomic/Input/Input.h> #include <Atomic/IO/Log.h> #include "WebKeyboard.h" namespace Atomic { static bool SDLScanCodeToWindowsScanCode(SDL_Scancode code, LPARAM& lParam, WPARAM& wParam ) { wParam = 0; lParam = 0; int numCodes = sizeof(windows_scancode_table)/sizeof(SDL_Scancode); int windowsScanCode = -1; for (int i = 0; i < numCodes; i++) { if (windows_scancode_table[i] == code) { windowsScanCode = i; break; } } if (windowsScanCode != -1) { wParam = MapVirtualKey(windowsScanCode, MAPVK_VSC_TO_VK); lParam = windowsScanCode << 16; } switch (code) { case SDL_SCANCODE_RIGHT: wParam = VK_RIGHT; break; case SDL_SCANCODE_LEFT: wParam = VK_LEFT; break; case SDL_SCANCODE_UP: wParam = VK_UP; break; case SDL_SCANCODE_DOWN: wParam = VK_DOWN; break; case SDL_SCANCODE_DELETE: wParam = VK_DELETE; break; case SDL_SCANCODE_BACKSPACE: wParam = VK_BACK; break; } return wParam != 0 || lParam != 0; } bool ConvertKeyEvent(Input* input, const StringHash eventType, VariantMap& eventData, CefKeyEvent& keyEvent) { if (eventType != "KeyDown" && eventType != "KeyUp") { ATOMIC_LOGERROR("ConvertKeyEvent - Unknown event type"); return false; } WebKeyEvent wk(eventType, eventData); if (wk.scanCode == SDL_SCANCODE_RETURN) { if (!wk.keyDown) return false; keyEvent.windows_key_code = VK_RETURN; keyEvent.native_key_code = (int) 0; keyEvent.type = KEYEVENT_RAWKEYDOWN; return true; } LPARAM lParam; WPARAM wParam; keyEvent.modifiers = EVENTFLAG_NONE; if (wk.qual & QUAL_SHIFT) keyEvent.modifiers |= EVENTFLAG_SHIFT_DOWN; if (wk.qual & QUAL_ALT) keyEvent.modifiers |= EVENTFLAG_ALT_DOWN; if (wk.qual & QUAL_CTRL) keyEvent.modifiers |= EVENTFLAG_CONTROL_DOWN; if (SDLScanCodeToWindowsScanCode((SDL_Scancode) wk.scanCode, lParam, wParam)) { keyEvent.windows_key_code = (int) wParam; keyEvent.native_key_code = (int) lParam; keyEvent.type = wk.keyDown ? KEYEVENT_RAWKEYDOWN : KEYEVENT_KEYUP; } return true; } bool ConvertTextInputEvent(StringHash eventType, VariantMap& eventData, CefKeyEvent& keyEvent) { if (eventType != "TextInput") { ATOMIC_LOGERROR("ConvertTextInputEvent - Unknown event type"); return false; } String text = eventData[TextInput::P_TEXT].GetString(); SDL_Keycode keyCode = SDL_GetKeyFromName(text.CString()); if (SDL_strlen(text.CString()) == 1) { if (text[0] >= 'A' && text[0] <= 'Z') { keyCode -= 32; } } keyEvent.windows_key_code = (int) keyCode; keyEvent.native_key_code = 0;// (int) lParam; keyEvent.type = KEYEVENT_CHAR; return true; } } #endif
[ "josh@galaxyfarfaraway.com" ]
josh@galaxyfarfaraway.com
d69ab602fa7ed52671584b5120e073cf75c06d36
3358e2982603a8fc0db41b1a10ecf227fab13303
/3rd/n3/code/extlibs/bullet/fw/include/win32/FWWin32Input.h
b0d6076b3947670ee9819879a1ea59a6f2be980a
[]
no_license
JerryZhou/opensc
118a1dc0595490c0f218d9a2e4325002be7fe254
28e685feaa302f174fbb2c0f6a60f597f497fdd9
refs/heads/master
2020-06-08T04:09:55.527373
2013-09-22T03:28:44
2013-09-22T03:28:44
11,479,319
1
0
null
null
null
null
UTF-8
C++
false
false
4,911
h
/* SCE CONFIDENTIAL * $PSLibId$ * Copyright (C) 2006 Sony Computer Entertainment Inc. * All Rights Reserved. */ //----------------------------------------------------------------------------- // Sample Framework // // Win32 Input // // $File: //nextgendev/Framework_080/include/win32/FWWin32Input.h $ // $Author: asidwell $ // $Date: 2006/01/06 $ // $Revision: #1 $ // // Copyright (C) 2006 Sony Computer Entertainment. // All Rights Reserved. // //----------------------------------------------------------------------------- #ifndef __FW_WIN32INPUT_H__ #define __FW_WIN32INPUT_H__ #define DIRECTINPUT_VERSION 0x0800 #include <windows.h> #include <dinput.h> // platform specific mouse info class FWWin32MouseInfo { public: bool mIsWithinClientArea; // mouse inside client area LPDIRECTINPUTDEVICE8 mpDevice; // pointer to dinput device }; // keyboard mapping to direct input key offsets static unsigned char sKeyboardMap[256] = { DIK_A, //Channel_Key_A, DIK_B, //Channel_Key_B, DIK_C, //Channel_Key_C, DIK_D, //Channel_Key_D, DIK_E, //Channel_Key_E, DIK_F, //Channel_Key_F, DIK_G, //Channel_Key_G, DIK_H, //Channel_Key_H, DIK_I, //Channel_Key_I, DIK_J, //Channel_Key_J, DIK_K, //Channel_Key_K, DIK_L, //Channel_Key_L, DIK_M, //Channel_Key_M, DIK_N, //Channel_Key_N, DIK_O, //Channel_Key_O, DIK_P, //Channel_Key_P, DIK_Q, //Channel_Key_Q, DIK_R, //Channel_Key_R, DIK_S, //Channel_Key_S, DIK_T, //Channel_Key_T, DIK_U, //Channel_Key_U, DIK_V, //Channel_Key_V, DIK_W, //Channel_Key_W, DIK_X, //Channel_Key_X, DIK_Y, //Channel_Key_Y, DIK_Z, //Channel_Key_Z, DIK_1, //Channel_Key_1, DIK_2, //Channel_Key_2, DIK_3, //Channel_Key_3, DIK_4, //Channel_Key_4, DIK_5, //Channel_Key_5, DIK_6, //Channel_Key_6, DIK_7, //Channel_Key_7, DIK_8, //Channel_Key_8, DIK_9, //Channel_Key_9, DIK_0, //Channel_Key_0, DIK_ESCAPE, //Channel_Key_Escape, DIK_F1, //Channel_Key_F1, DIK_F2, //Channel_Key_F2, DIK_F3, //Channel_Key_F3, DIK_F4, //Channel_Key_F4, DIK_F5, //Channel_Key_F5, DIK_F6, //Channel_Key_F6, DIK_F7, //Channel_Key_F7, DIK_F8, //Channel_Key_F8, DIK_F9, //Channel_Key_F9, DIK_F10, //Channel_Key_F10, DIK_F11, //Channel_Key_F11, DIK_F12, //Channel_Key_F12, DIK_RETURN, //Channel_Key_Enter, DIK_BACK, //Channel_Key_Backspace, DIK_TAB, //Channel_Key_Tab, DIK_SPACE, //Channel_Key_Space, DIK_MINUS, //Channel_Key_Minus, DIK_EQUALS, //Channel_Key_Equals, DIK_LBRACKET, //Channel_Key_LeftBracket, DIK_RBRACKET, //Channel_Key_RightBracket, DIK_BACKSLASH, //Channel_Key_Backslash, DIK_SEMICOLON, //Channel_Key_Semicolon DIK_APOSTROPHE, //Channel_Key_Apostrophe DIK_COMMA, //Channel_Key_Comma, DIK_PERIOD, //Channel_Key_Period, DIK_SLASH, //Channel_Key_Slash, DIK_LEFT, //Channel_Key_Left, DIK_RIGHT, //Channel_Key_Right, DIK_UP, //Channel_Key_Up, DIK_DOWN, //Channel_Key_Down, DIK_HOME, //Channel_Key_Home, DIK_END, //Channel_Key_End, DIK_PRIOR, //Channel_Key_PageUp, DIK_NEXT, //Channel_Key_PageDown, DIK_INSERT, //Channel_Key_Insert, DIK_DELETE, //Channel_Key_Delete, DIK_NUMPAD1, //Channel_Key_Numpad_1, DIK_NUMPAD2, //Channel_Key_Numpad_2, DIK_NUMPAD3, //Channel_Key_Numpad_3, DIK_NUMPAD4, //Channel_Key_Numpad_4, DIK_NUMPAD5, //Channel_Key_Numpad_5, DIK_NUMPAD6, //Channel_Key_Numpad_6, DIK_NUMPAD7, //Channel_Key_Numpad_7, DIK_NUMPAD8, //Channel_Key_Numpad_8, DIK_NUMPAD9, //Channel_Key_Numpad_9, DIK_NUMPAD0, //Channel_Key_Numpad_0, DIK_DIVIDE, //Channel_Key_Numpad_Slash, DIK_MULTIPLY, //Channel_Key_Numpad_Asterisk, DIK_SUBTRACT, //Channel_Key_Numpad_Minus, DIK_ADD, //Channel_Key_Numpad_Plus, DIK_NUMPADENTER,//Channel_Key_Numpad_Enter, DIK_DECIMAL, //Channel_Key_Numpad_Period, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; #endif//__FW_WIN32INPUT_H__ // Local variables: // indent-tabs-mode: t // tab-width: 4 // End: // vim:ts=4:sw=4
[ "JerryZhou@outlook.com" ]
JerryZhou@outlook.com
25963bc5f5842ffdd2909a8a32d50d5bb882cd46
da510e8caaa2791a1f7f11eb207f10fbe620cb0d
/games/src/Ghost.cpp
5ff9679f58b377fe995a3c16866dc54bdbc4d660
[]
no_license
LeBenki/arcade
d19d76a7d0b66d0f69994061b7f945c7d5acdd8e
0360b8ec80bb1fd85793a83355b9c89a1e981ea5
refs/heads/master
2020-03-24T03:42:30.612168
2018-08-02T11:39:41
2018-08-02T11:39:41
142,429,800
1
0
null
null
null
null
UTF-8
C++
false
false
1,571
cpp
/* ** EPITECH PROJECT, 2018 ** Ghost.cpp ** File description: ** Ghost entity class file */ #include "Ghost.hpp" arc::Ghost::Ghost(const arc::pos_t &pos, const unsigned int level, const unsigned int id) : arc::APacmanEntity("Ghost" + std::to_string(id % 4 + 1)) { _pos = {(float)(pos.x + 0.5), (float)(pos.y + 0.5)}; _health = 1; _speed = GHOSTSPEED * (1 + level * 0.5); _id = id; } void arc::Ghost::findPath(std::vector<std::vector<int>> distances, const std::vector<std::string> &map, const bool mode) { Direction target = DIR_UNDEFINED; int dist = -1; posf_t posTo; for (int i = 1; i < 5; i++) { posTo = getNextTile(_pos, (arc::Direction)i, map); if (_health == 0 && _distances[posTo.y][posTo.x] != -2 && (dist == -1 || _distances[posTo.y][posTo.x] < dist)) { target = (Direction)i; dist = _distances[posTo.y][posTo.x]; } else if (_health > 0 && distances[posTo.y][posTo.x] != -2 && (dist == -1 || (mode) ? distances[posTo.y][posTo.x] > dist : distances[posTo.y][posTo.x] < dist)) { target = (arc::Direction)i; dist = distances[posTo.y][posTo.x]; } } _direction = target; } void arc::Ghost::updateAnimation(const std::vector<std::string> &map) { std::chrono::milliseconds now = std::chrono::duration_cast< std::chrono::milliseconds>(std::chrono::system_clock::now() .time_since_epoch()); (void)map; if (now.count() - _lastUpdate.count() > ANIMATION_FREQUENCY / (_speed / GHOSTSPEED)) { _lastUpdate = now; _animationStatus = _animationStatus + 1 > 1 ? 0 : _animationStatus + 1; } }
[ "lucas.benkemoun@epitech.Eu" ]
lucas.benkemoun@epitech.Eu
4affec17d1d45ea635b2b85555fd49a59c51f24a
376b40b62f996ecc6665de0e0bc9735bf6a18268
/src/core/buffer/AsyncFrameBuffer.h
c028562f96f434be4b1b6046c0298e12884d7c6f
[ "MIT" ]
permissive
PearCoding/PearRay
f687863b3bc722240997fb0b3d22e5032d91b7b8
95f065adb20fc6202dfa40140d0308fc605dc440
refs/heads/master
2022-05-02T01:01:28.462545
2022-04-13T09:52:16
2022-04-13T09:52:16
45,111,096
20
0
MIT
2020-06-22T11:32:21
2015-10-28T12:33:36
C++
UTF-8
C++
false
false
2,414
h
#pragma once #include "FrameBuffer.h" #include <vector> namespace PR { template <typename T> class AsyncFrameBuffer { PR_CLASS_NON_COPYABLE(AsyncFrameBuffer); public: inline AsyncFrameBuffer(Size1i channels, const Size2i& size, const T& clear_value = T(), bool never_clear = false) : mFrameBuffer(channels, size, clear_value, never_clear) , mLocks(size) { } inline ~AsyncFrameBuffer() { } inline const Size2i& size() const { return mFrameBuffer.size(); } inline Size1i width() const { return mFrameBuffer.width(); } inline Size1i widthPitch() const { return mFrameBuffer.widthPitch(); } inline Size1i widthBytePitch() const { return mFrameBuffer.widthBytePitch(); } inline Size1i height() const { return mFrameBuffer.height(); } inline Size1i heightPitch() const { return mFrameBuffer.heightPitch(); } inline Size1i heightBytePitch() const { return mFrameBuffer.heightBytePitch(); } inline Size1i channels() const { return mFrameBuffer.channels(); } inline Size1i channelPitch() const { return mFrameBuffer.channelPitch(); } inline Size1i channelBytePitch() const { return mFrameBuffer.channelBytePitch(); } inline void setNeverClear(bool b) { mFrameBuffer.setNeverClear(b); } inline bool isNeverCleared() const { return mFrameBuffer.isNeverCleared(); } inline void setFragment(const Point2i& p, Size1i channel, const T& v) { mLocks.lock(p); mFrameBuffer.setFragment(p, channel, v); mLocks.unlock(p); } inline T getFragment(const Point2i& p, Size1i channel) const { mLocks.lock(p); const T ret = mFrameBuffer.getFragment(p, channel); mLocks.unlock(p); return ret; } inline void setFragment(Size1i pixelindex, Size1i channel, const T& v) { mLocks.lock(p); mFrameBuffer.setFragment(pixelindex, channel, v); mLocks.unlock(p); } inline T getFragment(Size1i pixelindex, Size1i channel = 0) const { mLocks.lock(p); const T ret = mFrameBuffer.getFragment(p, channel); mLocks.unlock(p); return ret; } inline const T* ptr() const { return mData.data(); } inline T* ptr() { return mData.data(); } inline void clearUnsafe(bool force = false) { mFrameBuffer.clear(force); } inline void fillUnsafe(const T& v) { mFrameBuffer.fill(v); } private: FrameBuffer<T> mFrameBuffer; PixelLock mLocks; }; typedef AsyncFrameBuffer<float> AsyncFrameBufferFloat; typedef AsyncFrameBuffer<uint32> AsyncFrameBufferUInt32; } // namespace PR
[ "yazici@cg.uni-saarland.de" ]
yazici@cg.uni-saarland.de
074969dd07cb25669ac1b95fc37176a4c08ecfc9
a0f0efaaaf69d6ccdc2a91596db29f04025f122c
/install/pnp_msgs/include/pnp_msgs/PNPConditionRequest.h
45da55705fb3a2fce47329a8174d417aa26b0b27
[]
no_license
chiuhandsome/ros_ws_test-git
75da2723154c0dadbcec8d7b3b1f3f8b49aa5cd6
619909130c23927ccc902faa3ff6d04ae0f0fba9
refs/heads/master
2022-12-24T05:45:43.845717
2020-09-22T10:12:54
2020-09-22T10:12:54
297,582,735
0
0
null
null
null
null
UTF-8
C++
false
false
5,093
h
// Generated by gencpp from file pnp_msgs/PNPConditionRequest.msg // DO NOT EDIT! #ifndef PNP_MSGS_MESSAGE_PNPCONDITIONREQUEST_H #define PNP_MSGS_MESSAGE_PNPCONDITIONREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace pnp_msgs { template <class ContainerAllocator> struct PNPConditionRequest_ { typedef PNPConditionRequest_<ContainerAllocator> Type; PNPConditionRequest_() : cond() { } PNPConditionRequest_(const ContainerAllocator& _alloc) : cond(_alloc) { (void)_alloc; } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _cond_type; _cond_type cond; typedef boost::shared_ptr< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> const> ConstPtr; }; // struct PNPConditionRequest_ typedef ::pnp_msgs::PNPConditionRequest_<std::allocator<void> > PNPConditionRequest; typedef boost::shared_ptr< ::pnp_msgs::PNPConditionRequest > PNPConditionRequestPtr; typedef boost::shared_ptr< ::pnp_msgs::PNPConditionRequest const> PNPConditionRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> >::stream(s, "", v); return s; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator==(const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator1> & lhs, const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator2> & rhs) { return lhs.cond == rhs.cond; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator!=(const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator1> & lhs, const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator2> & rhs) { return !(lhs == rhs); } } // namespace pnp_msgs namespace ros { namespace message_traits { template <class ContainerAllocator> struct IsFixedSize< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > { static const char* value() { return "ae73c3f52927beed1a1deae4df67effb"; } static const char* value(const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xae73c3f52927beedULL; static const uint64_t static_value2 = 0x1a1deae4df67effbULL; }; template<class ContainerAllocator> struct DataType< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > { static const char* value() { return "pnp_msgs/PNPConditionRequest"; } static const char* value(const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > { static const char* value() { return "string cond\n" ; } static const char* value(const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.cond); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct PNPConditionRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator>& v) { s << indent << "cond: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.cond); } }; } // namespace message_operations } // namespace ros #endif // PNP_MSGS_MESSAGE_PNPCONDITIONREQUEST_H
[ "chiuhandsome1966@gmail.com" ]
chiuhandsome1966@gmail.com
1c0abe3d770f5f4f87770204d64740edc628c4df
4fe6b129a2f415b22f1c8752169b56daf8551e23
/Aligner/TiltCalibrationPage3.cpp
6045d5e91e2c73d2e0b61452fece8d6b1d71566e
[]
no_license
Kingarne/Aligner308MK3
1821d6ce9a8cd6d3e6def31bb43cd0c37b43fe1e
04adc7e1ca1e97e2b4165c626dd73f095ad77c93
refs/heads/master
2023-08-31T05:48:52.441714
2023-08-21T13:14:32
2023-08-21T13:14:32
207,835,311
0
1
null
null
null
null
UTF-8
C++
false
false
2,221
cpp
// $Id: TiltCalibrationPage3.cpp,v 1.3 2014-07-15 13:22:33 riar Exp $ // // Copyright (C) Shill Reglerteknik AB 2002 #include "stdafx.h" #include "TiltCalibrationPage3.h" #include "CalibrationSheet.h" IMPLEMENT_DYNAMIC(TiltCalibrationPage3, CPropertyPage) TiltCalibrationPage3::TiltCalibrationPage3( void ) : CPropertyPage(TiltCalibrationPage3::IDD) { // Empty } TiltCalibrationPage3::~TiltCalibrationPage3( void ) { // Empty } void TiltCalibrationPage3::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange( pDX ) ; } BEGIN_MESSAGE_MAP(TiltCalibrationPage3, CPropertyPage) END_MESSAGE_MAP() BOOL TiltCalibrationPage3::OnSetActive( void ) { CalibrationSheet *pSheet = static_cast<CalibrationSheet *>(GetParent()) ; ASSERT(pSheet -> IsKindOf( RUNTIME_CLASS(CalibrationSheet) )) ; pSheet -> PlotConverted( 2 ) ; pSheet -> m_measurement = 2 ; pSheet -> SetWizardButtons( PSWIZB_BACK | PSWIZB_NEXT ) ; MoveDlgToRightSideOfApp(pSheet); inProgress = false; return __super::OnSetActive() ; } LRESULT TiltCalibrationPage3::OnWizardNext( void ) { if(inProgress) { inProgress = false; return CPropertyPage::OnWizardNext(); } CalibrationSheet *pSheet = static_cast<CalibrationSheet *>(GetParent()) ; ASSERT(pSheet -> IsKindOf( RUNTIME_CLASS(CalibrationSheet) )) ; inProgress = true; pSheet -> SetWizardButtons( 0 ) ; pSheet -> StartMeasurement() ; return -1 ; } BOOL TiltCalibrationPage3::OnQueryCancel( void ) { CalibrationSheet *pSheet = static_cast<CalibrationSheet *>(GetParent()) ; ASSERT(pSheet -> IsKindOf( RUNTIME_CLASS(CalibrationSheet) )) ; pSheet -> StopMeasurement() ; pSheet -> SetWizardButtons( PSWIZB_NEXT | PSWIZB_BACK ) ; return IDYES == ::AfxMessageBox( IDS_REALY_ABORT, MB_YESNO | MB_DEFBUTTON2 ) ; } LRESULT TiltCalibrationPage3::OnWizardBack( void ) { CalibrationSheet *pSheet = static_cast<CalibrationSheet *>(GetParent()) ; ASSERT(pSheet -> IsKindOf( RUNTIME_CLASS(CalibrationSheet) )) ; if (pSheet -> IsMeasuring()) { pSheet -> StopMeasurement() ; pSheet -> SetWizardButtons( PSWIZB_NEXT | PSWIZB_BACK ) ; return -1 ; } return IDYES != ::AfxMessageBox( IDS_REALY_BACK, MB_YESNO | MB_DEFBUTTON2 ) ; }
[ "riar@now.se" ]
riar@now.se
2e1947524297a95429c1a81937b6c253756bef76
48a73a0ba850ac2925118dd304baa8f7b2874582
/C++/source/Framework/ObjectRelationalMapping/RelationshipInfoFromSchemaDifference.cpp
4af631b6afd62673a1f66b385e6fdd8d05d10ecf
[ "Apache-2.0" ]
permissive
cxvisa/Wave
5e66dfbe32c85405bc2761c509ba8507ff66f8fe
1aca714933ff1df53d660f038c76ca3f2202bf4a
refs/heads/master
2021-05-03T15:00:49.991391
2018-03-31T23:06:40
2018-03-31T23:06:40
56,774,204
2
1
null
null
null
null
UTF-8
C++
false
false
7,063
cpp
/** *@file RelationshipInfoFromSchemaDifference.h * Copyright (C) 2011 Brocade Communications Systems,Inc. * All rights reserved. * Description: This file declares the class that stores the info regarding a relation * It will be used in the context of storing the added/removed relationships * for each table. * * * Author : Aashish Akhouri * Date : 10/20/2011 */ #include "Framework/ObjectRelationalMapping/RelationshipInfoFromSchemaDifference.h" #include "Framework/Utils/TraceUtils.h" namespace WaveNs { RelationshipInfoFromSchemaDifference::RelationshipInfoFromSchemaDifference (const string & relationName, const string & relatedToTable, OrmRelationUmlType relationUmlType, OrmRelationType relationType, bool disableValidations, bool canBeEmpty) : m_relationName (relationName), m_relatedToTable (relatedToTable), m_relationUmlType (relationUmlType), m_relationType (relationType), m_disableValidations (disableValidations), m_canBeEmpty (canBeEmpty), m_changedRelationshipAttributes (0) { } RelationshipInfoFromSchemaDifference::RelationshipInfoFromSchemaDifference (string relationName, string relationFieldType) { m_relationName = relationName; vector<string> tokens; tokenize(relationFieldType, tokens, '-'); if (tokens[0]=="a") { m_relationUmlType = ORM_RELATION_UML_TYPE_ASSOCIATION; } else if (tokens[0]=="c") { m_relationUmlType = ORM_RELATION_UML_TYPE_COMPOSITION; } else if (tokens[0]=="g") { m_relationUmlType = ORM_RELATION_UML_TYPE_AGGREGATION; } if (tokens[1]=="1") { m_relationType = ORM_RELATION_TYPE_ONE_TO_ONE; } else if (tokens[1]=="m") { m_relationType = ORM_RELATION_TYPE_ONE_TO_MANY; } vector<string>tkns; tokenize(tokens[2],tkns,'|'); m_relatedToTable = tkns[0]; if (tkns[2] == "0") { m_disableValidations = false; } else { m_disableValidations = true; } if (tkns[3] == "0") { m_canBeEmpty = false; } else { m_canBeEmpty = true; } m_changedRelationshipAttributes = 0; } const RelationshipInfoFromSchemaDifference & RelationshipInfoFromSchemaDifference::operator= (const RelationshipInfoFromSchemaDifference & relationInfo) { if(this != &relationInfo) { m_relationName = relationInfo.getRelationName (); m_relatedToTable = relationInfo.getRelatedToTable (); m_relationUmlType = relationInfo.getRelationUmlType (); m_relationType = relationInfo.getRelationType (); m_disableValidations = relationInfo.getDisableValidations (); m_canBeEmpty = relationInfo.getCanBeEmpty (); m_changedRelationshipAttributes = relationInfo.getChangedRelationshipAttributes (); } return (*this); } RelationshipInfoFromSchemaDifference::RelationshipInfoFromSchemaDifference (const RelationshipInfoFromSchemaDifference & relationInfo) { m_relationName = relationInfo.getRelationName (); m_relatedToTable = relationInfo.getRelatedToTable (); m_relationUmlType = relationInfo.getRelationUmlType (); m_relationType = relationInfo.getRelationType (); m_disableValidations = relationInfo.getDisableValidations (); m_canBeEmpty = relationInfo.getCanBeEmpty (); m_changedRelationshipAttributes = relationInfo.getChangedRelationshipAttributes (); } RelationshipInfoFromSchemaDifference::~RelationshipInfoFromSchemaDifference () { } const string & RelationshipInfoFromSchemaDifference::getRelationName () const { return (m_relationName); } const string & RelationshipInfoFromSchemaDifference::getRelatedToTable () const { return (m_relatedToTable); } OrmRelationUmlType RelationshipInfoFromSchemaDifference::getRelationUmlType () const { return (m_relationUmlType); } OrmRelationType RelationshipInfoFromSchemaDifference::getRelationType () const { return (m_relationType); } bool RelationshipInfoFromSchemaDifference::getDisableValidations () const { return (m_disableValidations); } bool RelationshipInfoFromSchemaDifference::getCanBeEmpty () const { return (m_canBeEmpty); } UI8 RelationshipInfoFromSchemaDifference::getChangedRelationshipAttributes () const { return (m_changedRelationshipAttributes); } bool RelationshipInfoFromSchemaDifference::isChangedRelationship () const { if (0 == m_changedRelationshipAttributes) { return false; } return true; } void RelationshipInfoFromSchemaDifference::setCanBeEmptyChanged () { m_changedRelationshipAttributes = ((m_changedRelationshipAttributes) | 0x01); } bool RelationshipInfoFromSchemaDifference::isCanBeEmptyChanged () const { if (0x01 == ((m_changedRelationshipAttributes) & 0x01)) { return true; } return false; } void RelationshipInfoFromSchemaDifference::setDisableValidationChanged () { m_changedRelationshipAttributes = ((m_changedRelationshipAttributes) | 0x02); } bool RelationshipInfoFromSchemaDifference::isDisableValidationChanged () const { if (0x02 == ((m_changedRelationshipAttributes) & 0x02)) { return true; } return false; } void RelationshipInfoFromSchemaDifference::printContentsForDebugging () { if (isChangedRelationship ()) { tracePrintf (TRACE_LEVEL_INFO, false, false, " Relation Name : %s is a changed Relationship\n",m_relationName.c_str()); if (isCanBeEmptyChanged ()) { tracePrintf (TRACE_LEVEL_INFO, false, false, " Can Be Empty is modified in this relation and it is now set to : %d\n", m_canBeEmpty); } if (isDisableValidationChanged ()) { tracePrintf (TRACE_LEVEL_INFO, false, false, " Disable Validation is modified in this relation and it is now set to : %d\n", m_disableValidations); } } tracePrintf (TRACE_LEVEL_INFO, false, false, " Relation Name : %s\n",m_relationName.c_str()); tracePrintf (TRACE_LEVEL_INFO, false, false, " Related To Table : %s\n",m_relatedToTable.c_str()); if (m_relationUmlType == ORM_RELATION_UML_TYPE_ASSOCIATION) { trace (TRACE_LEVEL_INFO, " Relation UML Type : Association"); } else if (m_relationUmlType == ORM_RELATION_UML_TYPE_AGGREGATION) { trace (TRACE_LEVEL_INFO, " Relation UML Type : Aggregation"); } else if (m_relationUmlType == ORM_RELATION_UML_TYPE_COMPOSITION) { trace (TRACE_LEVEL_INFO, " Relation UML Type : Composition"); } if (m_relationType == ORM_RELATION_TYPE_ONE_TO_ONE) { trace (TRACE_LEVEL_INFO, " Relation Type : One to One"); } else if (m_relationType == ORM_RELATION_TYPE_ONE_TO_MANY) { trace (TRACE_LEVEL_INFO, " Relation Type : One to Many"); } tracePrintf (TRACE_LEVEL_INFO, false, false, " Disable Validations is set to : %d\n",m_disableValidations); tracePrintf (TRACE_LEVEL_INFO, false, false, " Can Be Empty is set to : %d\n",m_canBeEmpty); } }
[ "sagar@wave.sagar.cisco.com" ]
sagar@wave.sagar.cisco.com
f39b3eb935a5defcde6d8572a443ab49ced81265
b8376621d63394958a7e9535fc7741ac8b5c3bdc
/lib/lib_mech/src/server/AqServer/AqCentral/AqCentral.cpp
ec94ec3bde6681a7cede8fa66875041b16852c61
[]
no_license
15831944/job_mobile
4f1b9dad21cb7866a35a86d2d86e79b080fb8102
ebdf33d006025a682e9f2dbb670b23d5e3acb285
refs/heads/master
2021-12-02T10:58:20.932641
2013-01-09T05:20:33
2013-01-09T05:20:33
null
0
0
null
null
null
null
UHC
C++
false
false
1,776
cpp
// AqCentral.cpp : DLL 응용 프로그램을 위해 내보낸 함수를 정의합니다. // #include "stdafx.h" #include "AqCentral.h" #include <boost/bind.hpp> #include "csv_loader.h" #include "../AqCommon/jXmlSaveManager.h" Aq_NetDLL* g_pjConsoleDLL=0; void _OnPacketSize_UsageInfo(tcstr szPlugIn,uint64 packet_size,tname1024_t info) { g_jAqCommon.OnPacketSize_UsageInfo(szPlugIn,packet_size); } extern "C" { AQCENTRAL_API void* jCreateInterface(jIE* pE) { init_common_AQ(); /* tfname_t szDir; Load_Common_CSV(szDir); //jFOR_EACH(pCM->m_Sys_LocalizingText.m_List , boost::bind(&Sys_LocalizingText::jDebugPrint,_1)); Sys_LocalizingText* pN = jCSV(Sys_LocalizingText).find(jS(we_are_fiend)); if(pN) { pN->jDebugPrint(); } else { GetjILog()->Warning( _T("Sys_LocalizingText : we_are_fiend : not found") ); } */ if(g_pjConsoleDLL) return g_pjConsoleDLL; g_pjConsoleDLL = new Aq_NetDLL(); nInterface::g_pjINet_OGS->RunMessageThread(); nInterface::g_pjINet_OGS->SetCallback_PacketSize_UsageInfo(_OnPacketSize_UsageInfo); return g_pjConsoleDLL; } AQCENTRAL_API void jDeleteInterface() { SAFE_DELETE(g_pjConsoleDLL); } AQCENTRAL_API acstr jGetModuleOwnerName() { return "icandoit"; } } bool Aq_NetDLL::ParseCmd(tcstr szCommand) { if( parent_t::ParseCmd(szCommand) ) return true; //여기에 코드를 추가하시오 if(!g_pCurrPlugIn) return false; return g_pCurrPlugIn->ParseCmd(szCommand); } bool Aq_NetDLL::Start(tcstr szNetConfigFile,tcstr szNetConfig_Name) { if(!parent_t::Start(szNetConfigFile,szNetConfig_Name)) return false; // 여기에 코드를 추가하시오 return true; } void Aq_NetDLL::End() { //여기에 코드를 추가하시오 g_jXmlSaveManager.Destory(); parent_t::End(); }
[ "whdnrfo@gmail.com" ]
whdnrfo@gmail.com
86b06258526acab138213f35e6eadd055b1e2769
dccd1058e723b6617148824dc0243dbec4c9bd48
/atcoder/arc036/b.cpp
7d80832839e6ae2d5b8a82f4540dd8f4b5781436
[]
no_license
imulan/procon
488e49de3bcbab36c624290cf9e370abfc8735bf
2a86f47614fe0c34e403ffb35108705522785092
refs/heads/master
2021-05-22T09:24:19.691191
2021-01-02T14:27:13
2021-01-02T14:27:13
46,834,567
7
1
null
null
null
null
UTF-8
C++
false
false
836
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i,n) for(i=0;i<n;++i) #define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr) #define mp make_pair #define pb push_back #define fi first #define sc second int main(int argc, char const *argv[]) { int i; int n; cin >>n; std::vector<int> h(n); rep(i,n) scanf(" %d",&h[i]); std::vector<int> v; v.pb(0); int now=0; rep(i,n-1){ if(h[i+1]-h[i]>0){ if(now<0){ v.pb(now); now=0; } ++now; } else{ if(now>0){ v.pb(now); now=0; } --now; } } if(now!=0) v.pb(now); v.pb(0); int ans=0; rep(i,(int)v.size()-1){ if(v[i]>=0&&v[i+1]<=0){ ans=max(ans,v[i]-v[i+1]+1); } } std::cout << ans << std::endl; return 0; }
[ "k0223.teru@gmail.com" ]
k0223.teru@gmail.com
b7808a2833e69a7500da4523732a15eb3d10600f
a6b7e6ff776bf577c7f63926edf3b236ec2ec917
/Protótipos_ESP8266_IDE-Arduino/ANDRE_SINAL/ANDRE_SINAL.ino
b042dff4f36b1f0f12e5f35faa626446cf30eb6d
[ "MIT" ]
permissive
francenylson/Robotica_ESP8266
a4f51cd0b2c322f8d52380f210cd7ee9f250ba25
882568b2656d319144aa19b3f34a0caf3c132b22
refs/heads/master
2022-12-05T11:14:10.715099
2020-08-28T15:36:43
2020-08-28T15:36:43
291,081,432
0
0
null
null
null
null
UTF-8
C++
false
false
2,690
ino
#define led_1 D0 //verde direito #define led_2 D1 //amarelo direito #define led_3 D2 //vermelho direito #define led_4 D3 //azul #define led_5 D4 //azul #define led_6 D5 //azul #define led_7 D6 //azul #define led_8 D7 //azul #define led_9 D8 void setup() { pinMode(led_1, OUTPUT); pinMode(led_2, OUTPUT); pinMode(led_3, OUTPUT); pinMode(led_4, OUTPUT); pinMode(led_5, OUTPUT); pinMode(led_6, OUTPUT); pinMode(led_7, OUTPUT); pinMode(led_8, OUTPUT); pinMode(led_9, OUTPUT); } void loop() { digitalWrite(led_1, HIGH); digitalWrite(led_2, LOW); digitalWrite(led_3, LOW); digitalWrite(led_4, HIGH); digitalWrite(led_5, LOW); digitalWrite(led_6, LOW); digitalWrite(led_7, HIGH); digitalWrite(led_8, LOW); digitalWrite(led_9, LOW); delay(3000); digitalWrite(led_1, HIGH); digitalWrite(led_2, LOW); digitalWrite(led_3, LOW); digitalWrite(led_4, LOW); digitalWrite(led_5, HIGH); digitalWrite(led_6, LOW); digitalWrite(led_7, HIGH); digitalWrite(led_8, LOW); digitalWrite(led_9, LOW); delay(2000); digitalWrite(led_1, LOW); digitalWrite(led_2, LOW); digitalWrite(led_3, HIGH); digitalWrite(led_4, LOW); digitalWrite(led_5, LOW); digitalWrite(led_6, HIGH); digitalWrite(led_7, LOW); digitalWrite(led_8, HIGH); digitalWrite(led_9, LOW); delay(2000); digitalWrite(led_1, LOW); digitalWrite(led_2, LOW); digitalWrite(led_3, HIGH); digitalWrite(led_4, LOW); digitalWrite(led_5, LOW); digitalWrite(led_6, HIGH); digitalWrite(led_7, LOW); digitalWrite(led_8, HIGH); digitalWrite(led_9, LOW); delay(2000); digitalWrite(led_1, LOW); digitalWrite(led_2, HIGH); digitalWrite(led_3, LOW); digitalWrite(led_4, LOW); digitalWrite(led_5, LOW); digitalWrite(led_6, HIGH); digitalWrite(led_7, HIGH); digitalWrite(led_8, LOW); digitalWrite(led_9, LOW); delay(2000); digitalWrite(led_1, HIGH); digitalWrite(led_2, LOW); digitalWrite(led_3, LOW); digitalWrite(led_4, HIGH); digitalWrite(led_5, LOW); digitalWrite(led_6, LOW); digitalWrite(led_7, HIGH); digitalWrite(led_8, HIGH); digitalWrite(led_9, LOW); delay(2000); digitalWrite(led_1, LOW); digitalWrite(led_2, HIGH); digitalWrite(led_3, LOW); digitalWrite(led_4, LOW); digitalWrite(led_5, LOW); digitalWrite(led_6, HIGH); digitalWrite(led_7, LOW); digitalWrite(led_8, LOW); digitalWrite(led_9, LOW); delay(2000); digitalWrite(led_1, LOW); digitalWrite(led_2, HIGH); digitalWrite(led_3, LOW); digitalWrite(led_4, LOW); digitalWrite(led_5, LOW); digitalWrite(led_6, HIGH); digitalWrite(led_7, LOW); digitalWrite(led_8, LOW); digitalWrite(led_9, LOW); delay(2000); }
[ "francenylson@gmail.com" ]
francenylson@gmail.com
c5d6b437b939d10b8a7d314d0a600e0ba112a0b1
c955730b68bd4ba2d9255183cfef092bd1ef2524
/CPP/chocoland.cpp
3d37c55fa71d75fad26834c5d97b202e00ecf4cd
[]
no_license
Manvi07/Competitive-programming
b6e95c2e8bc9673d9e23e784c460d50ed3754ab1
7b59d89988667b115500482691b3ae89c397d753
refs/heads/master
2020-05-19T06:12:07.019076
2020-05-08T09:22:16
2020-05-08T09:22:16
184,867,764
1
0
null
null
null
null
UTF-8
C++
false
false
280
cpp
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n,k,s; cin>>n>>k>>s; int d=s-s/7;int b=0; if(k*s>n*d)b=-1; else { while(1){ b++; if(b*n>=k*s) break;} } cout<<b<<endl; } }
[ "b17092@students.iitmandi.ac.in" ]
b17092@students.iitmandi.ac.in
cb6821270b6df9f5231b97e5bb6c491ec05917f6
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.h
9f2913252f11f98cf93ae9287fe5f25a9cdbbb7a
[ "MIT", "NCSA", "BSD-3-Clause", "NTP", "LicenseRef-scancode-unknown-license-reference" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
2,066
h
//===-- PPCMCTargetDesc.h - PowerPC Target Descriptions ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides PowerPC specific target descriptions. // //===----------------------------------------------------------------------===// #ifndef PPCMCTARGETDESC_H #define PPCMCTARGETDESC_H // GCC #defines PPC on Linux but we use it as our namespace name #undef PPC #include "llvm/Support/DataTypes.h" namespace llvm { class MCAsmBackend; class MCCodeEmitter; class MCContext; class MCInstrInfo; class MCObjectWriter; class MCRegisterInfo; class MCSubtargetInfo; class Target; class StringRef; class raw_ostream; extern Target ThePPC32Target; extern Target ThePPC64Target; extern Target ThePPC64LETarget; MCCodeEmitter *createPPCMCCodeEmitter(const MCInstrInfo &MCII, const MCRegisterInfo &MRI, const MCSubtargetInfo &STI, MCContext &Ctx); MCAsmBackend *createPPCAsmBackend(const Target &T, StringRef TT, StringRef CPU); /// createPPCELFObjectWriter - Construct an PPC ELF object writer. MCObjectWriter *createPPCELFObjectWriter(raw_ostream &OS, bool Is64Bit, uint8_t OSABI); } // End llvm namespace // Generated files will use "namespace PPC". To avoid symbol clash, // undefine PPC here. PPC may be predefined on some hosts. #undef PPC // Defines symbolic names for PowerPC registers. This defines a mapping from // register name to register number. // #define GET_REGINFO_ENUM #include "PPCGenRegisterInfo.inc" // Defines symbolic names for the PowerPC instructions. // #define GET_INSTRINFO_ENUM #include "PPCGenInstrInfo.inc" #define GET_SUBTARGETINFO_ENUM #include "PPCGenSubtargetInfo.inc" #endif
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
cf96835845de5aeaf4cf803b74175b0ce93499fa
aaf052bb772a863f86512724373f51a2b6e39576
/include/smp/components/samplers/theta_star_gaussian.hpp
b267b9483ac91e6dcf4bdc3bd6f06ed57ed893f1
[ "BSD-2-Clause" ]
permissive
HsiaoRay/proxemics_anytimerrts
0cec5c1736ebd1df38319e24bf22ab1dd55475e1
6d1c76e04ace18d53af91c3bfcfc9eddbb9fec60
refs/heads/master
2020-07-07T13:35:44.064098
2016-06-16T15:13:48
2016-06-16T15:13:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,667
hpp
#ifndef _SMP_SAMPLER_GAUSS_HPP_ #define _SMP_SAMPLER_GAUSS_HPP_ #include <iostream> #include <cstdlib> #include <smp/components/samplers/theta_star_gaussian.h> #include <smp/components/samplers/base.hpp> #include "eigenmultivariatenormal.cpp" template< class typeparams, int NUM_DIMENSIONS > int smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::sm_update_insert_vertex (vertex_t *vertex_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::sm_update_insert_edge (edge_t *edge_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::sm_update_delete_vertex (vertex_t *vertex_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::sm_update_delete_edge (edge_t *edge_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::theta_star_gaussian() { // Initialize the sampling distribution support. for (int i = 0; i < NUM_DIMENSIONS; i++) { support.center[i] = 0.0; support.size[i] = 1.0; } } template< class typeparams, int NUM_DIMENSIONS > smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::~theta_star_gaussian () { } /// Sample function for a Circle Region template< class typeparams, int NUM_DIMENSIONS > int smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::sample (state_t **state_sample_out) { // Sampling by Using Multivariate Gaussians Eigen::Vector2d mean; Eigen::Matrix2d covar; Eigen::Vector2d ns; double sigmaxi,sigmayi; if (NUM_DIMENSIONS <= 0) return 0; state_t *state_new = new state_t; mean << support.center[0],support.center[1]; sigmaxi=1; sigmayi=1; Eigen::Matrix2d rot ; rot=Eigen::Rotation2Dd(0).matrix(); covar = rot*Eigen::DiagonalMatrix<double,2,2>(sigmaxi,sigmayi)*rot.transpose(); EigenMultivariateNormal<double,2> *normX = new EigenMultivariateNormal<double,2>(mean,covar); (*normX).reseed(rand()+100*std::time(0)*rand()+std::time(0)); normX->nextSample(ns); // cout<<"DEBUG: sample --x,y--: -- "<<ns(0)<<","<<ns(1)<<endl; (*state_new)[0]=ns(0); (*state_new)[1]=ns(1); (*state_new)[2]=support.ang_range*rand()/(RAND_MAX + 1.0)-support.ang_range/2+support.center[2]; *state_sample_out = state_new; return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::set_support (region_t support_in) { support = support_in; return 1; } #endif
[ "charlyhuang@ira.e.ntu.edu.tw" ]
charlyhuang@ira.e.ntu.edu.tw
a65f1a5bfb772a4a4b3da4486e77663f3749efff
406c354fac53f5bad5eda5fcf2d4dedbaa67340a
/Source/ColorPickerTest419/NativeWidgetHostColorPicker.h
bf6dc7752d261b9e9a000fdc71b26c3a6e7c92e9
[]
no_license
HSeo/ColorPickerTest419
920b518d170211deac83552f44e31578e86ce007
af6ade6032d56cdeb59102e7f4cae579fef2ab3d
refs/heads/master
2020-04-20T04:39:43.535925
2019-03-02T07:29:55
2019-03-02T07:29:55
168,634,448
3
2
null
null
null
null
UTF-8
C++
false
false
546
h
#pragma once #include "CoreMinimal.h" #include "Components/NativeWidgetHost.h" #include "NativeWidgetHostColorPicker.generated.h" class SColorPicker; UCLASS() class COLORPICKERTEST419_API UNativeWidgetHostColorPicker : public UNativeWidgetHost { GENERATED_BODY() public: UNativeWidgetHostColorPicker(const FObjectInitializer& ObjectInitializer); virtual void ReleaseSlateResources(bool bReleaseChildren) override; protected: virtual TSharedRef<SWidget> RebuildWidget() override; private: TSharedPtr<SColorPicker> color_picker_; };
[ "seo@sciement.com" ]
seo@sciement.com
2c44462a1140f06e18bf0a60f6494730d14d3c2c
320aebafb7235465345a4e94aa598e4192663813
/tradeapi/utf8/USTPFtdcMduserApi.h
5fc01a883b74701202683e142e73bc9e49e7ebcc
[]
no_license
charmer1989/node-femas-api
5108f7c9ea9ec1cf66ed074b77fb7ed677bacbd7
6584da6d94dc6c6094000264bee6a99fc65504e8
refs/heads/master
2020-07-27T09:53:40.349144
2016-09-23T07:11:17
2016-09-23T07:11:17
67,613,337
3
0
null
null
null
null
UTF-8
C++
false
false
7,902
h
///////////////////////////////////////////////////////////////////////// ///@system 风控前置系统 ///@company 上海金融期货信息技术有限公司 ///@file USTPFtdcMduserApi.h ///@brief 定义了客户端接口 ///@history ///20130520 徐忠华 创建该文件 ///////////////////////////////////////////////////////////////////////// #if !defined(USTP_FTDCMDUSERAPI_H) #define USTP_FTDCMDUSERAPI_H #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "USTPFtdcUserApiStruct.h" #if defined(ISLIB) && defined(WIN32) #ifdef LIB_MDUSER_API_EXPORT #define MDUSER_API_EXPORT __declspec(dllexport) #else #define MDUSER_API_EXPORT __declspec(dllimport) #endif #else #define MDUSER_API_EXPORT #endif class CUstpFtdcMduserSpi { public: ///当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。 virtual void OnFrontConnected(){}; ///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。 ///@param nReason 错误原因 /// 0x1001 网络读失败 /// 0x1002 网络写失败 /// 0x2001 接收心跳超时 /// 0x2002 发送心跳失败 /// 0x2003 收到错误报文 virtual void OnFrontDisconnected(int nReason){}; ///心跳超时警告。当长时间未收到报文时,该方法被调用。 ///@param nTimeLapse 距离上次接收报文的时间 virtual void OnHeartBeatWarning(int nTimeLapse){}; ///报文回调开始通知。当API收到一个报文后,首先调用本方法,然后是各数据域的回调,最后是报文回调结束通知。 ///@param nTopicID 主题代码(如私有流、公共流、行情流等) ///@param nSequenceNo 报文序号 virtual void OnPackageStart(int nTopicID, int nSequenceNo){}; ///报文回调结束通知。当API收到一个报文后,首先调用报文回调开始通知,然后是各数据域的回调,最后调用本方法。 ///@param nTopicID 主题代码(如私有流、公共流、行情流等) ///@param nSequenceNo 报文序号 virtual void OnPackageEnd(int nTopicID, int nSequenceNo){}; ///错误应答 virtual void OnRspError(CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///风控前置系统用户登录应答 virtual void OnRspUserLogin(CUstpFtdcRspUserLoginField *pRspUserLogin, CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///用户退出应答 virtual void OnRspUserLogout(CUstpFtdcRspUserLogoutField *pRspUserLogout, CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///订阅主题应答 virtual void OnRspSubscribeTopic(CUstpFtdcDisseminationField *pDissemination, CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///主题查询应答 virtual void OnRspQryTopic(CUstpFtdcDisseminationField *pDissemination, CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///深度行情通知 virtual void OnRtnDepthMarketData(CUstpFtdcDepthMarketDataField *pDepthMarketData) {}; ///订阅合约的相关信息 virtual void OnRspSubMarketData(CUstpFtdcSpecificInstrumentField *pSpecificInstrument, CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///退订合约的相关信息 virtual void OnRspUnSubMarketData(CUstpFtdcSpecificInstrumentField *pSpecificInstrument, CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; }; class MDUSER_API_EXPORT CUstpFtdcMduserApi { public: ///创建MduserApi ///@param pszFlowPath 存贮订阅信息文件的目录,默认为当前目录 ///@return 创建出的UserApi static CUstpFtdcMduserApi *CreateFtdcMduserApi(const char *pszFlowPath = ""); ///获取系统版本号 ///@param nMajorVersion 主版本号 ///@param nMinorVersion 子版本号 ///@return 系统标识字符串 static const char *GetVersion(int &nMajorVersion, int &nMinorVersion); ///删除接口对象本身 ///@remark 不再使用本接口对象时,调用该函数删除接口对象 virtual void Release() = 0; ///初始化 ///@remark 初始化运行环境,只有调用后,接口才开始工作 virtual void Init() = 0; ///等待接口线程结束运行 ///@return 线程退出代码 virtual int Join() = 0; ///获取当前交易日 ///@retrun 获取到的交易日 ///@remark 只有登录成功后,才能得到正确的交易日 virtual const char *GetTradingDay() = 0; ///注册前置机网络地址 ///@param pszFrontAddress:前置机网络地址。 ///@remark 网络地址的格式为:“protocol://ipaddress:port”,如:”tcp://127.0.0.1:17001”。 ///@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”17001”代表服务器端口号。 virtual void RegisterFront(char *pszFrontAddress) = 0; ///注册名字服务器网络地址 ///@param pszNsAddress:名字服务器网络地址。 ///@remark 网络地址的格式为:“protocol://ipaddress:port”,如:”tcp://127.0.0.1:12001”。 ///@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”12001”代表服务器端口号。 ///@remark RegisterFront优先于RegisterNameServer virtual void RegisterNameServer(char *pszNsAddress) = 0; ///注册回调接口 ///@param pSpi 派生自回调接口类的实例 virtual void RegisterSpi(CUstpFtdcMduserSpi *pSpi) = 0; ///加载证书 ///@param pszCertFileName 用户证书文件名 ///@param pszKeyFileName 用户私钥文件名 ///@param pszCaFileName 可信任CA证书文件名 ///@param pszKeyFilePassword 用户私钥文件密码 ///@return 0 操作成功 ///@return -1 可信任CA证书载入失败 ///@return -2 用户证书载入失败 ///@return -3 用户私钥载入失败 ///@return -4 用户证书校验失败 virtual int RegisterCertificateFile(const char *pszCertFileName, const char *pszKeyFileName, const char *pszCaFileName, const char *pszKeyFilePassword) = 0; ///订阅市场行情。 ///@param nTopicID 市场行情主题 ///@param nResumeType 市场行情重传方式 /// USTP_TERT_RESTART:从本交易日开始重传 /// USTP_TERT_RESUME:从上次收到的续传(非订阅全部合约时,不支持续传模式) /// USTP_TERT_QUICK:先传送当前行情快照,再传送登录后市场行情的内容 ///@remark 该方法要在Init方法前调用。若不调用则不会收到私有流的数据。 virtual void SubscribeMarketDataTopic(int nTopicID, USTP_TE_RESUME_TYPE nResumeType) = 0; ///订阅合约行情。 ///@param ppInstrumentID 合约ID ///@param nCount 要订阅/退订行情的合约个数 ///@remark virtual int SubMarketData(char *ppInstrumentID[], int nCount)=0; ///退订合约行情。 ///@param ppInstrumentID 合约ID ///@param nCount 要订阅/退订行情的合约个数 ///@remark virtual int UnSubMarketData(char *ppInstrumentID[], int nCount)=0; ///设置心跳超时时间。 ///@param timeout 心跳超时时间(秒) virtual void SetHeartbeatTimeout(unsigned int timeout) = 0; ///风控前置系统用户登录请求 virtual int ReqUserLogin(CUstpFtdcReqUserLoginField *pReqUserLogin, int nRequestID) = 0; ///用户退出请求 virtual int ReqUserLogout(CUstpFtdcReqUserLogoutField *pReqUserLogout, int nRequestID) = 0; ///订阅主题请求 virtual int ReqSubscribeTopic(CUstpFtdcDisseminationField *pDissemination, int nRequestID) = 0; ///主题查询请求 virtual int ReqQryTopic(CUstpFtdcDisseminationField *pDissemination, int nRequestID) = 0; ///订阅合约的相关信息 virtual int ReqSubMarketData(CUstpFtdcSpecificInstrumentField *pSpecificInstrument, int nRequestID) = 0; ///退订合约的相关信息 virtual int ReqUnSubMarketData(CUstpFtdcSpecificInstrumentField *pSpecificInstrument, int nRequestID) = 0; protected: ~CUstpFtdcMduserApi(){}; }; #endif
[ "charmer01@sina.com" ]
charmer01@sina.com
4c032df9c5f81503760ae95bda4d60241eeff118
1064d896f7c1465a368db07ed4ce73f4172a6b2c
/C++/src/routine_superpixel_texture_and_color_majority.cpp
82bbf8f08e1b3fc5d29edb49148af4e757d8d5cd
[]
no_license
kyle5/apple_detection
264b73751f120ca0f8ecf970c7b844ecbe484a2e
875e178eda12a210afd36ccf9560d4e397cd1e50
refs/heads/master
2021-01-20T15:39:11.534313
2015-02-22T04:38:12
2015-02-22T04:38:12
31,152,198
0
0
null
null
null
null
UTF-8
C++
false
false
8,594
cpp
#include "utility.h" #include "include_in_all.h" #include "superpixel_computation.h" #include "visualization.h" #include "ml_helper_methods.h" #include "feature_computation.h" #include "setup_correct_apple_paths.h" #include "classify_images.h" #include "setup_feature_sets.h" #include "utility.h" #include <iomanip> #include <dirent.h> #include <cstdlib> #define PI 3.14159265 using namespace std; using namespace cv; string feature_type = "SURF"; string apple_type("green"); string root_data_directory = "/media/YIELDEST_KY/apple/"; string dataset_name = "2011_09_15_sunrise_9b/"; // TODO : ex: should mark the dark pixel values throughout the image as pixels that are "dark" // main function that calls everything else // first on one image then make a function to call everything else int main( int argc, char *argv[] ) { srand ( unsigned ( time(NULL) ) ); string dataset_path = root_data_directory + dataset_name; struct filepaths_apple_project fpaths = setup_correct_apple_paths( dataset_path ); string mkdir_apple_type_cmd = string("mkdir ") + apple_type; system( mkdir_apple_type_cmd.c_str() ); float percent_apple, percent_non_apple; Mat temp_percents; // TODO: Need to find a way to only do apple parts classification over the apple segments // full image: labels, texture features, color features ... // aim : features_full_images.all_texture_features string path_features_full_images_mask_dir = "features_full_images_mask/"; string system_call_features_save = string( "mkdir " ) + path_features_full_images_mask_dir; system( system_call_features_save.c_str() ); struct features_full_images features_apple_images; float resize_factor = 1; int save_full_img_features = 0; if ( save_full_img_features ) { features_apple_images = setup_features_full_images( fpaths.raw_training_paths, resize_factor, feature_type, fpaths ); save_features_full_images( path_features_full_images_mask_dir, features_apple_images, fpaths ); } else { features_apple_images = load_features_full_images( path_features_full_images_mask_dir, fpaths ); } vector<Mat> classifications_apple_segmentation; string root_saving_string_mask( "mask_images_" ); struct supervised_feature_set features_mask = setup_supervised_feature_set( fpaths.raw_training_paths, fpaths.mask_paths, 1, fpaths, root_saving_string_mask, resize_factor ); string root_saving_string_mos( "mos_images_" ); struct supervised_feature_set features_mask_of_shape = setup_supervised_feature_set( fpaths.raw_training_paths, fpaths.mos_paths, 0, fpaths, root_saving_string_mos, resize_factor ); // TODO : ex: make a leave one out function for ( int i = 0; i < (int) fpaths.raw_training_paths.size(); i++ ) { if ( fpaths.mask_paths[i].length() == 0 ) continue; // struct classifier_features loo_cf = setup_classifier_features( features_mask, i ); // create_svm( loo_cf ); // create_random_forest( loo_cf ); string raw_image_path = fpaths.raw_training_paths[i]; vector<Mat> superpixels_to_check_vec_mask; struct classification_result cur_class_result = classify_image( loo_cf, raw_image_path, features_apple_images, feature_type, superpixels_to_check_vec_mask, i ); Mat percentages_by_type = calculate_percentage_by_type( cur_class_result.superpixel_image, cur_class_result.classifications ); float min_probability = 0.7; // ex TODO : loop over a number of probabilities : segment superpixels that have a certainty of being apple pixels Mat classifications = calculate_maximal_classifications( percentages_by_type, min_probability ); // vector<Mat> superpixel_indices = calculate_superpixel_indices( cur_class_result.superpixel_image ); // Mat classifications_drawn = draw_classifications( cur_class_result.superpixel_image, classifications ); Mat classifications_drawn = draw_apple_pixels( cur_class_result.superpixel_image, read_image_and_flip_90(raw_image_path, 1), classifications ); ostringstream stream; stream << apple_type << "/results_simple_loo_" << i << ".ppm"; string image_path_cur = stream.str(); imwrite( image_path_cur, classifications_drawn ); if ( fpaths.mos_paths[i].length() == 0 ) continue; // There is no corresponding apple parts image struct classifier_features loo_mos_cf = setup_classifier_features( features_mask_of_shape, i ); Mat superpixels_to_check( classifications.rows, 1, CV_8U, Scalar(0) ); for ( int j = 0; j < classifications.rows; j++ ) { if ( classifications.at<uchar>( j, 0 ) == 1 ) { superpixels_to_check.at<uchar>(j, 0) = 1; } } vector<Mat> superpixels_to_check_vec_mos; superpixels_to_check_vec_mos.push_back( superpixels_to_check ); struct classification_result cur_class_result_mos = classify_image(loo_mos_cf, raw_image_path, features_apple_images, feature_type, superpixels_to_check_vec_mos, i); Mat percentages_by_type_mos = calculate_percentage_by_type( cur_class_result_mos.superpixel_image, cur_class_result_mos.classifications ); float min_probability_mos = 0.25; Mat classifications_mos = calculate_maximal_classifications( percentages_by_type_mos, min_probability_mos ); Mat classifications_drawn_mos = draw_apple_pixels( cur_class_result.superpixel_image, read_image_and_flip_90(raw_image_path, 1), classifications_mos ); ostringstream stream_mos; stream_mos << apple_type << "/results_simple_loo_mos_" << i << ".ppm"; string image_path_cur_mos = stream_mos.str(); imwrite( image_path_cur_mos, classifications_drawn_mos ); } int classify_testing_images = 0; if ( classify_testing_images ) { // TODO : Setup classification over images from a testing set // for each of the testing images : segment apples : segment mos /// load image /// get apple segmentation /// save apple segmentation struct classifier_features full_cf = setup_classifier_features( features_mask ); struct features_full_images temp_input; for ( int i = 0; i < (int) fpaths.testing_image_paths.size(); i++ ) { string cur_testing_image_path = fpaths.testing_image_paths[i]; int cur_testing_image_number = fpaths.testing_image_numbers[i]; vector<Mat> superpixels_to_check_vec_mask; // note i = -1 struct classification_result cur_class_result = classify_image( full_cf, cur_testing_image_path, temp_input, feature_type, superpixels_to_check_vec_mask, -1 ); Mat percentages_by_type = calculate_percentage_by_type( cur_class_result.superpixel_image, cur_class_result.classifications ); float min_probability = 0.7; // ex TODO : loop over a number of probabilities : segment superpixels that have a certainty of being apple pixels Mat classifications = calculate_maximal_classifications( percentages_by_type, min_probability ); // vector<Mat> superpixel_indices = calculate_superpixel_indices( cur_class_result.superpixel_image ); // Mat classifications_drawn = draw_classifications( cur_class_result.superpixel_image, classifications ); Mat raw_img = read_image_and_flip_90(cur_testing_image_path, 1); Mat classifications_drawn = draw_apple_pixels( cur_class_result.superpixel_image, raw_img, classifications ); ostringstream stream; stream << apple_type << "/results_testing_classifications_" << cur_testing_image_number << ".ppm"; string image_path_cur = stream.str(); imwrite( image_path_cur, classifications_drawn ); ostringstream stream_superpixel_img; stream_superpixel_img << apple_type << "/superpixel_image_" << cur_testing_image_number << ".png"; imwrite( stream_superpixel_img.str(), cur_class_result.superpixel_image ); // save the probability of apple classification int idx_apple = 0; Mat apple_classifications_probability_8U = draw_classification_probability( cur_class_result.superpixel_image, percentages_by_type, idx_apple ); ostringstream ap_prob_stream; ap_prob_stream << apple_type << "/apple_probabilities_" << cur_testing_image_number << ".pgm"; imwrite( ap_prob_stream.str(), apple_classifications_probability_8U ); // save the actual classifications Mat apple_classifications_drawn_8U = draw_only_apple_classifications( cur_class_result.superpixel_image, classifications ); ostringstream ap_class_stream; ap_class_stream << apple_type << "/apple_classifications_" << cur_testing_image_number << ".pgm"; imwrite( ap_class_stream.str(), apple_classifications_drawn_8U ); } printf( "z\n" ); } return 0; }
[ "kyle@kyle-All-Series.(none)" ]
kyle@kyle-All-Series.(none)
e86216202f0dcf0b5150326077e1bc5a2ea3657c
3a1fa284cccc1ee84aea82d109362c7f749dcb0c
/engine/enginecode/include/independent/systems/systems/resourceManager.h
09f0feaf64b7ea706eaec892c15dda3472300c86
[]
no_license
DanBullin/Owl-Engine
8007ebccaf31f4af9e73c9015f25c3be1fcfad80
d67c2a0c76458c6566dfd69e9c8d81153a7ec12c
refs/heads/main
2023-04-24T19:24:47.367794
2021-05-17T07:18:57
2021-05-17T07:18:57
367,107,845
0
0
null
null
null
null
UTF-8
C++
false
false
5,060
h
/*! \file resourceManager.h * * \brief A resource manager containing all the resources that are currently loaded. All resources are stored in a single map containing a key which is a unique string. * * \author Daniel Bullin * */ #ifndef RESOURCEMANAGER_H #define RESOURCEMANAGER_H #include <json.hpp> #include "independent/systems/system.h" #include "independent/core/common.h" #include "independent/systems/components/resource.h" #include "independent/rendering/geometry/vertexBuffer.h" #include "independent/rendering/geometry/indexBuffer.h" #include "independent/rendering/geometry/vertexArray.h" #include "independent/rendering/geometry/indirectBuffer.h" #include "independent/rendering/uniformBuffer.h" #include "independent/rendering/frameBuffer.h" #include "independent/rendering/shaders/shaderProgram.h" #include "independent/rendering/textures/texture.h" #include "independent/rendering/textures/subTexture.h" #include "independent/rendering/geometry/model3D.h" #include "independent/rendering/materials/material.h" namespace OwlEngine { namespace Config { /*! \enum ConfigData * \brief The different types of configurable data */ enum ConfigData { MaxSubTexturesPerMaterial = 0, VertexCapacity3D = 1, IndexCapacity3D = 2, BatchCapacity3D = 3, BatchCapacity2D = 4, MaxLayersPerScene = 5, MaxRenderPassesPerScene = 6, MaxLightsPerDraw = 7, UseBloom = 8, BloomBlurFactor = 9, PrintResourcesInDestructor = 10, PrintOpenGLDebugMessages = 11, ShowColliders = 12, ApplyFog = 13 }; } /*! \class ResourceManager * \brief A resource manager managing resources */ class ResourceManager : public System { private: static bool s_enabled; //!< Is this system enabled static std::map<std::string, Resource*> s_loadedResources; //!< A list of loaded resources static std::vector<uint32_t> s_configValues; //!< The config values static std::string s_resBeingLoaded; //!< The name of the resource being loaded public: ResourceManager(); //!< Constructor ~ResourceManager(); //!< Destructor void start() override; //!< Start the system void stop() override; //!< Stop the system static const bool resourceExists(const std::string& resourceName); //!< Check if the resource name exists static void registerResource(const std::string& resourceName, Resource* resource); //!< Register a resource static void destroyResource(const std::string& resourceName = ""); //!< Destroy a resource by name or all of them static void loadNTResources(); //!< Load non-threaded resources static void loadTResources(); //!< Load threaded resources template<typename T> static T* getResource(const std::string& resourceName); //!< Get a resource by name template<typename T> static std::vector<T*> getResourcesOfType(const ResourceType type); //!< Get all resources of a certain type static std::map<std::string, Resource*>& getResources(); //!< Get a list of all resources static std::string getCurrentDirectory(); //!< Returns the current directory static std::string getContents(const std::string& filePath); //!< Return the file contents static std::string getLineFromString(const std::string& stringContents, const uint32_t lineIndex); //!< Return the contents on line static nlohmann::json getJSON(const std::string& filePath); //!< Load the contents of a file into a JSON object and return the object static const uint32_t getConfigValue(const Config::ConfigData data); //!< Get a config value static void setConfigValue(const Config::ConfigData data, const uint32_t value); //!< Set a config value static FrameBuffer* getDefaultFrameBuffer(); //!< Get the default framebuffer static const std::string& getResBeingLoaded(); //!< Get the name of the resource being loaded static void setResBeingLoaded(const std::string& name); //!< Set the name of the resource being loaded static void printResourceManagerDetails(); //!< Print resource manager details static void printResourceDetails(const std::string& resourceName = ""); //!< Print resource details }; template<typename T> //! getResource() /*! \param resourceName a const std::string& - The name of the resource \return a T* - The resource in type T */ static T* ResourceManager::getResource(const std::string& resourceName) { // Check if resource exists by name // Cast and return it if it does, otherwise return nullptr // No type checking, quite frankly its your fault if you get it wrong if (resourceExists(resourceName)) return static_cast<T*>(s_loadedResources[resourceName]); else return nullptr; } template<typename T> //! getResourcesOfType() /*! \param type a const ResourceType - The resource type \return a std::vector<T*> - The list of resources of type T */ static std::vector<T*> ResourceManager::getResourcesOfType(const ResourceType type) { std::vector<T*> resources; for (auto& res : s_loadedResources) { if (res.second) { if (res.second->getType() == type) resources.emplace_back(static_cast<T*>(res.second)); } } return resources; } } #endif
[ "danbullin@gmail.com" ]
danbullin@gmail.com
e3d9c3f1e076ae554af9d032aa9628c1aa5df376
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/vis/writer/vis_writer_factory.cpp
f17a2d9662492c70428061ca51440dccfd7d2525
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,323
cpp
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #include "../buildfiles/_apps_enable_cmake.h" #ifdef ENABLE_VIS #include "apps/vis/writer/vis_writer_factory.h" #include "apps/vis/writer/vis_writer_keeper.h" #include "apps/vis/writer/vis_png_writer.h" #include "apps/vis/writer/vis_pdf_writer.h" namespace vis { WriterFactory:: WriterFactory( void ) {} WriterFactory::~WriterFactory() {} // ---------------------------------------------------------------------- std::string WriterFactory:: name( void ) const throw() { return "vis_writer"; } // ---------------------------------------------------------------------- std::string WriterFactory:: description( void ) const throw() { return "Vis filewriter objects"; } } #endif
[ "csinger08@users.sourceforge.net" ]
csinger08@users.sourceforge.net
b85c598b93e86eab1aed35bfbcad0e64e41fc4fd
1e58f86db88d590ce63110c885c52305d67f8136
/Common/application.h
135c6ff621210a865d79a44129e62e0f359c1abb
[]
no_license
urielyan/F270
32a9b87780b6b0bbbd8e072ca4305cd38dc975c1
c3d1eceead895ded12166eeb6748df111f46ef2d
refs/heads/master
2021-01-10T02:06:40.335370
2016-03-02T03:23:02
2016-03-02T03:23:02
52,927,128
1
1
null
null
null
null
UTF-8
C++
false
false
999
h
#ifndef APPLICATION_H #define APPLICATION_H #include <QApplication> #include <QTimer> #include "eventaction.h" class Application : public QApplication { Q_OBJECT public: explicit Application(int & argc, char ** argv); bool notify(QObject *receiver, QEvent *e); void actionEventNotify(EVENT_OBJECT *pEvent); //动作事件通知 void lcdSaverConfigChanged(); //TODO,启动时待调用 void autoGroupConfigChanged(); //TODO,启动时待调用 void homeWinConfigChanged(); //TODO,启动时待调用 private slots: void slotLcdSaverTimeOut(); void slotAutoGroupTimerOut(); void slotHomeWinTimeOut(); private: int m_actionEvent; //动作事件类型注册值 bool m_lcdSaved; //LCD屏幕保护模式 QTimer m_lcdSaver; //LCD屏幕保护定时器 QTimer m_autoGroup; //组自动切换定时器 QTimer m_homeWin; //默认窗体切换定时器 friend class EventAction; }; #endif // APPLICATION_H
[ "urielyan@sina.com" ]
urielyan@sina.com
9aac9a88600abc61c4bcceb500b8a798de196ad5
451915543cefc4c588192895204c728dab2278b7
/ProgrammingMethodsAndTechnics/container_Sort.cpp
858059ca3b1d4c47da35b3fe43c7fed7324bfa74
[]
no_license
Bumer19981/ProgrammingMethodsAndTechnics
a523d8838f36bcbf4269b09172219c44869cb073
85bf25e4399ecf06cd16d2c7f19beab4c9153c3f
refs/heads/master
2021-04-02T04:04:19.361030
2020-05-30T17:56:03
2020-05-30T17:56:03
248,238,844
0
0
null
null
null
null
UTF-8
C++
false
false
1,647
cpp
#include <fstream> #include "container_atd.h" using namespace std; namespace simple_langtypes { //bool Compare(langtype* first, langtype* second); void sort(Container& c) { if (c.list.head == NULL) { throw std::invalid_argument("Error: list is empty!"); } for (int i = 0; i < c.list.size - 1; i++) { for (int j = i + 1; j < c.list.size; j++) { Container::List::Node* ComparableItem1 = new Container::List::Node; Container::List::Node* ComparableItem2 = new Container::List::Node; for (int k = 0; k <= i; ++k) { if (k == 0) { ComparableItem1 = c.list.head; } else { ComparableItem1 = ComparableItem1->next; } } for (int k = 0; k <= j; ++k) { if (k == 0) { ComparableItem2 = c.list.head; } else { ComparableItem2 = ComparableItem2->next; } } if (compare(ComparableItem1->l, ComparableItem2->l)) { Container::List::Node* tmp; tmp = ComparableItem2->next; ComparableItem2->next = ComparableItem1->next; ComparableItem2->next->prev = ComparableItem2; ComparableItem1->next = tmp; ComparableItem1->next->prev = ComparableItem1; tmp = ComparableItem1->prev; ComparableItem1->prev = ComparableItem2->prev; ComparableItem1->prev->next = ComparableItem1; ComparableItem2->prev = tmp; ComparableItem2->prev->next = ComparableItem2; if (compare(c.list.head->l, ComparableItem2->l)) c.list.head = ComparableItem2; } } } for (int i = 0; i < c.list.size; ++i) { if (i == 0) { c.list.tail = c.list.head; } else { c.list.tail = c.list.tail->next; } } } }
[ "bumer19981@gmail.com" ]
bumer19981@gmail.com
d30eb7835336c078b994c6947861a94b3fa5c410
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/boost/interfaces/extract.hpp
4a3ce5ac936a78aa303d77001082113c7418afde
[]
no_license
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
1,765
hpp
// (C) Copyright Jonathan Turkanis 2004. // 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.) // Disclaimer: Not a Boost library. #ifndef BOOST_IDL_EXTRACT_HPP_INCLUDED #define BOOST_IDL_EXTRACT_HPP_INCLUDED #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <typeinfo> // bad_cast. #include <boost/interfaces/access.hpp> #include <boost/interfaces/detail/interface_table.hpp> #include <boost/interfaces/detail/constants.hpp> #include <boost/interfaces_fwd.hpp> //#include <boost/static_assert.hpp> //#include <boost/type_traits/is_const.hpp> #include <boost/type_traits/remove_const.hpp> namespace boost { namespace interfaces { class bad_extract : public std::bad_cast { public: const char* what() const throw() { return "boost::interfaces::bad_extract: failed extraction"; } }; template<typename X, typename Interface> X& extract(const Interface& i) { typedef typename remove_const<X>::type base_type; // BOOST_STATIC_ASSERT( is_const<X>::value || // !(Interface::interface_flags & flags::is_const) ); try { if (!i) throw bad_extract(); detail::thrower throw_ = detail::get_thrower(i); throw_(access::get_interface_pointer(i)); throw 0; // Unreachable. } catch (base_type* x) { return *x; } catch (void*) { throw bad_extract(); } } template<typename Interface> const std::type_info& target_type(const Interface& i) { if (!i) throw bad_extract(); detail::typer typer = detail::get_typer(i); return typer(); } } } // End namespaces interfaces, boost. #endif // #ifndef BOOST_IDL_EXTRACT_HPP_INCLUDED
[ "j@coderage.com" ]
j@coderage.com
540e39b740d4d64be046bee523848379304e7ff7
9eb2eb4de471b6c522ecb6e11bd1d10ee3bf1c29
/src/gigablast/Spider.h
3459c12c54bea3b550d1c481f5ac80ae2ab15245
[ "Apache-2.0" ]
permissive
fossabot/kblast
6df5a5c6d4ae708a6813963f0dac990d94710a91
37b89fd6ba5ce429be5a69e2c6160da8a6aa21e6
refs/heads/main
2023-07-25T04:06:20.527449
2021-09-08T04:15:07
2021-09-08T04:15:07
404,208,031
1
0
Apache-2.0
2021-09-08T04:15:02
2021-09-08T04:15:01
null
UTF-8
C++
false
false
52,973
h
// SPDX-License-Identifier: Apache-2.0 // // Copyright 2000-2014 Matt Wells // Copyright 2004-2013 Gigablast, Inc. // Copyright 2013 Web Research Properties, LLC // // 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 _SPIDER_H_ #define _SPIDER_H_ #define MAX_SPIDER_PRIORITIES 128 #define MAX_DAYS 365 #include "Rdb.h" #include "Conf.h" #include "Titledb.h" #include "Hostdb.h" #include "RdbList.h" #include "RdbTree.h" #include "HashTableX.h" #include <time.h> #include "Msg5.h" // local getList() #include "Msg4.h" #include "Msg1.h" #include "hash.h" #include "RdbCache.h" // for diffbot, this is for xmldoc.cpp to update CollectionRec::m_crawlInfo // which has m_pagesCrawled and m_pagesProcessed. //bool updateCrawlInfo ( CollectionRec *cr , // void *state , // void (* callback)(void *state) , // bool useCache = true ) ; // . values for CollectionRec::m_spiderStatus // . reasons why crawl is not happening #define SP_INITIALIZING 0 #define SP_MAXROUNDS 1 // hit max rounds limit #define SP_MAXTOCRAWL 2 // hit max to crawl limit #define SP_MAXTOPROCESS 3 // hit max to process limit #define SP_ROUNDDONE 4 // spider round is done #define SP_NOURLS 5 // initializing #define SP_PAUSED 6 // user paused spider #define SP_INPROGRESS 7 // it is going on! #define SP_ADMIN_PAUSED 8 // g_conf.m_spideringEnabled = false #define SP_COMPLETED 9 // crawl is done, and no repeatCrawl is scheduled bool tryToDeleteSpiderColl ( SpiderColl *sc ) ; void spiderRoundIncremented ( class CollectionRec *cr ) ; bool testPatterns ( ) ; bool doesStringContainPattern ( char *content , char *pattern ) ; bool getSpiderStatusMsg ( class CollectionRec *cx , class SafeBuf *msg , long *status ) ; long getFakeIpForUrl1 ( char *url1 ) ; long getFakeIpForUrl2 ( Url *url2 ) ; // Overview of Spider // // this new spider algorithm ensures that urls get spidered even if a host // is dead. and even if the url was being spidered by a host that suddenly went // dead. // // . Spider.h/.cpp contains all the code related to spider scheduling // . Spiderdb holds the SpiderRecs which indicate the time to spider a url // . there are 2 types of SpiderRecs: SpiderRequest and SpiderReply recs // // // There are 3 main components to the spidering process: // 1) spiderdb // 2) the "waiting tree" // 3) doledb // // spiderdb holds all the spiderrequests/spiderreplies sorted by // their IP // // the waiting tree holds at most one entry for an IP indicating that // we should scan all the spiderrequests/spiderreplies for that IP in // spiderdb, find the "best" one(s) and add it (them) to doledb. // // doledb holds the best spiderrequests from spiderdb sorted by // "priority". priorities range from 0 to 127, the highest priority. // basically doledb holds the urls that are ready for spidering now. // Spiderdb // // the spiderdb holds all the SpiderRequests and SpiderReplies, each of which // are sorted by their "firstIP" and then by their 48-bit url hash, // "uh48". the parentDocId is also kept in the key to prevent collisions. // Each group (shard) of hosts is responsible for spidering a fixed set of // IPs. // Dividing Workload by IP Address // // Each host is responsible for its own set of IP addresses. Each SpiderRequest // contains an IP address called m_firstIP. It alone is responsible for adding // SpiderRequests from this set of IPs to doledb. // the doled out // SpiderRequests are added to doledb using Msg4. Once in doledb, a // SpiderRequest is ready to be spidered by any host in the group (shard), // provided that that host gets all the locks. // "firstIP" // // when we lookup the ip address of the subdomain of an outlink for the first // time we store that ip address into tagdb using the tag named "firstip". // that way anytime we add outlinks from the same subdomain in the future they // are guaranteed to get the same "firstip" even if the actual ip changed. this // allows us to consistently throttle urls from the same subdomain, even if // the subdomain gets a new ip. this also increaseses performance when looking // up the "ips" of every outlink on a page because we are often just hitting // tagdb, which is much faster than doing dns lookups, that might miss the // dns cache! // Adding a SpiderRequest // // When a SpiderRequest is added to spiderdb in Rdb.cpp it calls // SpiderColl::addSpiderRequest(). If our host is responsible for doling // that firstIP, we check m_doleIPTable to see if that IP address is // already in doledb. if it is then we bail. Next we compute the url filter // number of the url in order to compute its spider time, then we add // it to the waiting tree. It will not get added to the waiting tree if // the current entry in the waiting tree has an earlier spider time. // then when the waiting tree is scanned it will read SpiderRequests from // spiderdb for just that firstIP and add the best one to doledb when it is // due to be spidered. // Waiting Tree // // The waiting tree is a b-tree where the keys are a spiderTime/IPaddress tuple // of the corresponding SpiderRequest. Think of its keys as requests to // spider something from that IP address at the given time, spiderTime. // The entries are sorted by spiderTime first then IP address. // It let's us know the earliest time we can spider a SpiderRequest // from an IP address. We have exactly one entry in the waiting tree from // every IP address that is in Spiderdb. "m_waitingTable" maps an IP // address to its entry in the waiting tree. If an IP should not be spidered // until the future then its spiderTime in the waiting tree will be in the // future. // Adding a SpiderReply // // We intercept SpiderReplies being added to Spiderdb in Rdb.cpp as well by // calling SpiderColl::addSpiderReply(). Then we get the firstIP // from that and we look in spiderdb to find a replacement SpiderRequest // to add to doledb. To make this part easy we just add the firstIP to the // waiting tree with a spiderTime of 0. so when the waiting tree scan happens // it will pick that up and look in spiderdb for the best SpiderRequest with // that same firstIP that can be spidered now, and then it adds that to // doledb. (To prevent from having to scan long spiderdb lists and speed // things up we might want to keep a little cache that maps a firstIP to // a few SpiderRequests ready to be spidered). // Deleting Dups // // we now remove spiderdb rec duplicates in the spiderdb merge. we also call // getUrlFilterNum() on each spiderdb rec during the merge to see if it is // filtered and not indexed, and if so, we delete it. we also delete all but // the latest SpiderReply for a given uh48/url. And we remove redundant // SpiderRequests like we used to do in addSpiderRequest(), which means that // the merge op needs to keep a small little table to scan in order to // compare all the SpiderRequests in the list for the same uh48. all of this // deduping takes place on the final merged list which is then further // filtered by this by calling Spiderdb.cpp::filterSpiderdbRecs(RdbList *list). // because the list is just a random piece of spiderdb, boundary issues will // cause some records to leak through, but with enough file merge operations // they should eventually be zapped. // DoleDB // // This holds SpiderRequests that are ready to be spidered right now. A host // in our group (shard) will call getLocks() to get the locks for a // SpiderRequest in doledb that it wants to spider. it must receive grants // from every alive machine in the group in order to properly get the lock. // If it receives a rejection from one host it release the lock on all the // other hosts. It is kind of random to get a lock, similar to ethernet // collision detection. // Dole IP Table // // m_doleIpTable (HashTableX, 96 bit keys, no data) // Purpose: let's us know how many SpiderRequests have been doled out for // a given firstIP // Key is simply a 4-byte IP. // Data is the number of doled out SpiderRequests from that IP. // we use m_doleIpTable for keeping counts based on ip of what is doled out. // // g_doledb // // Purpose: holds the spider request your group (shard) is supposed to spider // according to getGroupIdToSpider(). 96-bit keys, data is the spider rec with // key. ranked according to when things should be spidered. // <~priority> 8bits // <spiderTime> 32bits // <urlHash48> 48bits (to avoid collisions) // <reserved> 7bits (used 7 bits from urlhash48 to avoid collisio) // <delBit> 1bit // DATA: // <spiderRec> Xbits (spiderdb record to spider, includes key) // everyone in group (shard) tries to spider this shit in order. // you call SpiderLoop::getLocks(sr,hostId) to get the lock for it before // you can spider it. everyone in the group (shard) gets the lock request. // if you do not get granted lock by all alive hosts in the group (shard) then // you call Msg12::removeAllLocks(sr,hostId). nobody tries to spider // a doledb spider rec if the lock is granted to someone else, just skip it. // if a doling host goes dead, then its twins will dole for it after their // SpiderColl::m_nextReloadTime is reached and they reset their cache and // re-scan spiderdb. XmlDoc adds the negative key to RDB_DOLEDB so that // should remove it from doledb when the spidering is complete, and when // Rdb.cpp receives a "fake" negative TITLEDB key it removes the doledbKey lock // from m_lockTable. See XmlDoc.cpp "fake titledb key". // Furthermore, if Rdb.cpp receives a positive doledbKey // it might update SpiderColl::m_nextKeys[priority] so that the next read of // doledb starts there when SpiderLoop::spiderDoledUrls() calls // msg5 to read doledb records from disk. // TODO: when a host dies, consider speeding up the reload. might be 3 hrs! // PROBLEM: what if a host dies with outstanding locks??? // SpiderLoop::m_lockTable (HashTableX(6,8)) // Purpose: allows a host to lock a doledb key for spidering. used by Msg12 // and SpiderLoop. a host must get the lock for all its alive twins in its // group (shard) before it can spider the SpiderRequest, otherwise, it will // removeall the locks from the hosts that did grant it by calling // Msg12::removeAllLocks(sr,hostId). // GETTING A URL TO SPIDER // // To actually spider something, we do a read of doledb to get the next // SpiderRequest. Because there are so many negative/positive key annihilations // in doledb, we keep a "cursor key" for each spider priority in doledb. // We get a "lock" on the url so no other hosts in our group (shard) can // spider it from doledb. We get the lock if all hosts in the shard // successfully grant it to us, otherwise, we inform all the hosts that // we were unable to get the lock, so they can unlock it. // // SpiderLoop::spiderDoledUrls() will scan doledb for each collection that // has spidering enabled, and get the SpiderRequests in doledb that are // in need of spidering. The keys in doledb are sorted by highest spider // priority first and then by the "spider time". If one spider priority is // empty or only has spiderRequests in it that can be spidered in the future, // then the next priority is read. // // any host in our group (shard) can spider a request in doledb, but they must // lock it by calling getLocks() first and all hosts in the group (shard) must // grant them the lock for that url otherwise they remove all the locks and // try again on another spiderRequest in doledb. // // Each group (shard) is responsible for spidering a set of IPs in spiderdb. // and each host in the group (shard) has its own subset of those IPs for which // it is responsible for adding to doledb. but any host in the group (shard) // can spider any request/url in doledb provided they get the lock. // evalIpLoop() // // The waiting tree is populated at startup by scanning spiderdb (see // SpiderColl::evalIpLoop()), which might take a while to complete, // so it is running in the background while the gb server is up. it will // log "10836674298 spiderdb bytes scanned for waiting tree re-population" // periodically in the log as it tries to do a complete spiderdb scan // every 24 hours. It should not be necessary to scan spiderdb more than // once, but it seems we are leaking ips somehow so we do the follow-up // scans for now. (see populateWaitingTreeFromSpiderdb() in Spider.cpp) // It will also perform a background scan if the admin changes the url // filters table, which dictates that we recompute everything. // // evalIpLoop() will recompute the "url filter number" (matching row) // in the url filters table for each url in each SpiderRequest it reads. // it will ignore spider requests whose urls // are "filtered" or "banned". otherwise they will have a spider priority >= 0. // So it calls ::getUrlFilterNum() for each url it scans which is where // most of the cpu it uses will probably be spent. It picks the best // url to spider for each IP address. It only picks one per IP right now. // If the best url has a scheduled spider time in the future, it will add it // to the waiting tree with that future timestamp. The waiting tree only // stores one entry for each unique IP, so it tries to store // the entry with the earliest computed scheduled spider time, but if // some times are all BEFORE the current time, it will resolve conflicts // by preferring those with the highest priority. Tied spider priorities // should be resolved by minimum hopCount probably. // // If the spidertime of the URL is overdue then evalIpLoop() will NOT add // it to waiting tree, but will add it to doledb directly to make it available // for spidering immediately. It calls m_msg4.addMetaList() to add it to // doledb on all hosts in its group (shard). It uses s_ufnTree for keeping // track of the best urls to spider for a given IP/spiderPriority. // // evalIpLoop() can also be called with its m_nextKey/m_endKey limited // to just scan the SpiderRequests for a specific IP address. It does // this after adding a SpiderReply. addSpiderReply() calls addToWaitingTree() // with the "0" time entry, and addToWaitingTree() calls // populateDoledbFromWaitingTree() which will see that "0" entry and call // evalIpLoop(true) after setting m_nextKey/m_endKey for that IP. // POPULATING DOLEB // // SpiderColl::populateDoledbFromWaitingTree() scans the waiting tree for // entries whose spider time is due. so it gets the IP address and spider // priority from the waiting tree. but then it calls evalIpLoop() // restricted to that IP (using m_nextKey,m_endKey) to get the best // SpiderRequest from spiderdb for that IP to add to doledb for immediate // spidering. populateDoledbFromWaitingTree() is called a lot to try to // keep doledb in sync with waiting tree. any time an entry in the waiting // tree becomes available for spidering it should be called right away so // as not to hold back the spiders. in general it should exit quickly because // it calls getNextIpFromWaitingTree() which most of the time will return 0 // indicating there are no IPs in the waiting tree ready to be spidered. // Which is why as we add SpiderRequests to doledb for an IP we also // remove that IP from the waiting tree. This keeps this check fast. // SUPPORTING MULTIPLE SPIDERS PER IP // // In order to allow multiple outstanding spiders per IP address, if, say, // maxSpidersPerIp is > 1, we now promptly add the negative doledb key // as soon as a lock is granted and we also add an entry to the waiting tree // which will result in an addition to doledb of the next unlocked // SpiderRequest. This logic is mostly in Spider.cpp's Msg12::gotLockReply(). // // Rdb.cpp will see that we added a "fakedb" record // A record is only removed from Doledb after the spider adds the negative // doledb record in XmlDoc.cpp when it is done. XmlDoc.cpp also adds a // "fake" negative titledb record to remove the lock on that url at the // same time. // // So, 1) we can allow for multiple doledb entries per IP and the assigned // host can reply with "wait X ms" to honor the spiderIpWait constraint, // or 2) we can delete the doledb entry after the lock is granted, and then // we can immediately add a "currentTime + X ms" entry to the waiting tree to // add the next doledb record for this IP X ms from now. // // I kind of like the 2nd approach because then there is only one entry // per IP in doledb. that is kind of nice. So maybe using the same // logic that is used by Spider.cpp to release a lock, we can say, // "hey, i got the lock, delete it from doledb"... // . what groupId (shardId) should spider/index this spider request? // . CAUTION: NOT the same group (shard) that stores it in spiderdb!!! // . CAUTION: NOT the same group (shard) that doles it out to spider!!! //unsigned long getGroupIdToSpider ( char *spiderRec ); // now used by xmldoc.cpp bool isAggregator ( long siteHash32 , long domHash32 , char *url , long urlLen ) ; // The 128-bit Spiderdb record key128_t for a rec in Spiderdb is as follows: // // <32 bit firstIp> (firstIp of the url to spider) // <48 bit normalized url hash> (of the url to spider) // <1 bit isRequest> (a SpiderRequest or SpiderReply record?) // <38 bit docid of parent> (to avoid collisions!) // <8 bit reserved> (was "spiderLinks"/"forced"/"retryNum") // <1 bit delbit> (0 means this is a *negative* key) // there are two types of SpiderRecs really, a "request" to spider a url // and a "reply" or report on the attempted spidering of a url. in this way // Spiderdb is a perfect log of desired and actual spider activity. // . Spiderdb contains an m_rdb which has SpiderRecs/urls to be spidered // . we split the SpiderRecs up w/ the hosts in our group (shard) by IP of the // url. // . once we've spidered a url it gets added with a negative spiderdb key // in XmlDoc.cpp class Spiderdb { public: // reset rdb void reset(); // set up our private rdb for holding SpiderRecs bool init ( ); // init the rebuild/secondary rdb, used by PageRepair.cpp bool init2 ( long treeMem ); bool verify ( char *coll ); bool addColl ( char *coll, bool doVerify = true ); Rdb *getRdb ( ) { return &m_rdb; }; DiskPageCache *getDiskPageCache() { return &m_pc; }; // this rdb holds urls waiting to be spidered or being spidered Rdb m_rdb; long long getUrlHash48 ( key128_t *k ) { return (((k->n1)<<16) | k->n0>>(64-16)) & 0xffffffffffffLL; }; bool isSpiderRequest ( key128_t *k ) { return (k->n0>>(64-17))&0x01; }; bool isSpiderReply ( key128_t *k ) { return ((k->n0>>(64-17))&0x01)==0x00; }; long long getParentDocId ( key128_t *k ) {return (k->n0>>9)&DOCID_MASK;}; // same as above long long getDocId ( key128_t *k ) {return (k->n0>>9)&DOCID_MASK;}; long getFirstIp ( key128_t *k ) { return (k->n1>>32); } key128_t makeKey ( long firstIp , long long urlHash48 , bool isRequest , long long parentDocId , bool isDel ) ; key128_t makeFirstKey ( long firstIp ) { return makeKey ( firstIp,0LL,false,0LL,true); }; key128_t makeLastKey ( long firstIp ) { return makeKey ( firstIp,0xffffffffffffLL,true, MAX_DOCID,false); }; key128_t makeFirstKey2 ( long firstIp , long long uh48 ) { return makeKey ( firstIp,uh48,false,0LL,true); }; key128_t makeLastKey2 ( long firstIp , long long uh48 ) { return makeKey ( firstIp,uh48,true,MAX_DOCID,false); }; // what groupId (shardid) spiders this url? /* inline unsigned long getShardNum ( long firstIp ) { // must be valid if ( firstIp == 0 || firstIp == -1 ) {char *xx=NULL;*xx=0; } // mix it up unsigned long h = (unsigned long)hash32h ( firstIp, 0x123456 ); // get it return h % g_hostdb.m_numShards; }; */ // print the spider rec long print( char *srec ); private: DiskPageCache m_pc; }; void dedupSpiderdbList ( RdbList *list , long niceness , bool removeNegRecs ); extern class Spiderdb g_spiderdb; extern class Spiderdb g_spiderdb2; class SpiderRequest { public: // we now define the data so we can use this class to cast // a SpiderRec outright key128_t m_key; long m_dataSize; // this ip is taken from the TagRec for the domain of the m_url, // but we do a dns lookup initially if not in tagdb and we put it in // tagdb then. that way, even if the domain gets a new ip, we still // use the original ip for purposes of deciding which groupId (shardId) // is responsible for storing, doling/throttling this domain. if the // ip lookup results in NXDOMAIN or another error then we generally // do not add it to tagdb in msge*.cpp. this ensures that any given // domain will always be spidered by the same group (shard) of hosts // even if the ip changes later on. this also increases performance // since we do a lot fewer dns lookups on the outlinks. long m_firstIp; //long getFirstIp ( ) { return g_spiderdb.getFirstIp(&m_key); }; long m_hostHash32; long m_domHash32; long m_siteHash32; // this is computed from every outlink's tagdb record but i guess // we can update it when adding a spider rec reply long m_siteNumInlinks; // . when this request was first was added to spiderdb // . Spider.cpp dedups the oldest SpiderRequests that have the // same bit flags as this one. that way, we get the most uptodate // date in the request... UNFORTUNATELY we lose m_addedTime then!!! time_t m_addedTime; // if m_isNewOutlink is true, then this SpiderRequest is being added // for a link that did not exist on this page the last time it was // spidered. XmlDoc.cpp needs to set XmlDoc::m_min/maxPubDate for // m_url. if m_url's content does not contain a pub date explicitly // then we can estimate it based on when m_url's parent was last // spidered (when m_url was not an outlink on its parent page) time_t m_parentPrevSpiderTime; // info on the page we were harvest from long m_parentFirstIp; long m_parentHostHash32; long m_parentDomHash32; long m_parentSiteHash32; // the PROBABLE DOCID. if there is a collision with another docid // then we increment the last 8 bits or so. see Msg22.cpp. long long m_probDocId; //long m_parentPubDate; // . pub date taken from url directly, not content // . ie. http://mysite.com/blog/nov-06-2009/food.html // . ie. http://mysite.com/blog/11062009/food.html //long m_urlPubDate; // . replace this with something we need for smart compression // . this is zero if none or invalid long m_contentHash32; // . each request can have a different hop count // . this is only valid if m_hopCountValid is true! // . i made this a short from long to support m_parentLangId etc above short m_hopCount; // when creating a chinese search engine for instance it is nice // to know the language of the page we are spidering's parent. // typically a chinese page will link to another chinese page, // though not always of course. this is the primary language of // the parent. uint8_t m_parentLangId;//reserved1; // the new add url control will allow user to control link spidering // on each url they add. they can also specify file:// instead of // http:// to index local files. so we have to allow file:// /* char m_onlyAddSameDomainLinks :1; */ /* char m_onlyAddSameSubdomainLinks :1; */ /* char m_onlyDoNotAddLinksLinks :1; // max hopcount 1 */ /* char m_onlyDoNotAddLinksLinksLinks :1; // max hopcount 2 */ char m_ignoreDocUnchangedError:1;//reserved2a:1; char m_reserved2b:1; char m_reserved2c:1; char m_reserved2d:1; char m_reserved2e:1; char m_reserved2f:1; char m_reserved2g:1; char m_reserved2h:1; //long m_hopCount; // . this is now computed dynamically often based on the latest // m_addedTime and m_percentChanged of all the SpideRec *replies*. // we may decide to change some url filters // that affect this computation. so SpiderCache always changes // this value before adding any SpiderRec *request* to the // m_orderTree, etc. //time_t m_spiderTime; // // our bit flags // long m_hopCountValid:1; // are we a request/reply from the add url page? long m_isAddUrl:1; // are we a request/reply from PageReindex.cpp long m_isPageReindex:1; // are we a request/reply from PageInject.cpp long m_isPageInject:1; // or from PageParser.cpp directly long m_isPageParser:1; // should we use the test-spider-dir for caching test coll requests? long m_useTestSpiderDir:1; // . is the url a docid (not an actual url) // . could be a "query reindex" long m_urlIsDocId:1; // does m_url end in .rss? or a related rss file extension? long m_isRSSExt:1; // is url in a format known to be a permalink format? long m_isUrlPermalinkFormat:1; // is url "rpc.weblogs.com/shortChanges.xml"? long m_isPingServer:1; // . are we a delete instruction? (from Msg7.cpp as well) // . if you want it to be permanently banned you should ban or filter // it in the urlfilters/tagdb. so this is kinda useless... long m_forceDelete:1; // are we a fake spider rec? called from Test.cpp now! long m_isInjecting:1; // are we a respider request from Sections.cpp //long m_fromSections:1; // a new flag. replaced above. did we have a corresponding SpiderReply? long m_hadReply:1; // are we scraping from google, etc.? long m_isScraping:1; // page add url can be updated to store content for the web page // into titledb or something to simulate injections of yore. we can // use that content as the content of the web page. the add url can // accept it from a form and we store it right away into titledb i // guess using msg4, then we look it up when we spider the url. long m_hasContent:1; // is first ip a hash of url or docid or whatever? long m_fakeFirstIp:1; // www.xxx.com/*? or xxx.com/*? long m_isWWWSubdomain:1; // // these "parent" bits are invalid if m_parentHostHash32 is 0! // that includes m_isMenuOutlink // // if the parent was respidered and the outlink was there last time // and is there now, then this is "0", otherwise, this is "1" long m_isNewOutlink :1; long m_sameDom :1; long m_sameHost :1; long m_sameSite :1; long m_wasParentIndexed :1; long m_parentIsRSS :1; long m_parentIsPermalink :1; long m_parentIsPingServer:1; long m_parentHasAddress :1; // is this outlink from content or menu? long m_isMenuOutlink :1; // // these bits also in SpiderReply // // was it in google's index? long m_inGoogle:1; // expires after a certain time or if ownership changed // did it have an inlink from a really nice site? long m_hasAuthorityInlink :1; long m_hasContactInfo :1; long m_isContacty :1; long m_hasSiteVenue :1; // are the 3 bits above valid? // if site ownership changes might be invalidated. // "inGoogle" also may expire after so long too long m_inGoogleValid :1; long m_hasAuthorityInlinkValid :1; long m_hasContactInfoValid :1; long m_isContactyValid :1; long m_hasAddressValid :1; //long m_matchesUrlCrawlPattern :1; //long m_matchesUrlProcessPattern:1; long m_hasTODValid :1; long m_hasSiteVenueValid :1; long m_siteNumInlinksValid :1; // . only support certain tags in url filters now i guess // . use the tag value from most recent SpiderRequest only // . the "deep" tag is popular for hitting certain sites hard //long m_tagDeep:1; // we set this to one from Diffbot.cpp when urldata does not // want the url's to have their links spidered. default is to make // this 0 and to not avoid spidering the links. long m_avoidSpiderLinks:1; // for identifying address heavy sites... //long m_tagYellowPages:1; // when indexing urls for dmoz, i.e. the urls outputted from // 'dmozparse urldump -s' we need to index them even if there // was a ETCPTIMEDOUT because we have to have indexed the same // urls that dmoz has in it in order to be identical to dmoz. long m_ignoreExternalErrors:1; // called XmlDoc::set4() from PageSubmit.cpp? //long m_isPageSubmit:1; // // INTERNAL USE ONLY // // are we in the m_orderTree/m_doleTables/m_ipTree //long m_inOrderTree:1; // are we doled out? //long m_doled:1; // are we a re-add of a spiderrequest already in spiderdb added // from xmldoc.cpp when done spidering so that the spider request // gets back in the cache quickly? //long m_readd:1; // . what url filter num do we match in the url filters table? // . determines our spider priority and wait time short m_ufn; // . m_priority is dynamically computed like m_spiderTime // . can be negative to indicate filtered, banned, skipped, etc. // . for the spiderrec request, this is invalid until it is set // by the SpiderCache logic, but for the spiderrec reply this is // the priority we used! char m_priority; // . this is copied from the most recent SpiderReply into here // . its so XMlDoc.cpp can increment it and add it to the new // SpiderReply it adds in case there is another download error , // like ETCPTIMEDOUT or EDNSTIMEDOUT char m_errCount; // we really only need store the url for *requests* and not replies char m_url[MAX_URL_LEN+1]; // . basic functions // . clear all void reset() { memset ( this , 0 , (long)m_url - (long)&m_key ); // -1 means uninitialized, this is required now m_ufn = -1; // this too m_priority = -1; // this happens to be zero already, but just in case it changes m_parentLangId = langUnknown; }; static long getNeededSize ( long urlLen ) { return sizeof(SpiderRequest) - (long)MAX_URL_LEN + urlLen; }; long getRecSize () { return m_dataSize + 4 + sizeof(key128_t); } // how much buf will we need to serialize ourselves? //long getRecSize () { // //return m_dataSize + 4 + sizeof(key128_t); } // return (m_url - (char *)this) + gbstrlen(m_url) + 1 // // subtract m_key and m_dataSize // - sizeof(key_t) - 4 ; //}; long getUrlLen() { return m_dataSize - // subtract the \0 ((char *)m_url-(char *)&m_firstIp) - 1;}; char *getUrlPath() { char *p = m_url; for ( ; *p ; p++ ) { if ( *p != ':' ) continue; p++; if ( *p != '/' ) continue; p++; if ( *p != '/' ) continue; p++; break; } if ( ! *p ) return NULL; // skip until / then for ( ; *p && *p !='/' ; p++ ) ; if ( *p != '/' ) return NULL; // return root path of / if there. return p; }; //long getUrlLen() { return gbstrlen(m_url); }; void setKey ( long firstIp , long long parentDocId , long long uh48 , bool isDel ) ; void setKey ( long firstIp, long long parentDocId , bool isDel ) { long long uh48 = hash64b ( m_url ); setKey ( firstIp , parentDocId, uh48, isDel ); } void setDataSize ( ); long long getUrlHash48 () {return g_spiderdb.getUrlHash48(&m_key); }; long long getParentDocId (){return g_spiderdb.getParentDocId(&m_key);}; long print( class SafeBuf *sb ); long printToTable ( SafeBuf *sb , char *status , class XmlDoc *xd , long row ) ; // for diffbot... long printToTableSimple ( SafeBuf *sb , char *status , class XmlDoc *xd , long row ) ; static long printTableHeader ( SafeBuf *sb , bool currentlSpidering ) ; static long printTableHeaderSimple ( SafeBuf *sb , bool currentlSpidering ) ; // returns false and sets g_errno on error bool setFromAddUrl ( char *url ) ; bool setFromInject ( char *url ) ; }; // . XmlDoc adds this record to spiderdb after attempting to spider a url // supplied to it by a SpiderRequest // . before adding a SpiderRequest to the spider cache, we scan through // all of its SpiderRecReply records and just grab the last one. then // we pass that to ::getUrlFilterNum() // . if it was not a successful reply, then we try to populate it with // the member variables from the last *successful* reply before passing // it to ::getUrlFilterNum() // . getUrlFilterNum() also takes the SpiderRequest record as well now // . we only keep the last X successful SpiderRecReply records, and the // last unsucessful Y records (only if more recent), and we nuke all the // other SpiderRecReply records class SpiderReply { public: // we now define the data so we can use this class to cast // a SpiderRec outright key128_t m_key; long m_dataSize; // for calling getHostIdToDole() long m_firstIp; //long getFirstIp ( ) { return g_spiderdb.getFirstIp(&m_key); }; // we need this too in case it changes! long m_siteHash32; // and this for updating crawl delay in m_cdTable long m_domHash32; // since the last successful SpiderRecReply float m_percentChangedPerDay; // when we attempted to spider it time_t m_spideredTime; // . value of g_errno/m_indexCode. 0 means successfully indexed. // . might be EDOCBANNED or EDOCFILTERED long m_errCode; // this is fresher usually so we can use it to override // SpiderRequest's m_siteNumLinks long m_siteNumInlinks; // how many inlinks does this particular page have? //long m_pageNumInlinks; // the actual pub date we extracted (0 means none, -1 unknown) long m_pubDate; // . SpiderRequests added to spiderdb since m_spideredTime // . XmlDoc.cpp's ::getUrlFilterNum() uses this as "newinlinks" arg //long m_newRequests; // . replaced m_newRequests // . this is zero if none or invalid long m_contentHash32; // in milliseconds, from robots.txt (-1 means none) // TODO: store in tagdb, lookup when we lookup tagdb recs for all // out outlinks long m_crawlDelayMS; // . when we basically finished DOWNLOADING it // . use 0 if we did not download at all // . used by Spider.cpp to space out urls using sameIpWait long long m_downloadEndTime; // how many errors have we had in a row? //long m_retryNum; // . like "404" etc. "200" means successfully downloaded // . we can still successfully index pages that are 404 or permission // denied, because we might have link text for them. short m_httpStatus; // . only non-zero if errCode is set! // . 1 means it is the first time we tried to download and got an error // . 2 means second, etc. char m_errCount; // what language was the page in? char m_langId; // // our bit flags // // XmlDoc::isSpam() returned true for it! //char m_isSpam:1; // was the page in rss format? long m_isRSS:1; // was the page a permalink? long m_isPermalink:1; // are we a pingserver page? long m_isPingServer:1; // did we delete the doc from the index? //long m_deleted:1; // was it in the index when we were done? long m_isIndexed:1; // // these bits also in SpiderRequest // // was it in google's index? long m_inGoogle:1; // did it have an inlink from a really nice site? long m_hasAuthorityInlink:1; // does it have contact info long m_hasContactInfo:1; long m_isContacty :1; long m_hasAddress :1; long m_hasTOD :1; // make this "INvalid" not valid since it was set to 0 before // and we want to be backwards compatible long m_isIndexedINValid :1; //long m_hasSiteVenue :1; // expires after a certain time or if ownership changed long m_inGoogleValid :1; long m_hasContactInfoValid :1; long m_hasAuthorityInlinkValid :1; long m_isContactyValid :1; long m_hasAddressValid :1; long m_hasTODValid :1; //long m_hasSiteVenueValid :1; long m_reserved2 :1; long m_siteNumInlinksValid :1; // was the request an injection request long m_fromInjectionRequest :1; // did we TRY to send it to the diffbot backend filter? might be err? long m_sentToDiffbot :1; long m_hadDiffbotError :1; // . was it in the index when we started? // . we use this with m_isIndexed above to adjust quota counts for // this m_siteHash32 which is basically just the subdomain/host // for SpiderColl::m_quotaTable long m_wasIndexed :1; // this also pertains to m_isIndexed as well: long m_wasIndexedValid :1; // how much buf will we need to serialize ourselves? long getRecSize () { return m_dataSize + 4 + sizeof(key128_t); } // clear all void reset() { memset ( this , 0 , sizeof(SpiderReply) ); }; void setKey ( long firstIp, long long parentDocId , long long uh48 , bool isDel ) ; long print ( class SafeBuf *sbarg ); long long getUrlHash48 () {return g_spiderdb.getUrlHash48(&m_key); }; long long getParentDocId (){return g_spiderdb.getParentDocId(&m_key);}; }; // are we responsible for this ip? bool isAssignedToUs ( long firstIp ) ; #define DOLEDBKEY key_t // . store urls that can be spidered right NOW in doledb // . SpiderLoop.cpp doles out urls from its local spiderdb into // the doledb rdb of remote hosts (and itself as well sometimes!) // . then each host calls SpiderLoop::spiderDoledUrls() to spider the // urls doled to their group (shard) in doledb class Doledb { public: void reset(); bool init ( ); bool addColl ( char *coll, bool doVerify = true ); DiskPageCache *getDiskPageCache() { return &m_pc; }; // . see "overview of spidercache" below for key definition // . these keys when hashed are clogging up the hash table // so i am making the 7 reserved bits part of the urlhash48... key_t makeKey ( long priority , time_t spiderTime , long long urlHash48 , bool isDelete ) { // sanity checks if ( priority & 0xffffff00 ) { char *xx=NULL;*xx=0;} if ( urlHash48 & 0xffff000000000000LL ) { char *xx=NULL;*xx=0;} key_t k; k.n1 = (255 - priority); k.n1 <<= 24; k.n1 |= (spiderTime >>8); k.n0 = spiderTime & 0xff; k.n0 <<= 48; k.n0 |= urlHash48; // 7 bits reserved k.n0 <<= 7; // still reserved but when adding to m_doleReqTable it needs // to be more random!! otherwise the hash table is way slow! k.n0 |= (urlHash48 & 0x7f); // 1 bit for negative bit k.n0 <<= 1; // we are positive or not? setting this means we are positive if ( ! isDelete ) k.n0 |= 0x01; return k; }; // . use this for a query reindex // . a docid-based spider request // . crap, might we have collisions between a uh48 and docid???? key_t makeReindexKey ( long priority , time_t spiderTime , long long docId , bool isDelete ) { return makeKey ( priority,spiderTime,docId,isDelete); }; key_t makeFirstKey2 ( long priority ) { key_t k; k.setMin(); // set priority k.n1 = (255 - priority); k.n1 <<= 24; return k; }; key_t makeLastKey2 ( long priority ) { key_t k; k.setMax(); // set priority k.n1 = (255 - priority); k.n1 <<= 24; k.n1 |= 0x00ffffff; return k; }; long getPriority ( key_t *k ) { return 255 - ((k->n1 >> 24) & 0xff); }; long getSpiderTime ( key_t *k ) { unsigned long spiderTime = (k->n1) & 0xffffff; spiderTime <<= 8; // upper 8 bits of k.n0 are lower 8 bits of spiderTime spiderTime |= (unsigned long)((k->n0) >> (64-8)); return (long)spiderTime; }; long getIsDel ( key_t *k ) { if ( (k->n0 & 0x01) ) return 0; return 1; }; long long getUrlHash48 ( key_t *k ) { return (k->n0>>8)&0x0000ffffffffffffLL; } key_t makeFirstKey ( ) { key_t k; k.setMin(); return k;}; key_t makeLastKey ( ) { key_t k; k.setMax(); return k;}; Rdb *getRdb() { return &m_rdb;}; Rdb m_rdb; DiskPageCache m_pc; }; extern class Doledb g_doledb; // was 1000 but breached, now equals SR_READ_SIZE/sizeof(SpiderReply) #define MAX_BEST_REQUEST_SIZE (MAX_URL_LEN+1+sizeof(SpiderRequest)) #define MAX_DOLEREC_SIZE (MAX_BEST_REQUEST_SIZE+sizeof(key_t)+4) #define MAX_SP_REPLY_SIZE (sizeof(SpiderReply)) // we have one SpiderColl for each collection record class SpiderColl { public: ~SpiderColl ( ); SpiderColl ( ) ; void clearLocks(); // called by main.cpp on exit to free memory void reset(); bool load(); long long m_msg4Start; long getTotalOutstandingSpiders ( ) ; void urlFiltersChanged(); key128_t m_firstKey; // spiderdb is now 128bit keys key128_t m_nextKey; key128_t m_endKey; bool m_useTree; //bool m_lastDoledbReadEmpty; //bool m_encounteredDoledbRecs; //long long m_numRoundsDone; //bool m_bestRequestValid; //char m_bestRequestBuf[MAX_BEST_REQUEST_SIZE]; //SpiderRequest *m_bestRequest; //uint64_t m_bestSpiderTimeMS; //long m_bestMaxSpidersPerIp; bool m_lastReplyValid; char m_lastReplyBuf[MAX_SP_REPLY_SIZE]; // doledbkey + dataSize + bestRequestRec //char m_doleBuf[MAX_DOLEREC_SIZE]; SafeBuf m_doleBuf; bool m_isLoading; // for scanning the wait tree... bool m_isPopulating; // for reading from spiderdb //bool m_isReadDone; bool m_didRead; // corresponding to CollectionRec::m_siteListBuf //char *m_siteListAsteriskLine; bool m_siteListHasNegatives; bool m_siteListIsEmpty; bool m_siteListIsEmptyValid; // data buckets in this table are of type HashTableX m_siteListDomTable; // substring matches like "contains:goodstuff" or // later "regex:.*" SafeBuf m_negSubstringBuf; SafeBuf m_posSubstringBuf; RdbCache m_dupCache; RdbTree m_winnerTree; HashTableX m_winnerTable; long m_tailIp; long m_tailPriority; long long m_tailTimeMS; long long m_tailUh48; long m_tailHopCount; long long m_minFutureTimeMS; Msg4 m_msg4x; Msg4 m_msg4; Msg1 m_msg1; bool m_msg1Avail; bool isInDupCache ( SpiderRequest *sreq , bool addToCache ) ; // Rdb.cpp calls this bool addSpiderReply ( SpiderReply *srep ); bool addSpiderRequest ( SpiderRequest *sreq , long long nowGlobalMS ); void removeFromDoledbTable ( long firstIp ); bool addToDoleTable ( SpiderRequest *sreq ) ; bool updateSiteNumInlinksTable ( long siteHash32,long sni,long tstamp); uint64_t getSpiderTimeMS ( SpiderRequest *sreq, long ufn, SpiderReply *srep, uint64_t nowGlobalMS); // doledb cursor keys for each priority to speed up performance key_t m_nextKeys[MAX_SPIDER_PRIORITIES]; // save us scanning empty priorities char m_isDoledbEmpty [MAX_SPIDER_PRIORITIES]; // are all priority slots empt? //long m_allDoledbPrioritiesEmpty; //long m_lastEmptyCheck; // maps priority to first ufn that uses that // priority. map to -1 if no ufn uses it. that way when we scan // priorities for spiderrequests to dole out we can start with // priority 63 and see what the max spiders or same ip wait are // because we need the ufn to get the maxSpiders from the url filters // table. long m_priorityToUfn[MAX_SPIDER_PRIORITIES]; // init this to false, and also set to false on reset, then when // it is false we re-stock m_ufns. re-stock if user changes the // url filters table... bool m_ufnMapValid; // list for loading spiderdb recs during the spiderdb scan RdbList m_list; // spiderdb scan for populating waiting tree RdbList m_list2; Msg5 m_msg5b; bool m_gettingList2; key128_t m_nextKey2; key128_t m_endKey2; time_t m_lastScanTime; bool m_waitingTreeNeedsRebuild; long m_numAdded; long long m_numBytesScanned; long long m_lastPrintCount; // used by SpiderLoop.cpp long m_spidersOut; // . hash of collection name this arena represents // . 0 for main collection collnum_t m_collnum; char m_coll [ MAX_COLL_LEN + 1 ] ; class CollectionRec *getCollRec(); class CollectionRec *m_cr; char *getCollName(); bool m_isTestColl; HashTableX m_doleIpTable; // freshest m_siteNumInlinks per site stored in here HashTableX m_sniTable; // maps a domainHash32 to a crawl delay in milliseconds HashTableX m_cdTable; RdbCache m_lastDownloadCache; bool m_countingPagesIndexed; HashTableX m_localTable; long long m_lastReqUh48a; long long m_lastReqUh48b; long long m_lastRepUh48; // move to CollectionRec so it can load at startup and save it //HashTableX m_pageCountTable; bool makeDoleIPTable ( ); bool makeWaitingTable ( ); bool makeWaitingTree ( ); long long getEarliestSpiderTimeFromWaitingTree ( long firstIp ) ; bool printWaitingTree ( ) ; bool addToWaitingTree ( uint64_t spiderTime , long firstIp , bool callForScan ); long getNextIpFromWaitingTree ( ); void populateDoledbFromWaitingTree ( ); //bool scanSpiderdb ( bool needList ); // broke up scanSpiderdb into simpler functions: bool evalIpLoop ( ) ; bool readListFromSpiderdb ( ) ; bool scanListForWinners ( ) ; bool addWinnersIntoDoledb ( ) ; void populateWaitingTreeFromSpiderdb ( bool reentry ) ; HashTableX m_waitingTable; RdbTree m_waitingTree; RdbMem m_waitingMem; // used by m_waitingTree key_t m_waitingTreeKey; bool m_waitingTreeKeyValid; long m_scanningIp; long m_gotNewDataForScanningIp; long m_lastListSize; long m_lastScanningIp; long long m_totalBytesScanned; char m_deleteMyself; // start key for reading doledb key_t m_msg5StartKey; void devancePriority(); key_t m_nextDoledbKey; bool m_didRound; long m_pri2; bool m_twinDied; long m_lastUrlFiltersUpdate; // for reading lists from spiderdb Msg5 m_msg5; bool m_gettingList1; // how many outstanding spiders a priority has long m_outstandingSpiders[MAX_SPIDER_PRIORITIES]; bool printStats ( SafeBuf &sb ) ; }; class SpiderCache { public: // returns false and set g_errno on error bool init ( ) ; SpiderCache ( ) ; // what SpiderColl does a SpiderRec with this key belong? SpiderColl *getSpiderColl ( collnum_t collNum ) ; SpiderColl *getSpiderCollIffNonNull ( collnum_t collNum ) ; // called by main.cpp on exit to free memory void reset(); void save ( bool useThread ); bool needsSave ( ) ; void doneSaving ( ) ; bool m_isSaving; // . we allocate one SpiderColl per collection // . each one stores the collNum of the collection name it represents, // and has a ptr to it, m_cr, that is updated by sync() // when the Collectiondb is updated // . NOW, this is a ptr in the CollectionRec.. only new'd if // in use, and deleted if not being used... //SpiderColl *m_spiderColls [ MAX_COLL_RECS ]; //long m_numSpiderColls; }; extern class SpiderCache g_spiderCache; ///////// // // we now include the firstip in the case where the same url // has 2 spiderrequests where one is a fake firstip. in that scenario // we will miss the spider request to spider, the waiting tree // node will be removed, and the spider round will complete, // which triggers a waiting tree recompute and we end up spidering // the dup spider request right away and double increment the round. // ///////// inline long long makeLockTableKey ( long long uh48 , long firstIp ) { return uh48 ^ (unsigned long)firstIp; } inline long long makeLockTableKey ( SpiderRequest *sreq ) { return makeLockTableKey(sreq->getUrlHash48(),sreq->m_firstIp); } inline long long makeLockTableKey ( SpiderReply *srep ) { return makeLockTableKey(srep->getUrlHash48(),srep->m_firstIp); } class LockRequest { public: long long m_lockKeyUh48; long m_lockSequence; long m_firstIp; char m_removeLock; collnum_t m_collnum; }; class ConfirmRequest { public: long long m_lockKeyUh48; collnum_t m_collnum; key_t m_doledbKey; long m_firstIp; long m_maxSpidersOutPerIp; }; class UrlLock { public: long m_hostId; long m_lockSequence; long m_timestamp; long m_expires; long m_firstIp; char m_spiderOutstanding; char m_confirmed; collnum_t m_collnum; }; class Msg12 { public: Msg12(); bool confirmLockAcquisition ( ) ; //unsigned long m_lockGroupId; LockRequest m_lockRequest; ConfirmRequest m_confirmRequest; // stuff for getting the msg12 lock for spidering a url bool getLocks ( long long probDocId, char *url , DOLEDBKEY *doledbKey, collnum_t collnum, long sameIpWaitTime, // in milliseconds long maxSpidersOutPerIp, long firstIp, void *state, void (* callback)(void *state) ); bool gotLockReply ( class UdpSlot *slot ); bool removeAllLocks ( ); // these two things comprise the lock request buffer //unsigned long long m_lockKey; // this is the new lock key. just use docid for docid-only spider reqs. unsigned long long m_lockKeyUh48; long m_lockSequence; long long m_origUh48; long m_numReplies; long m_numRequests; long m_grants; bool m_removing; bool m_confirming; char *m_url; // for debugging void *m_state; void (*m_callback)(void *state); bool m_gettingLocks; bool m_hasLock; collnum_t m_collnum; DOLEDBKEY m_doledbKey; long m_sameIpWaitTime; long m_maxSpidersOutPerIp; long m_firstIp; Msg4 m_msg4; }; void handleRequest12 ( UdpSlot *udpSlot , long niceness ) ; void handleRequestc1 ( UdpSlot *slot , long niceness ) ; // . the spider loop // . it gets urls to spider from the SpiderCache global class, g_spiderCache // . supports robots.txt // . supports <META NAME="ROBOTS" CONTENT="NOINDEX"> (no indexing) // . supports <META NAME="ROBOTS" CONTENT="NOFOLLOW"> (no links) // . supports limiting spiders per domain // . max spiders we can have going at once for this process // . limit to 50 to preven OOM conditions #define MAX_SPIDERS 100 class SpiderLoop { public: ~SpiderLoop(); SpiderLoop(); bool isInLockTable ( long long probDocId ); bool printLockTable ( ); long getNumSpidersOutPerIp ( long firstIp , collnum_t collnum ) ; // free all XmlDocs and m_list void reset(); // . call this no matter what // . if spidering is disabled this will sleep about 10 seconds or so // before checking to see if it's been enabled void startLoop(); void doLoop(); void doleUrls1(); void doleUrls2(); long getMaxAllowableSpidersOut ( long pri ) ; void spiderDoledUrls ( ) ; bool gotDoledbList2 ( ) ; // . returns false if blocked and "callback" will be called, // true otherwise // . returns true and sets g_errno on error bool spiderUrl9 ( class SpiderRequest *sreq , key_t *doledbKey , collnum_t collnum,//char *coll , long sameIpWaitTime , // in milliseconds long maxSpidersOutPerIp ); bool spiderUrl2 ( ); Msg12 m_msg12; // state memory for calling SpiderUrl2() (maybe also getLocks()!) SpiderRequest *m_sreq; //char *m_coll; collnum_t m_collnum; char *m_content; long m_contentLen; char m_contentHasMime; key_t *m_doledbKey; void *m_state; void (*m_callback)(void *state); // . the one that was just indexed // . Msg7.cpp uses this to see what docid the injected doc got so it // can forward it to external program long long getLastDocId ( ); // delete m_msg14[i], decrement m_numSpiders, m_maxUsed void cleanUp ( long i ); // registers sleep callback iff not already registered void doSleep ( ) ; bool indexedDoc ( class XmlDoc *doc ); // are we registered for sleep callbacks bool m_isRegistered; long m_numSpidersOut; // for spidering/parsing/indexing a url(s) class XmlDoc *m_docs [ MAX_SPIDERS ]; // . this is "i" where m_msg14[i] is the highest m_msg14 in use // . we use it to limit our scanning to the first "i" m_msg14's long m_maxUsed; // . list for getting next url(s) to spider RdbList m_list; // for getting RdbLists Msg5 m_msg5; class SpiderColl *m_sc; // used to avoid calling getRec() twice! //bool m_gettingList0; long m_outstanding1; bool m_gettingDoledbList; HashTableX m_lockTable; // save on msg12 lookups! keep somewhat local... RdbCache m_lockCache; //bool m_gettingLocks; // for round robining in SpiderLoop::doleUrls(), etc. long m_cri; long long m_doleStart; long m_processed; }; extern class SpiderLoop g_spiderLoop; void clearUfnTable ( ) ; long getUrlFilterNum ( class SpiderRequest *sreq , class SpiderReply *srep , long nowGlobal , bool isForMsg20 , long niceness , class CollectionRec *cr , bool isOutlink , // = false , HashTableX *quotaTable );//= NULL ) ; #endif
[ "masanori.ogino@gmail.com" ]
masanori.ogino@gmail.com
02680ec075b5e117fd54a7751662d18f658cc1c7
988e7ad6574222ca77e8620b9fbe15e1b0cc9a1a
/reverse-of-string.cpp
0b91f66f5cc1dd35f0bca05cdf71353472e9e8e8
[]
no_license
vaarigupta/C-_programs
361df5af8ebb9eb36f79a24189e4ff0be3934bd6
ae5d5c6f3b147b16c5dbdbc449de2c6fbb8a5dac
refs/heads/master
2020-03-12T20:36:20.483047
2018-04-26T08:36:29
2018-04-26T08:36:29
130,809,479
0
0
null
null
null
null
UTF-8
C++
false
false
253
cpp
#include<iostream> #include<cstring> using namespace std; void reverse(char a[]) { int i=0; int j =strlen(a) -1; while(i<=j) { swap(a[i],a[j]); i++; j--; } } int main() { char a[100]; cin.get(a,100); reverse(a); cout<<a; return 0; }
[ "cutievaarigupta@gmail.com" ]
cutievaarigupta@gmail.com
b62269ed8c719e6316288749234db36b395ce70e
6e05fc9db48d795d0485ce8502b3cb9f0ac53074
/spt_helper/src/spt_user_info.cpp
bb868568e39ff024d60a177fdb9e2f18257fa295
[]
no_license
squirrel-project/squirrel_hri
df4a6e6ffb55c25187c7c4f5c334ac8e2c1a3546
719514c945bd06adde608cfc3afeec4ba3cb3869
refs/heads/indigo_dev
2021-09-08T21:27:48.355442
2018-03-12T10:30:13
2018-03-12T10:30:13
28,039,712
0
4
null
2018-03-12T10:30:14
2014-12-15T14:18:25
C
UTF-8
C++
false
false
4,407
cpp
#include <ros/ros.h> #include <visualization_msgs/Marker.h> #include <tf/transform_listener.h> #include <squirrel_person_tracker_msgs/SkeletonVector.h> geometry_msgs::Point gtransformToGpoint(const geometry_msgs::TransformStamped& transform, geometry_msgs::Point& tmpPoint) { tmpPoint.x = transform.transform.translation.x; tmpPoint.y = transform.transform.translation.y; tmpPoint.z = transform.transform.translation.z; return tmpPoint; } void createLineSkel(const squirrel_person_tracker_msgs::Skeleton& skel, visualization_msgs::Marker& line_list) { geometry_msgs::Point tmpPoint; std::vector<geometry_msgs::Point> joint_points; geometry_msgs::TransformStamped transform; line_list.color.b = 1.0; line_list.color.a = 1.0; for (int i = 0; i < skel.skeleton_joints.size(); ++i) { joint_points.push_back(gtransformToGpoint(skel.skeleton_joints[i].joint, tmpPoint)); } if (!joint_points.empty()) { line_list.points.push_back(joint_points[0]); line_list.points.push_back(joint_points[1]); line_list.points.push_back(joint_points[1]); line_list.points.push_back(joint_points[2]); line_list.points.push_back(joint_points[1]); line_list.points.push_back(joint_points[3]); line_list.points.push_back(joint_points[3]); line_list.points.push_back(joint_points[4]); line_list.points.push_back(joint_points[4]); line_list.points.push_back(joint_points[5]); line_list.points.push_back(joint_points[1]); line_list.points.push_back(joint_points[6]); line_list.points.push_back(joint_points[6]); line_list.points.push_back(joint_points[7]); line_list.points.push_back(joint_points[7]); line_list.points.push_back(joint_points[8]); line_list.points.push_back(joint_points[2]); line_list.points.push_back(joint_points[9]); line_list.points.push_back(joint_points[9]); line_list.points.push_back(joint_points[10]); line_list.points.push_back(joint_points[10]); line_list.points.push_back(joint_points[11]); line_list.points.push_back(joint_points[2]); line_list.points.push_back(joint_points[12]); line_list.points.push_back(joint_points[12]); line_list.points.push_back(joint_points[13]); line_list.points.push_back(joint_points[13]); line_list.points.push_back(joint_points[14]); } } void skelVecCB(const squirrel_person_tracker_msgs::SkeletonVector::ConstPtr skel_vec, std::string frame_id, const ros::Publisher& marker_pub, const ros::Publisher& point_pub) { visualization_msgs::Marker line_list; line_list.header.frame_id = frame_id; line_list.header.stamp = ros::Time(0); line_list.action = visualization_msgs::Marker::ADD; line_list.pose.orientation.w = 1.0; line_list.id = 0; line_list.type = visualization_msgs::Marker::LINE_LIST; line_list.scale.x = 0.05; visualization_msgs::Marker sphere_list; sphere_list.header.frame_id = frame_id; sphere_list.header.stamp = ros::Time(0); sphere_list.action = visualization_msgs::Marker::ADD; sphere_list.pose.orientation.w = 1.0; sphere_list.id = 0; sphere_list.type = visualization_msgs::Marker::POINTS; sphere_list.scale.x = 0.15; sphere_list.scale.y = 0.15; sphere_list.color.r = 1; sphere_list.color.g = 0; sphere_list.color.b = 0; sphere_list.color.a = 1; for (int i = 0; i < skel_vec->skeleton_vector.size(); ++i) { createLineSkel(skel_vec->skeleton_vector[i], line_list); if (skel_vec->skeleton_vector[i].isPointing) { sphere_list.header = skel_vec->skeleton_vector[i].pointingPoint.header; sphere_list.points.push_back(skel_vec->skeleton_vector[i].pointingPoint.point); } } point_pub.publish(sphere_list); marker_pub.publish(line_list); sphere_list.points.clear(); line_list.points.clear(); } int main(int argc, char** argv) { ros::init(argc, argv, "spt_skeleton_lines"); ros::NodeHandle n; std::string frame_id = "/kinect_depth_optical_frame"; ros::Publisher marker_pub = n.advertise<visualization_msgs::Marker>("skeleton_lines", 10); ros::Publisher point_pub = n.advertise<visualization_msgs::Marker>("pointing_point", 10); ros::Subscriber subSkelVec = n.subscribe<squirrel_person_tracker_msgs::SkeletonVector>( "/squirrel_person_tracker/user_information", 1, boost::bind(&skelVecCB, _1, frame_id, marker_pub, point_pub)); ros::spin(); }
[ "pregier@cs.uni-bonn.de" ]
pregier@cs.uni-bonn.de
00027acf9ab6f5987171deeec9ca0d7328220c6e
ec5a3af4822403e5adbfb44dfba9ece0c8998ed6
/src/Vulkan/VulkanPipeline.cpp
5e90094384230427fd69843572f5b47e86b295a6
[]
no_license
WeyrSDev/VirtualVistaVulkan
99ff448a39f4d06fe49f2b0d9aa5543c8d79cbd6
6a979510da45b3e55b47674d74078ffdb42565f0
refs/heads/master
2021-05-05T19:14:38.918264
2017-06-15T22:52:09
2017-06-15T22:52:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,561
cpp
#include "VulkanPipeline.h" namespace vv { ///////////////////////////////////////////////////////////////////////////////////////////// Public VulkanPipeline::VulkanPipeline() { } VulkanPipeline::~VulkanPipeline() { } void VulkanPipeline::create(VulkanDevice *device, Shader *shader, VkPipelineLayout pipeline_layout, VulkanRenderPass *render_pass, VkFrontFace front_face, bool depth_test_enable, bool depth_write_enable) { _device = device; VkPipelineShaderStageCreateInfo vert_shader_create_info = {}; vert_shader_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; vert_shader_create_info.stage = VK_SHADER_STAGE_VERTEX_BIT; vert_shader_create_info.module = shader->vert_module; vert_shader_create_info.pName = "main"; VkPipelineShaderStageCreateInfo frag_shader_create_info = {}; frag_shader_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; frag_shader_create_info.stage = VK_SHADER_STAGE_FRAGMENT_BIT; frag_shader_create_info.module = shader->frag_module; frag_shader_create_info.pName = "main"; std::array<VkPipelineShaderStageCreateInfo, 2> shaders = { vert_shader_create_info, frag_shader_create_info }; // Fixed Function Pipeline Layout VkPipelineVertexInputStateCreateInfo vertex_input_state_create_info = {}; vertex_input_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertex_input_state_create_info.flags = 0; vertex_input_state_create_info.vertexBindingDescriptionCount = 1; vertex_input_state_create_info.vertexAttributeDescriptionCount = (uint32_t)Vertex::getAttributeDescriptions().size(); vertex_input_state_create_info.pVertexBindingDescriptions = &Vertex::getBindingDesciption(); vertex_input_state_create_info.pVertexAttributeDescriptions = Vertex::getAttributeDescriptions().data(); VkPipelineInputAssemblyStateCreateInfo input_assembly_create_info = {}; input_assembly_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; input_assembly_create_info.flags = 0; input_assembly_create_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; // render triangles input_assembly_create_info.primitiveRestartEnable = VK_FALSE; // todo: viewport should be dynamic. figure out how to update pipeline when needed. probably has to do with dynamic state settings. VkViewport viewport = {}; viewport.width = static_cast<float>(Settings::inst()->getWindowWidth()); viewport.height = static_cast<float>(Settings::inst()->getWindowHeight()); viewport.x = 0.0f; viewport.y = 0.0f; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor = {}; scissor.offset = { 0, 0 }; scissor.extent.width = static_cast<uint32_t>(Settings::inst()->getWindowWidth()); scissor.extent.height = static_cast<uint32_t>(Settings::inst()->getWindowHeight()); VkPipelineViewportStateCreateInfo viewport_state_create_info = {}; viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewport_state_create_info.flags = 0; viewport_state_create_info.viewportCount = 1; viewport_state_create_info.scissorCount = 1; viewport_state_create_info.pViewports = &viewport; viewport_state_create_info.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterization_state_create_info = {}; rasterization_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterization_state_create_info.depthClampEnable = VK_FALSE; // clamp geometry within clip space rasterization_state_create_info.rasterizerDiscardEnable = VK_FALSE; // discard geometry rasterization_state_create_info.polygonMode = VK_POLYGON_MODE_FILL; // create fragments from the inside of a polygon rasterization_state_create_info.lineWidth = 1.0f; rasterization_state_create_info.cullMode = VK_CULL_MODE_BACK_BIT; // cull the back of polygons from rendering rasterization_state_create_info.frontFace = front_face;// VK_FRONT_FACE_CLOCKWISE; // order of vertices rasterization_state_create_info.depthBiasEnable = VK_FALSE; // all stuff for shadow mapping? look into it rasterization_state_create_info.depthBiasClamp = 0.0f; rasterization_state_create_info.depthBiasConstantFactor = 0.0f; rasterization_state_create_info.depthBiasSlopeFactor = 0.0f; // todo: add anti-aliasing settings support VkPipelineMultisampleStateCreateInfo multisample_state_create_info = {}; multisample_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisample_state_create_info.flags = 0; multisample_state_create_info.sampleShadingEnable = VK_FALSE; multisample_state_create_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisample_state_create_info.minSampleShading = 1.0f; multisample_state_create_info.pSampleMask = nullptr; multisample_state_create_info.alphaToCoverageEnable = VK_FALSE; multisample_state_create_info.alphaToOneEnable = VK_FALSE; VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info = {}; depth_stencil_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; depth_stencil_state_create_info.flags = 0; depth_stencil_state_create_info.depthTestEnable = depth_test_enable; depth_stencil_state_create_info.depthWriteEnable = depth_write_enable; depth_stencil_state_create_info.depthCompareOp = VK_COMPARE_OP_LESS; depth_stencil_state_create_info.depthBoundsTestEnable = VK_FALSE; depth_stencil_state_create_info.minDepthBounds = 0.0f; depth_stencil_state_create_info.maxDepthBounds = 1.0f; depth_stencil_state_create_info.stencilTestEnable = VK_FALSE; // don't want to do any cutting of the image currently. depth_stencil_state_create_info.front = {}; depth_stencil_state_create_info.back = {}; // todo: for some reason, if this is activated the output color is overridden // This along with color blend create info specify alpha blending operations VkPipelineColorBlendAttachmentState color_blend_attachment_state = {}; color_blend_attachment_state.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; color_blend_attachment_state.blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo color_blend_state_create_info = {}; color_blend_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; color_blend_state_create_info.logicOpEnable = VK_FALSE; color_blend_state_create_info.logicOp = VK_LOGIC_OP_COPY; color_blend_state_create_info.attachmentCount = 1; color_blend_state_create_info.pAttachments = &color_blend_attachment_state; color_blend_state_create_info.blendConstants[0] = 0.0f; color_blend_state_create_info.blendConstants[1] = 0.0f; color_blend_state_create_info.blendConstants[2] = 0.0f; color_blend_state_create_info.blendConstants[3] = 0.0f; // add enum values here for more dynamic pipeline state changes!! /*std::array<VkDynamicState, 2> dynamic_pipeline_settings = { VK_DYNAMIC_STATE_VIEWPORT }; VkPipelineDynamicStateCreateInfo dynamic_state_create_info = {}; dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamic_state_create_info.flags = 0; dynamic_state_create_info.dynamicStateCount = (uint32_t)dynamic_pipeline_settings.size(); dynamic_state_create_info.pDynamicStates = dynamic_pipeline_settings.data();*/ VkGraphicsPipelineCreateInfo graphics_pipeline_create_info = {}; graphics_pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; graphics_pipeline_create_info.flags = 0; graphics_pipeline_create_info.stageCount = 2; graphics_pipeline_create_info.pStages = shaders.data(); graphics_pipeline_create_info.pVertexInputState = &vertex_input_state_create_info; graphics_pipeline_create_info.pInputAssemblyState = &input_assembly_create_info; graphics_pipeline_create_info.pViewportState = &viewport_state_create_info; graphics_pipeline_create_info.pRasterizationState = &rasterization_state_create_info; graphics_pipeline_create_info.pDynamicState = VK_NULL_HANDLE;//&dynamic_state_create_info; graphics_pipeline_create_info.pTessellationState = VK_NULL_HANDLE; graphics_pipeline_create_info.pMultisampleState = &multisample_state_create_info; graphics_pipeline_create_info.pDepthStencilState = &depth_stencil_state_create_info; graphics_pipeline_create_info.pColorBlendState = &color_blend_state_create_info; graphics_pipeline_create_info.layout = pipeline_layout; graphics_pipeline_create_info.renderPass = render_pass->render_pass; graphics_pipeline_create_info.subpass = 0; // index of render_pass that this pipeline will be used with graphics_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE; // used for creating new pipeline from existing one. // info: the null handle here specifies a VkPipelineCache that can be used to store pipeline creation info after a pipeline's deletion. VV_CHECK_SUCCESS(vkCreateGraphicsPipelines(_device->logical_device, VK_NULL_HANDLE, 1, &graphics_pipeline_create_info, nullptr, &pipeline)); } void VulkanPipeline::shutDown() { vkDestroyPipeline(_device->logical_device, pipeline, nullptr); } void VulkanPipeline::bind(VkCommandBuffer command_buffer, VkPipelineBindPoint bind_point) const { vkCmdBindPipeline(command_buffer, bind_point, pipeline); } ///////////////////////////////////////////////////////////////////////////////////////////// Private }
[ "romanylarionov@gmail.com" ]
romanylarionov@gmail.com
de22b7071a63a301c8fd819b9184914c37367a37
c4692fbdc122876043a060756aa9ef61e563fca1
/proper/abi/include/locale_misc/collate-inl.h
c68b9b05c41cccf3e2fb4ea0916d0182d6b8e1d9
[]
no_license
nahratzah/ilias_os
837b8eabe3d638767d552206b5c2691a176069fa
a63c03a36e656cee1b897eb952a39bccc2616406
refs/heads/master
2021-01-23T13:43:55.103755
2015-06-11T07:37:01
2015-06-11T07:37:01
28,526,656
1
0
null
null
null
null
UTF-8
C++
false
false
2,653
h
#ifndef _LOCALE_MISC_COLLATE_INL_H_ #define _LOCALE_MISC_COLLATE_INL_H_ #include <locale_misc/collate.h> _namespace_begin(std) template<typename Char> collate<Char>::collate(size_t refs) : locale::facet(refs) {} template<typename Char> collate<Char>::~collate() noexcept {} template<typename Char> auto collate<Char>::compare(const char_type* b1, const char_type* e1, const char_type* b2, const char_type* e2) const -> int { return do_compare(b1, e1, b2, e2); } template<typename Char> auto collate<Char>::transform(const char_type* b, const char_type* e) const -> string_type { return do_transform(b, e); } template<typename Char> auto collate<Char>::hash(const char_type* b, const char_type* e) const -> long { return do_hash(b, e); } template<typename Char> auto collate<Char>::do_compare(const char_type* b1, const char_type* e1, const char_type* b2, const char_type* e2) const -> int { int rv = char_traits<Char>::compare(b1, e1, min(e1 - b1, e2 - b2)); if (rv == 0) { if (e1 - b1 < e2 - b2) return -1; if (e1 - b1 > e2 - b2) return 1; } return 0; } template<typename Char> auto collate<Char>::do_transform(const char_type* b, const char_type* e) const -> string_type { return string_type(b, e); } template<typename Char> auto collate<Char>::do_hash(const char_type* b, const char_type* e) const -> long { using string = basic_string_ref<Char>; using hash_t = _namespace(std)::hash<string>; return hash_t()(string(b, typename string::size_type(e - b))); } template<typename Char> collate_byname<Char>::collate_byname(const char* name, size_t refs) : collate_byname(string_ref(name), refs) {} template<typename Char> collate_byname<Char>::collate_byname(const string& name, size_t refs) : collate_byname(string_ref(name), refs) {} template<typename Char> collate_byname<Char>::collate_byname(string_ref name, size_t refs) : collate<Char>(refs), impl::facet_ref<collate<Char>>(locale(name)) {} template<typename Char> auto collate_byname<Char>::do_compare(const char_type* b1, const char_type* e1, const char_type* b2, const char_type* e2) const -> int { return this->impl.compare(b1, e1, b2, e2); } template<typename Char> auto collate_byname<Char>::do_transform(const char_type* b, const char_type* e) const -> string_type { return this->impl.transform(b, e); } template<typename Char> auto collate_byname<Char>::do_hash(const char_type* b, const char_type* e) const -> long { return this->impl.hash(b, e); } _namespace_end(std) #endif /* _LOCALE_MISC_COLLATE_INL_H_ */
[ "ariane@stack.nl" ]
ariane@stack.nl
cce76a425374a67e655a29adb6fe02cc28bab0a2
afe353957386de4859f782d29743d1536c5660c5
/OpenGL_4_Application_VS2015/Camera.hpp
0475847f179ecd65e67d48e8eb18d126fa4a5f88
[]
no_license
BlagaCristi/GraphicalProcessingSystemsProject
df0722819f4e40acea150bbdfefd5e2768e638ee
f4380fb0c4168023b28e416625d4426ce02396ba
refs/heads/master
2023-03-05T01:28:49.308577
2021-01-30T19:13:08
2021-01-30T19:13:08
334,490,492
0
0
null
null
null
null
UTF-8
C++
false
false
862
hpp
// // Camera.hpp // // Created by CGIS on 28/10/2016. // Copyright © 2016 CGIS. All rights reserved. // #ifndef Camera_hpp #define Camera_hpp #include <stdio.h> #include "glm/glm.hpp" #include "glm/gtx/transform.hpp" namespace gps { enum MOVE_DIRECTION {MOVE_FORWARD, MOVE_BACKWARD, MOVE_RIGHT, MOVE_LEFT}; class Camera { public: Camera(glm::vec3 cameraPosition, glm::vec3 cameraTarget); glm::mat4 getViewMatrix(); glm::vec3 getCameraTarget(); glm::vec3 getCameraPosition(); void move(MOVE_DIRECTION direction, float speed); void rotate(float pitch, float yaw); void rotateAroundY(float angle); private: glm::vec3 cameraPosition; glm::vec3 cameraTarget; glm::vec3 cameraDirection; glm::vec3 cameraRightDirection; }; } #endif /* Camera_hpp */
[ "blaga.cristi23@gmail.com" ]
blaga.cristi23@gmail.com
2cc76ada63d066c138b7a4202bf08d90b6980398
140d78334109e02590f04769ec154180b2eaf78d
/aws-cpp-sdk-marketplace-entitlement/include/aws/marketplace-entitlement/model/Entitlement.h
cb1cbd41f3eecf0ef1a6221433aa447189bb6eda
[ "Apache-2.0", "MIT", "JSON" ]
permissive
coderTong/aws-sdk-cpp
da140feb7e5495366a8d2a6a02cf8b28ba820ff6
5cd0c0a03b667c5a0bd17394924abe73d4b3754a
refs/heads/master
2021-07-08T07:04:40.181622
2017-08-22T21:50:00
2017-08-22T21:50:00
101,145,374
0
1
Apache-2.0
2021-05-04T21:06:36
2017-08-23T06:24:37
C++
UTF-8
C++
false
false
12,794
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 #include <aws/marketplace-entitlement/MarketplaceEntitlementService_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/marketplace-entitlement/model/EntitlementValue.h> #include <aws/core/utils/DateTime.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace MarketplaceEntitlementService { namespace Model { /** * <p>An entitlement represents capacity in a product owned by the customer. For * example, a customer might own some number of users or seats in an SaaS * application or some amount of data capacity in a multi-tenant * database.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/entitlement.marketplace-2017-01-11/Entitlement">AWS * API Reference</a></p> */ class AWS_MARKETPLACEENTITLEMENTSERVICE_API Entitlement { public: Entitlement(); Entitlement(const Aws::Utils::Json::JsonValue& jsonValue); Entitlement& operator=(const Aws::Utils::Json::JsonValue& jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline const Aws::String& GetProductCode() const{ return m_productCode; } /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline void SetProductCode(const Aws::String& value) { m_productCodeHasBeenSet = true; m_productCode = value; } /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline void SetProductCode(Aws::String&& value) { m_productCodeHasBeenSet = true; m_productCode = std::move(value); } /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline void SetProductCode(const char* value) { m_productCodeHasBeenSet = true; m_productCode.assign(value); } /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline Entitlement& WithProductCode(const Aws::String& value) { SetProductCode(value); return *this;} /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline Entitlement& WithProductCode(Aws::String&& value) { SetProductCode(std::move(value)); return *this;} /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline Entitlement& WithProductCode(const char* value) { SetProductCode(value); return *this;} /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline const Aws::String& GetDimension() const{ return m_dimension; } /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline void SetDimension(const Aws::String& value) { m_dimensionHasBeenSet = true; m_dimension = value; } /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline void SetDimension(Aws::String&& value) { m_dimensionHasBeenSet = true; m_dimension = std::move(value); } /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline void SetDimension(const char* value) { m_dimensionHasBeenSet = true; m_dimension.assign(value); } /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline Entitlement& WithDimension(const Aws::String& value) { SetDimension(value); return *this;} /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline Entitlement& WithDimension(Aws::String&& value) { SetDimension(std::move(value)); return *this;} /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline Entitlement& WithDimension(const char* value) { SetDimension(value); return *this;} /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline const Aws::String& GetCustomerIdentifier() const{ return m_customerIdentifier; } /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline void SetCustomerIdentifier(const Aws::String& value) { m_customerIdentifierHasBeenSet = true; m_customerIdentifier = value; } /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline void SetCustomerIdentifier(Aws::String&& value) { m_customerIdentifierHasBeenSet = true; m_customerIdentifier = std::move(value); } /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline void SetCustomerIdentifier(const char* value) { m_customerIdentifierHasBeenSet = true; m_customerIdentifier.assign(value); } /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline Entitlement& WithCustomerIdentifier(const Aws::String& value) { SetCustomerIdentifier(value); return *this;} /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline Entitlement& WithCustomerIdentifier(Aws::String&& value) { SetCustomerIdentifier(std::move(value)); return *this;} /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline Entitlement& WithCustomerIdentifier(const char* value) { SetCustomerIdentifier(value); return *this;} /** * <p>The EntitlementValue represents the amount of capacity that the customer is * entitled to for the product.</p> */ inline const EntitlementValue& GetValue() const{ return m_value; } /** * <p>The EntitlementValue represents the amount of capacity that the customer is * entitled to for the product.</p> */ inline void SetValue(const EntitlementValue& value) { m_valueHasBeenSet = true; m_value = value; } /** * <p>The EntitlementValue represents the amount of capacity that the customer is * entitled to for the product.</p> */ inline void SetValue(EntitlementValue&& value) { m_valueHasBeenSet = true; m_value = std::move(value); } /** * <p>The EntitlementValue represents the amount of capacity that the customer is * entitled to for the product.</p> */ inline Entitlement& WithValue(const EntitlementValue& value) { SetValue(value); return *this;} /** * <p>The EntitlementValue represents the amount of capacity that the customer is * entitled to for the product.</p> */ inline Entitlement& WithValue(EntitlementValue&& value) { SetValue(std::move(value)); return *this;} /** * <p>The expiration date represents the minimum date through which this * entitlement is expected to remain valid. For contractual products listed on AWS * Marketplace, the expiration date is the date at which the customer will renew or * cancel their contract. Customers who are opting to renew their contract will * still have entitlements with an expiration date.</p> */ inline const Aws::Utils::DateTime& GetExpirationDate() const{ return m_expirationDate; } /** * <p>The expiration date represents the minimum date through which this * entitlement is expected to remain valid. For contractual products listed on AWS * Marketplace, the expiration date is the date at which the customer will renew or * cancel their contract. Customers who are opting to renew their contract will * still have entitlements with an expiration date.</p> */ inline void SetExpirationDate(const Aws::Utils::DateTime& value) { m_expirationDateHasBeenSet = true; m_expirationDate = value; } /** * <p>The expiration date represents the minimum date through which this * entitlement is expected to remain valid. For contractual products listed on AWS * Marketplace, the expiration date is the date at which the customer will renew or * cancel their contract. Customers who are opting to renew their contract will * still have entitlements with an expiration date.</p> */ inline void SetExpirationDate(Aws::Utils::DateTime&& value) { m_expirationDateHasBeenSet = true; m_expirationDate = std::move(value); } /** * <p>The expiration date represents the minimum date through which this * entitlement is expected to remain valid. For contractual products listed on AWS * Marketplace, the expiration date is the date at which the customer will renew or * cancel their contract. Customers who are opting to renew their contract will * still have entitlements with an expiration date.</p> */ inline Entitlement& WithExpirationDate(const Aws::Utils::DateTime& value) { SetExpirationDate(value); return *this;} /** * <p>The expiration date represents the minimum date through which this * entitlement is expected to remain valid. For contractual products listed on AWS * Marketplace, the expiration date is the date at which the customer will renew or * cancel their contract. Customers who are opting to renew their contract will * still have entitlements with an expiration date.</p> */ inline Entitlement& WithExpirationDate(Aws::Utils::DateTime&& value) { SetExpirationDate(std::move(value)); return *this;} private: Aws::String m_productCode; bool m_productCodeHasBeenSet; Aws::String m_dimension; bool m_dimensionHasBeenSet; Aws::String m_customerIdentifier; bool m_customerIdentifierHasBeenSet; EntitlementValue m_value; bool m_valueHasBeenSet; Aws::Utils::DateTime m_expirationDate; bool m_expirationDateHasBeenSet; }; } // namespace Model } // namespace MarketplaceEntitlementService } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
e381831028fd574d1c0d62069e8810ba4d330d17
0fc78bbf3e9656878924d0ac4b2beec5a4579d81
/perpalin.cpp
8c76d85b7ccc4ee2f25de4fbbc40e94776862524
[]
no_license
adityalahiri/CPP-Code
b15e7139a49b78d87be849465294bff44a87cbe9
98defdeb37388ceb109a5e94b1ac75a0bdc7ec70
refs/heads/master
2021-10-09T12:02:50.874157
2018-12-27T10:51:19
2018-12-27T10:51:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
509
cpp
#include <iostream> #include <bits/stdc++.h> using namespace std; typedef long long ll; int main(){ int num_tests = 0; cin>>num_tests; while(num_tests--){ ll N,P; cin>>N>>P; if((N==P && N==2) || P == 1 || P == 2){ cout<<"impossible"<<endl; continue; } string s[P]; s[0] = 'a'; s[P-1] = 'a'; for(ll i = 1; i<P-1; i++) s[i] = 'b'; for(ll i = 0; i<N; i+=P){ for(ll i = 0; i<P; i++) cout<<s[i]; } cout<<endl; } }
[ "arrayslayer@gmail.com" ]
arrayslayer@gmail.com
b0f9da022642503c09c3942f0110255898253dfd
1a20961af3b03b46c109b09812143a7ef95c6caa
/ZGame/DX11/DirectXTex/ScreenGrab/ScreenGrab12.h
f20c42191774ee2c60f1bf686f41b38e63d8f6bd
[ "MIT" ]
permissive
JetAr/ZNginx
eff4ae2457b7b28115787d6af7a3098c121e8368
698b40085585d4190cf983f61b803ad23468cdef
refs/heads/master
2021-07-16T13:29:57.438175
2017-10-23T02:05:43
2017-10-23T02:05:43
26,522,265
3
1
null
null
null
null
UTF-8
C++
false
false
1,845
h
//-------------------------------------------------------------------------------------- // File: ScreenGrab12.h // // Function for capturing a 2D texture and saving it to a file (aka a 'screenshot' // when used on a Direct3D 12 Render Target). // // Note these functions are useful as a light-weight runtime screen grabber. For // full-featured texture capture, DDS writer, and texture processing pipeline, // see the 'Texconv' sample and the 'DirectXTex' library. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/?LinkId=248926 // http://go.microsoft.com/fwlink/?LinkID=615561 //-------------------------------------------------------------------------------------- #pragma once #include <d3d12.h> #include <ocidl.h> #include <stdint.h> #include <functional> namespace DirectX { HRESULT __cdecl SaveDDSTextureToFile( _In_ ID3D12CommandQueue* pCommandQueue, _In_ ID3D12Resource* pSource, _In_z_ const wchar_t* fileName, D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_RENDER_TARGET); HRESULT __cdecl SaveWICTextureToFile( _In_ ID3D12CommandQueue* pCommandQ, _In_ ID3D12Resource* pSource, REFGUID guidContainerFormat, _In_z_ const wchar_t* fileName, D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_RENDER_TARGET, _In_opt_ const GUID* targetFormat = nullptr, _In_opt_ std::function<void __cdecl(IPropertyBag2*)> setCustomProps = nullptr); }
[ "126.org@gmail.com" ]
126.org@gmail.com
b5952f4126ae3959822968d187aae5fa4f573542
40aa541c6529115e964d50ec4fe6f7cf774bc0cb
/opt_algs.1.0/oa_hillclimb.h
cca2d76d9dcf6d367305bcfd95f5e41230d7cc99
[ "BSD-3-Clause" ]
permissive
ghornby/opt_algs
663edcc2f32d7a195f394108c883948d48dd614c
b68aefceda7c6ab50976e87551cc6986b5616321
refs/heads/master
2020-05-18T19:33:01.257390
2017-04-05T18:57:17
2017-04-05T18:57:17
20,343,075
1
0
null
null
null
null
UTF-8
C++
false
false
2,041
h
/*** This file is part of the OptAlgs C++ library originally developed by Gregory Hornby. This code is released under the BSD-3 license: http://opensource.org/licenses/BSD-3-Clause See the file "license.txt" in the root directory for full details. ***/ /* author: Gregory S. Hornby file: oa_hillclimb.h Description: This a simple search algorithm which uses a hill-climbing strategy. */ #ifndef OA_HILLCLIMB_HEADER_FILE #define OA_HILLCLIMB_HEADER_FILE #include "opt_alg.h" #include <iostream> #include <fstream> #include <map> #include <semaphore.h> #include <set> #include <string> #include <vector> class FitnessFunc; class Individual; class HillClimber : public OptAlg { friend std::ostream& operator<<(std::ostream&, const HillClimber&); friend std::istream& operator>>(std::istream&, HillClimber&); public: const static std::string class_name_; /* ******* */ HillClimber(const FitnessFunc* func, const Individual* ind_template); ~HillClimber(); std::string get_class_name() const { return class_name_; } void copy_settings(const HillClimber* p_src); OptAlg* new_instance(const Individual*) const; OptAlg* new_instance() const; OptAlg* make_copy() const; void clear(); void init_variables(); // Only resets evaluation counts. virtual int configure(const char *fname, int verbose); // ************************************************** void do_search_step(); // ************************************************** void print_current_individs(std::ostream& ostr); void print_current_individs(); virtual std::ostream& write_template(std::ostream& ostr) const; virtual std::ostream& write_header(std::ostream& ostr) const; virtual std::ostream& write(std::ostream& os) const; virtual bool write(const char *fname) const; virtual bool write_backup() const; virtual std::istream& read(std::istream& is); virtual bool read(const char *fname); // ********************* protected: Individual* individ_best_; Individual* individ_new_; }; #endif
[ "ghornby@gmail.com" ]
ghornby@gmail.com
527066550fcc10c61464f38660542c8052c3c0ae
1d351697bcf282cd30044db8c35eb10036bca483
/Sound/ScriptMgr.h
8d14371b2cbacc90c901f1b9e984f2b149e03e50
[]
no_license
Hyski/ParadiseCracked
489c007d39a7f7f7a0331a7282d8ba4f083918c0
b3815cc146c038a8454c97e9f48d462c8ddc50ca
refs/heads/master
2021-04-04T13:21:18.347302
2020-03-19T09:25:44
2020-03-19T09:25:44
248,460,973
0
1
null
null
null
null
WINDOWS-1251
C++
false
false
631
h
#if !defined(__SCRIPT_MANAGER_INCLUDED__) #define __SCRIPT_MANAGER_INCLUDED__ #include <map> class cc_DirectMusic; class cc_SndScript; class cc_SegmentMgr; class cc_ScriptMgr { static const char *m_LogFile; typedef std::map<std::string,cc_SndScript *> scripts_t; scripts_t m_Scripts; DECLARE_LOG_MEMBER(m_log); cc_SegmentMgr *m_segmentMgr; public: cc_ScriptMgr(cc_SegmentMgr *); ~cc_ScriptMgr(); // Инициализация/деинициализация // void init(); // void shut(); cc_SndScript *getScript(const char *scriptName); // Для загрузчика void addScript(cc_SndScript *); }; #endif
[ "43969955+Hyski@users.noreply.github.com" ]
43969955+Hyski@users.noreply.github.com
98efd4f0d622df241b771c7a6d3ec86923f8d5cc
e51d009c6c6a1633c2c11ea4e89f289ea294ec7e
/xr2-dsgn/sources/xray/physics/sources/geometry.h
b87b5dc0b929c6fe532929e5251760a5b90d7e52
[]
no_license
avmal0-Cor/xr2-dsgn
a0c726a4d54a2ac8147a36549bc79620fead0090
14e9203ee26be7a3cb5ca5da7056ecb53c558c72
refs/heads/master
2023-07-03T02:05:00.566892
2021-08-06T03:10:53
2021-08-06T03:10:53
389,939,196
3
2
null
null
null
null
UTF-8
C++
false
false
1,697
h
//////////////////////////////////////////////////////////////////////////// // Created : 30.01.2008 // Author : Konstantin Slipchenko // Description : geometry: collision geometry to integration cycle interface //////////////////////////////////////////////////////////////////////////// #ifndef XRAY_PHYSICS_GEOMETRY_H_INCLUDED #define XRAY_PHYSICS_GEOMETRY_H_INCLUDED #include "pose_anchor.h" class contact_info_buffer; class complex_geometry; class transformed_geometry; class box_geometry; class sphere_geometry; class cylinder_geometry; class triangle_mesh_base; class geometry { public: virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const geometry& og ) const = 0; virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const transformed_geometry& og ) const = 0; virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const complex_geometry& og ) const = 0; virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const box_geometry& og ) const = 0; virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const sphere_geometry& og ) const = 0; virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const cylinder_geometry& og ) const = 0; virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const triangle_mesh_base& og ) const = 0; public: virtual ~geometry( ){} protected: // virtual void generate_contacts( contact_info_buffer &contacts, const pose_anchor &anch, const geometry &og )const =0; }; #endif
[ "youalexandrov@icloud.com" ]
youalexandrov@icloud.com
750ba1e613b374e8fce1631ec5ab6f16090c2e9c
bb0c64f97a7350b48e0a1c7a6f54429a436c6e10
/board.h
71ae61c69c16351dbe3496c4401a98b66bec957f
[]
no_license
arladerus/cs246FinalProject
1c32df001c46a56082b6c0925c3cb52fbb4feaec
23e2e6ac2338227d822c8c8cdb9b5b5ee9a99f75
refs/heads/master
2021-01-18T10:36:50.335480
2013-07-21T04:07:55
2013-07-21T04:07:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
958
h
#ifndef __BOARD_H__ #define __BOARD_H__ #include "cell.h" #include "window.h" #include<iostream> class Board{ Cell ** gameBoard; //the board object that holds the game matrix Xwindow * window; //the GUI int xStartPos; //default starting location for the blocks int yStartPos; int column; //column of the matrix int row; //row of the matrix int cellSize; //size of each cell on screen public: Board(); Board(const int& row, const int& column, const int& xStart, const int& yStart); ~Board(); bool isEmpty(const int&x , const int&y); //returns if the location is empty, false if it reaches an edge bool moveCell(const int& xFrom, const int& yFrom, const int& xDest, const int& yDest); //moves the cell, empties the original cell, invoked by the Block class //returns false if the destination cell is occupied void XwindowUpdate(); //updates the window friend std::ostream& operator<<(std::ostream&, const Board&); }; #endif
[ "joeyjoeyze@hotmail.com" ]
joeyjoeyze@hotmail.com
54ad0d10779dfcbc8509a28b21650256e9850955
eac0bb6459c9d8a2c725263e3352c80e8a102d48
/src/s390/assembler-s390.h
b916884a544c0071031dedfa4594b3673756b6ad
[ "BSD-3-Clause", "bzip2-1.0.6", "SunPro" ]
permissive
Yafei5515/v8
cf3b00daa7cf9a44e2c23477f13c8e33c4b946ac
f1e04dbc0ad5eb6e593735ba98a3bf353af177b8
refs/heads/master
2020-04-14T23:03:22.174990
2019-01-05T03:08:28
2019-01-05T03:49:20
164,188,391
2
0
null
null
null
null
UTF-8
C++
false
false
58,326
h
// Copyright (c) 1994-2006 Sun Microsystems Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // - Redistribution 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. // // - Neither the name of Sun Microsystems or the names of contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // The original source code covered by the above license above has been // modified significantly by Google Inc. // Copyright 2014 the V8 project authors. All rights reserved. // A light-weight S390 Assembler // Generates user mode instructions for z/Architecture #ifndef V8_S390_ASSEMBLER_S390_H_ #define V8_S390_ASSEMBLER_S390_H_ #include <stdio.h> #if V8_HOST_ARCH_S390 // elf.h include is required for auxv check for STFLE facility used // for hardware detection, which is sensible only on s390 hosts. #include <elf.h> #endif #include <fcntl.h> #include <unistd.h> #include <vector> #include "src/assembler.h" #include "src/external-reference.h" #include "src/label.h" #include "src/objects/smi.h" #include "src/s390/constants-s390.h" #include "src/s390/register-s390.h" #define ABI_USES_FUNCTION_DESCRIPTORS 0 #define ABI_PASSES_HANDLES_IN_REGS 1 // ObjectPair is defined under runtime/runtime-util.h. // On 31-bit, ObjectPair == uint64_t. ABI dictates long long // be returned with the lower addressed half in r2 // and the higher addressed half in r3. (Returns in Regs) // On 64-bit, ObjectPair is a Struct. ABI dictaes Structs be // returned in a storage buffer allocated by the caller, // with the address of this buffer passed as a hidden // argument in r2. (Does NOT return in Regs) // For x86 linux, ObjectPair is returned in registers. #if V8_TARGET_ARCH_S390X #define ABI_RETURNS_OBJECTPAIR_IN_REGS 0 #else #define ABI_RETURNS_OBJECTPAIR_IN_REGS 1 #endif #define ABI_CALL_VIA_IP 1 #define INSTR_AND_DATA_CACHE_COHERENCY LWSYNC namespace v8 { namespace internal { // ----------------------------------------------------------------------------- // Machine instruction Operands // Class Operand represents a shifter operand in data processing instructions // defining immediate numbers and masks class Operand { public: // immediate V8_INLINE explicit Operand(intptr_t immediate, RelocInfo::Mode rmode = RelocInfo::NONE) : rmode_(rmode) { value_.immediate = immediate; } V8_INLINE static Operand Zero() { return Operand(static_cast<intptr_t>(0)); } V8_INLINE explicit Operand(const ExternalReference& f) : rmode_(RelocInfo::EXTERNAL_REFERENCE) { value_.immediate = static_cast<intptr_t>(f.address()); } explicit Operand(Handle<HeapObject> handle); V8_INLINE explicit Operand(Smi value) : rmode_(RelocInfo::NONE) { value_.immediate = static_cast<intptr_t>(value.ptr()); } // rm V8_INLINE explicit Operand(Register rm); static Operand EmbeddedNumber(double value); // Smi or HeapNumber static Operand EmbeddedStringConstant(const StringConstantBase* str); // Return true if this is a register operand. V8_INLINE bool is_reg() const { return rm_.is_valid(); } bool must_output_reloc_info(const Assembler* assembler) const; inline intptr_t immediate() const { DCHECK(!rm_.is_valid()); DCHECK(!is_heap_object_request()); return value_.immediate; } HeapObjectRequest heap_object_request() const { DCHECK(is_heap_object_request()); return value_.heap_object_request; } inline void setBits(int n) { value_.immediate = (static_cast<uint32_t>(value_.immediate) << (32 - n)) >> (32 - n); } Register rm() const { return rm_; } bool is_heap_object_request() const { DCHECK_IMPLIES(is_heap_object_request_, !rm_.is_valid()); DCHECK_IMPLIES(is_heap_object_request_, rmode_ == RelocInfo::EMBEDDED_OBJECT || rmode_ == RelocInfo::CODE_TARGET); return is_heap_object_request_; } RelocInfo::Mode rmode() const { return rmode_; } private: Register rm_ = no_reg; union Value { Value() {} HeapObjectRequest heap_object_request; // if is_heap_object_request_ intptr_t immediate; // otherwise } value_; // valid if rm_ == no_reg bool is_heap_object_request_ = false; RelocInfo::Mode rmode_; friend class Assembler; friend class MacroAssembler; }; typedef int32_t Disp; // Class MemOperand represents a memory operand in load and store instructions // On S390, we have various flavours of memory operands: // 1) a base register + 16 bit unsigned displacement // 2) a base register + index register + 16 bit unsigned displacement // 3) a base register + index register + 20 bit signed displacement class MemOperand { public: explicit MemOperand(Register rx, Disp offset = 0); explicit MemOperand(Register rx, Register rb, Disp offset = 0); int32_t offset() const { return offset_; } uint32_t getDisplacement() const { return offset(); } // Base register Register rb() const { DCHECK(baseRegister != no_reg); return baseRegister; } Register getBaseRegister() const { return rb(); } // Index Register Register rx() const { DCHECK(indexRegister != no_reg); return indexRegister; } Register getIndexRegister() const { return rx(); } private: Register baseRegister; // base Register indexRegister; // index int32_t offset_; // offset friend class Assembler; }; class DeferredRelocInfo { public: DeferredRelocInfo() {} DeferredRelocInfo(int position, RelocInfo::Mode rmode, intptr_t data) : position_(position), rmode_(rmode), data_(data) {} int position() const { return position_; } RelocInfo::Mode rmode() const { return rmode_; } intptr_t data() const { return data_; } private: int position_; RelocInfo::Mode rmode_; intptr_t data_; }; class V8_EXPORT_PRIVATE Assembler : public AssemblerBase { public: // Create an assembler. Instructions and relocation information are emitted // into a buffer, with the instructions starting from the beginning and the // relocation information starting from the end of the buffer. See CodeDesc // for a detailed comment on the layout (globals.h). // // If the provided buffer is nullptr, the assembler allocates and grows its // own buffer, and buffer_size determines the initial buffer size. The buffer // is owned by the assembler and deallocated upon destruction of the // assembler. // // If the provided buffer is not nullptr, the assembler uses the provided // buffer for code generation and assumes its size to be buffer_size. If the // buffer is too small, a fatal error occurs. No deallocation of the buffer is // done upon destruction of the assembler. Assembler(const AssemblerOptions& options, void* buffer, int buffer_size); virtual ~Assembler() {} // GetCode emits any pending (non-emitted) code and fills the descriptor // desc. GetCode() is idempotent; it returns the same result if no other // Assembler functions are invoked in between GetCode() calls. void GetCode(Isolate* isolate, CodeDesc* desc); // Label operations & relative jumps (PPUM Appendix D) // // Takes a branch opcode (cc) and a label (L) and generates // either a backward branch or a forward branch and links it // to the label fixup chain. Usage: // // Label L; // unbound label // j(cc, &L); // forward branch to unbound label // bind(&L); // bind label to the current pc // j(cc, &L); // backward branch to bound label // bind(&L); // illegal: a label may be bound only once // // Note: The same Label can be used for forward and backward branches // but it may be bound only once. void bind(Label* L); // binds an unbound label L to the current code position // Links a label at the current pc_offset(). If already bound, returns the // bound position. If already linked, returns the position of the prior link. // Otherwise, returns the current pc_offset(). int link(Label* L); // Determines if Label is bound and near enough so that a single // branch instruction can be used to reach it. bool is_near(Label* L, Condition cond); // Returns the branch offset to the given label from the current code position // Links the label to the current position if it is still unbound int branch_offset(Label* L) { return link(L) - pc_offset(); } // Puts a labels target address at the given position. // The high 8 bits are set to zero. void label_at_put(Label* L, int at_offset); void load_label_offset(Register r1, Label* L); // Read/Modify the code target address in the branch/call instruction at pc. // The isolate argument is unused (and may be nullptr) when skipping flushing. V8_INLINE static Address target_address_at(Address pc, Address constant_pool); V8_INLINE static void set_target_address_at( Address pc, Address constant_pool, Address target, ICacheFlushMode icache_flush_mode = FLUSH_ICACHE_IF_NEEDED); // Return the code target address at a call site from the return address // of that call in the instruction stream. inline static Address target_address_from_return_address(Address pc); // Given the address of the beginning of a call, return the address // in the instruction stream that the call will return to. V8_INLINE static Address return_address_from_call_start(Address pc); inline Handle<Object> code_target_object_handle_at(Address pc); // This sets the branch destination. // This is for calls and branches within generated code. inline static void deserialization_set_special_target_at( Address instruction_payload, Code code, Address target); // Get the size of the special target encoded at 'instruction_payload'. inline static int deserialization_special_target_size( Address instruction_payload); // This sets the internal reference at the pc. inline static void deserialization_set_target_internal_reference_at( Address pc, Address target, RelocInfo::Mode mode = RelocInfo::INTERNAL_REFERENCE); // Here we are patching the address in the IIHF/IILF instruction pair. // These values are used in the serialization process and must be zero for // S390 platform, as Code, Embedded Object or External-reference pointers // are split across two consecutive instructions and don't exist separately // in the code, so the serializer should not step forwards in memory after // a target is resolved and written. static constexpr int kSpecialTargetSize = 0; // Number of bytes for instructions used to store pointer sized constant. #if V8_TARGET_ARCH_S390X static constexpr int kBytesForPtrConstant = 12; // IIHF + IILF #else static constexpr int kBytesForPtrConstant = 6; // IILF #endif // Distance between the instruction referring to the address of the call // target and the return address. // Offset between call target address and return address // for BRASL calls // Patch will be appiled to other FIXED_SEQUENCE call static constexpr int kCallTargetAddressOffset = 6; // --------------------------------------------------------------------------- // Code generation template <class T, int size, int lo, int hi> inline T getfield(T value) { DCHECK(lo < hi); DCHECK_GT(size, 0); int mask = hi - lo; int shift = size * 8 - hi; uint32_t mask_value = (mask == 32) ? 0xffffffff : (1 << mask) - 1; return (value & mask_value) << shift; } #define DECLARE_S390_RIL_AB_INSTRUCTIONS(name, op_name, op_value) \ template <class R1> \ inline void name(R1 r1, const Operand& i2) { \ ril_format(op_name, r1.code(), i2.immediate()); \ } #define DECLARE_S390_RIL_C_INSTRUCTIONS(name, op_name, op_value) \ inline void name(Condition m1, const Operand& i2) { \ ril_format(op_name, m1, i2.immediate()); \ } inline void ril_format(Opcode opcode, int f1, int f2) { uint32_t op1 = opcode >> 4; uint32_t op2 = opcode & 0xf; emit6bytes( getfield<uint64_t, 6, 0, 8>(op1) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(op2) | getfield<uint64_t, 6, 16, 48>(f2)); } S390_RIL_A_OPCODE_LIST(DECLARE_S390_RIL_AB_INSTRUCTIONS) S390_RIL_B_OPCODE_LIST(DECLARE_S390_RIL_AB_INSTRUCTIONS) S390_RIL_C_OPCODE_LIST(DECLARE_S390_RIL_C_INSTRUCTIONS) #undef DECLARE_S390_RIL_AB_INSTRUCTIONS #undef DECLARE_S390_RIL_C_INSTRUCTIONS #define DECLARE_S390_RR_INSTRUCTIONS(name, op_name, op_value) \ inline void name(Register r1, Register r2) { \ rr_format(op_name, r1.code(), r2.code()); \ } \ inline void name(DoubleRegister r1, DoubleRegister r2) { \ rr_format(op_name, r1.code(), r2.code()); \ } \ inline void name(Condition m1, Register r2) { \ rr_format(op_name, m1, r2.code()); \ } inline void rr_format(Opcode opcode, int f1, int f2) { emit2bytes(getfield<uint16_t, 2, 0, 8>(opcode) | getfield<uint16_t, 2, 8, 12>(f1) | getfield<uint16_t, 2, 12, 16>(f2)); } S390_RR_OPCODE_LIST(DECLARE_S390_RR_INSTRUCTIONS) #undef DECLARE_S390_RR_INSTRUCTIONS #define DECLARE_S390_RRD_INSTRUCTIONS(name, op_name, op_value) \ template <class R1, class R2, class R3> \ inline void name(R1 r1, R3 r3, R2 r2) { \ rrd_format(op_name, r1.code(), r3.code(), r2.code()); \ } inline void rrd_format(Opcode opcode, int f1, int f2, int f3) { emit4bytes(getfield<uint32_t, 4, 0, 16>(opcode) | getfield<uint32_t, 4, 16, 20>(f1) | getfield<uint32_t, 4, 24, 28>(f2) | getfield<uint32_t, 4, 28, 32>(f3)); } S390_RRD_OPCODE_LIST(DECLARE_S390_RRD_INSTRUCTIONS) #undef DECLARE_S390_RRD_INSTRUCTIONS #define DECLARE_S390_RRE_INSTRUCTIONS(name, op_name, op_value) \ template <class R1, class R2> \ inline void name(R1 r1, R2 r2) { \ rre_format(op_name, r1.code(), r2.code()); \ } inline void rre_format(Opcode opcode, int f1, int f2) { emit4bytes(getfield<uint32_t, 4, 0, 16>(opcode) | getfield<uint32_t, 4, 24, 28>(f1) | getfield<uint32_t, 4, 28, 32>(f2)); } S390_RRE_OPCODE_LIST(DECLARE_S390_RRE_INSTRUCTIONS) // Special format void lzdr(DoubleRegister r1) { rre_format(LZDR, r1.code(), 0); } #undef DECLARE_S390_RRE_INSTRUCTIONS #define DECLARE_S390_RX_INSTRUCTIONS(name, op_name, op_value) \ template <class R1> \ inline void name(R1 r1, Register x2, Register b2, const Operand& d2) { \ rx_format(op_name, r1.code(), x2.code(), b2.code(), \ d2.immediate()); \ } \ template <class R1> \ inline void name(R1 r1, const MemOperand& opnd) { \ name(r1, opnd.getIndexRegister(), opnd.getBaseRegister(), \ Operand(opnd.getDisplacement())); \ } inline void rx_format(Opcode opcode, int f1, int f2, int f3, int f4) { DCHECK(is_uint8(opcode)); DCHECK(is_uint12(f4)); emit4bytes(getfield<uint32_t, 4, 0, 8>(opcode) | getfield<uint32_t, 4, 8, 12>(f1) | getfield<uint32_t, 4, 12, 16>(f2) | getfield<uint32_t, 4, 16, 20>(f3) | getfield<uint32_t, 4, 20, 32>(f4)); } S390_RX_A_OPCODE_LIST(DECLARE_S390_RX_INSTRUCTIONS) void bc(Condition cond, const MemOperand& opnd) { bc(cond, opnd.getIndexRegister(), opnd.getBaseRegister(), Operand(opnd.getDisplacement())); } void bc(Condition cond, Register x2, Register b2, const Operand& d2) { rx_format(BC, cond, x2.code(), b2.code(), d2.immediate()); } #undef DECLARE_S390_RX_INSTRUCTIONS #define DECLARE_S390_RXY_INSTRUCTIONS(name, op_name, op_value) \ template <class R1, class R2> \ inline void name(R1 r1, R2 r2, Register b2, const Operand& d2) { \ rxy_format(op_name, r1.code(), r2.code(), b2.code(), d2.immediate()); \ } \ template <class R1> \ inline void name(R1 r1, const MemOperand& opnd) { \ name(r1, opnd.getIndexRegister(), opnd.getBaseRegister(), \ Operand(opnd.getDisplacement())); \ } inline void rxy_format(Opcode opcode, int f1, int f2, int f3, int f4) { DCHECK(is_uint16(opcode)); DCHECK(is_int20(f4)); emit6bytes(getfield<uint64_t, 6, 0, 8>(opcode >> 8) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 20>(f3) | getfield<uint64_t, 6, 20, 32>(f4 & 0x0fff) | getfield<uint64_t, 6, 32, 40>(f4 >> 12) | getfield<uint64_t, 6, 40, 48>(opcode & 0x00ff)); } S390_RXY_A_OPCODE_LIST(DECLARE_S390_RXY_INSTRUCTIONS) void pfd(Condition cond, const MemOperand& opnd) { pfd(cond, opnd.getIndexRegister(), opnd.getBaseRegister(), Operand(opnd.getDisplacement())); } void pfd(Condition cond, Register x2, Register b2, const Operand& d2) { rxy_format(PFD, cond, x2.code(), b2.code(), d2.immediate()); } #undef DECLARE_S390_RXY_INSTRUCTIONS inline void rsy_format(Opcode op, int f1, int f2, int f3, int f4) { DCHECK(is_int20(f4)); DCHECK(is_uint16(op)); uint64_t code = (getfield<uint64_t, 6, 0, 8>(op >> 8) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 20>(f3) | getfield<uint64_t, 6, 20, 32>(f4 & 0x0fff) | getfield<uint64_t, 6, 32, 40>(f4 >> 12) | getfield<uint64_t, 6, 40, 48>(op & 0xff)); emit6bytes(code); } #define DECLARE_S390_RSY_A_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register r3, Register b2, \ const Operand& d2 = Operand::Zero()) { \ rsy_format(op_name, r1.code(), r3.code(), b2.code(), d2.immediate()); \ } \ void name(Register r1, Register r3, Operand d2) { \ name(r1, r3, r0, d2); \ } \ void name(Register r1, Register r3, const MemOperand& opnd) { \ name(r1, r3, opnd.getBaseRegister(), Operand(opnd.getDisplacement())); \ } S390_RSY_A_OPCODE_LIST(DECLARE_S390_RSY_A_INSTRUCTIONS); #undef DECLARE_S390_RSY_A_INSTRUCTIONS #define DECLARE_S390_RSY_B_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Condition m3, Register b2, const Operand& d2) { \ rsy_format(op_name, r1.code(), m3, b2.code(), d2.immediate()); \ } \ void name(Register r1, Condition m3, const MemOperand& opnd) { \ name(r1, m3, opnd.getBaseRegister(), Operand(opnd.getDisplacement())); \ } S390_RSY_B_OPCODE_LIST(DECLARE_S390_RSY_B_INSTRUCTIONS); #undef DECLARE_S390_RSY_B_INSTRUCTIONS inline void rs_format(Opcode op, int f1, int f2, int f3, const int f4) { uint32_t code = getfield<uint32_t, 4, 0, 8>(op) | getfield<uint32_t, 4, 8, 12>(f1) | getfield<uint32_t, 4, 12, 16>(f2) | getfield<uint32_t, 4, 16, 20>(f3) | getfield<uint32_t, 4, 20, 32>(f4); emit4bytes(code); } #define DECLARE_S390_RS_A_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register r3, Register b2, const Operand& d2) { \ rs_format(op_name, r1.code(), r3.code(), b2.code(), d2.immediate()); \ } \ void name(Register r1, Register r3, const MemOperand& opnd) { \ name(r1, r3, opnd.getBaseRegister(), Operand(opnd.getDisplacement())); \ } S390_RS_A_OPCODE_LIST(DECLARE_S390_RS_A_INSTRUCTIONS); #undef DECLARE_S390_RS_A_INSTRUCTIONS #define DECLARE_S390_RS_B_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Condition m3, Register b2, const Operand& d2) { \ rs_format(op_name, r1.code(), m3, b2.code(), d2.immediate()); \ } \ void name(Register r1, Condition m3, const MemOperand& opnd) { \ name(r1, m3, opnd.getBaseRegister(), Operand(opnd.getDisplacement())); \ } S390_RS_B_OPCODE_LIST(DECLARE_S390_RS_B_INSTRUCTIONS); #undef DECLARE_S390_RS_B_INSTRUCTIONS #define DECLARE_S390_RS_SHIFT_FORMAT(name, opcode) \ void name(Register r1, Register r2, const Operand& opnd = \ Operand::Zero()) { \ DCHECK(r2 != r0); \ rs_format(opcode, r1.code(), r0.code(), r2.code(), opnd.immediate()); \ } \ void name(Register r1, const Operand& opnd) { \ rs_format(opcode, r1.code(), r0.code(), r0.code(), opnd.immediate()); \ } DECLARE_S390_RS_SHIFT_FORMAT(sll, SLL) DECLARE_S390_RS_SHIFT_FORMAT(srl, SRL) DECLARE_S390_RS_SHIFT_FORMAT(sla, SLA) DECLARE_S390_RS_SHIFT_FORMAT(sra, SRA) DECLARE_S390_RS_SHIFT_FORMAT(sldl, SLDL) DECLARE_S390_RS_SHIFT_FORMAT(srda, SRDA) DECLARE_S390_RS_SHIFT_FORMAT(srdl, SRDL) #undef DECLARE_S390_RS_SHIFT_FORMAT inline void rxe_format(Opcode op, int f1, int f2, int f3, int f4, int f5 = 0) { DCHECK(is_uint12(f4)); DCHECK(is_uint16(op)); uint64_t code = (getfield<uint64_t, 6, 0, 8>(op >> 8) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 20>(f3) | getfield<uint64_t, 6, 20, 32>(f4 & 0x0fff) | getfield<uint64_t, 6, 32, 36>(f5) | getfield<uint64_t, 6, 40, 48>(op & 0xff)); emit6bytes(code); } #define DECLARE_S390_RXE_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register x2, Register b2, const Operand& d2, \ Condition m3 = static_cast<Condition>(0)) { \ rxe_format(op_name, r1.code(), x2.code(), b2.code(), d2.immediate(), \ m3); \ } \ template<class _R1Type> \ void name(_R1Type r1, const MemOperand& opnd) { \ name(Register::from_code(r1.code()), opnd.rx(), opnd.rb(), \ Operand(opnd.offset())); \ } S390_RXE_OPCODE_LIST(DECLARE_S390_RXE_INSTRUCTIONS); #undef DECLARE_S390_RXE_INSTRUCTIONS inline void ri_format(Opcode opcode, int f1, int f2) { uint32_t op1 = opcode >> 4; uint32_t op2 = opcode & 0xf; emit4bytes(getfield<uint32_t, 4, 0, 8>(op1) | getfield<uint32_t, 4, 8, 12>(f1) | getfield<uint32_t, 4, 12, 16>(op2) | getfield<uint32_t, 4, 16, 32>(f2)); } #define DECLARE_S390_RI_A_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r, const Operand& i2) { \ DCHECK(is_uint12(op_name)); \ DCHECK(is_uint16(i2.immediate()) || is_int16(i2.immediate())); \ ri_format(op_name, r.code(), i2.immediate()); \ } S390_RI_A_OPCODE_LIST(DECLARE_S390_RI_A_INSTRUCTIONS); #undef DECLARE_S390_RI_A_INSTRUCTIONS #define DECLARE_S390_RI_B_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, const Operand& imm) { \ /* 2nd argument encodes # of halfwords, so divide by 2. */ \ int16_t numHalfwords = static_cast<int16_t>(imm.immediate()) / 2; \ Operand halfwordOp = Operand(numHalfwords); \ halfwordOp.setBits(16); \ ri_format(op_name, r1.code(), halfwordOp.immediate()); \ } S390_RI_B_OPCODE_LIST(DECLARE_S390_RI_B_INSTRUCTIONS); #undef DECLARE_S390_RI_B_INSTRUCTIONS #define DECLARE_S390_RI_C_INSTRUCTIONS(name, op_name, op_value) \ void name(Condition m, const Operand& i2) { \ DCHECK(is_uint12(op_name)); \ DCHECK(is_uint4(m)); \ DCHECK(op_name == BRC ? \ is_int16(i2.immediate()) : is_uint16(i2.immediate())); \ ri_format(op_name, m, i2.immediate()); \ } S390_RI_C_OPCODE_LIST(DECLARE_S390_RI_C_INSTRUCTIONS); #undef DECLARE_S390_RI_C_INSTRUCTIONS inline void rrf_format(Opcode op, int f1, int f2, int f3, int f4) { uint32_t code = getfield<uint32_t, 4, 0, 16>(op) | getfield<uint32_t, 4, 16, 20>(f1) | getfield<uint32_t, 4, 20, 24>(f2) | getfield<uint32_t, 4, 24, 28>(f3) | getfield<uint32_t, 4, 28, 32>(f4); emit4bytes(code); } #define DECLARE_S390_RRF_A_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Condition m4, Register r2, Register r3) { \ rrf_format(op_name, r3.code(), m4, r1.code(), r2.code()); \ } \ void name(Register r1, Register r2, Register r3) { \ name(r1, Condition(0), r2, r3); \ } S390_RRF_A_OPCODE_LIST(DECLARE_S390_RRF_A_INSTRUCTIONS); #undef DECLARE_S390_RRF_A_INSTRUCTIONS #define DECLARE_S390_RRF_B_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Condition m4, Register r2, Register r3) { \ rrf_format(op_name, r3.code(), m4, r1.code(), r2.code()); \ } \ void name(Register r1, Register r2, Register r3) { \ name(r1, Condition(0), r2, r3); \ } S390_RRF_B_OPCODE_LIST(DECLARE_S390_RRF_B_INSTRUCTIONS); #undef DECLARE_S390_RRF_B_INSTRUCTIONS #define DECLARE_S390_RRF_C_INSTRUCTIONS(name, op_name, op_value) \ template <class R1, class R2> \ void name(Condition m3, Condition m4, R1 r1, R2 r2) { \ rrf_format(op_name, m3, m4, r1.code(), r2.code()); \ } \ template <class R1, class R2> \ void name(Condition m3, R1 r1, R2 r2) { \ name(m3, Condition(0), r1, r2); \ } S390_RRF_C_OPCODE_LIST(DECLARE_S390_RRF_C_INSTRUCTIONS); #undef DECLARE_S390_RRF_C_INSTRUCTIONS #define DECLARE_S390_RRF_D_INSTRUCTIONS(name, op_name, op_value) \ template <class R1, class R2> \ void name(Condition m3, Condition m4, R1 r1, R2 r2) { \ rrf_format(op_name, m3, m4, r1.code(), r2.code()); \ } \ template <class R1, class R2> \ void name(Condition m3, R1 r1, R2 r2) { \ name(m3, Condition(0), r1, r2); \ } S390_RRF_D_OPCODE_LIST(DECLARE_S390_RRF_D_INSTRUCTIONS); #undef DECLARE_S390_RRF_D_INSTRUCTIONS #define DECLARE_S390_RRF_E_INSTRUCTIONS(name, op_name, op_value) \ template <class M3, class M4, class R1, class R2> \ void name(M3 m3, M4 m4, R1 r1, R2 r2) { \ rrf_format(op_name, m3, m4, r1.code(), r2.code()); \ } \ template <class M3, class R1, class R2> \ void name(M3 m3, R1 r1, R2 r2) { \ name(m3, Condition(0), r1, r2); \ } S390_RRF_E_OPCODE_LIST(DECLARE_S390_RRF_E_INSTRUCTIONS); #undef DECLARE_S390_RRF_E_INSTRUCTIONS enum FIDBRA_FLAGS { FIDBRA_CURRENT_ROUNDING_MODE = 0, FIDBRA_ROUND_TO_NEAREST_AWAY_FROM_0 = 1, // ... FIDBRA_ROUND_TOWARD_0 = 5, FIDBRA_ROUND_TOWARD_POS_INF = 6, FIDBRA_ROUND_TOWARD_NEG_INF = 7 }; inline void rsi_format(Opcode op, int f1, int f2, int f3) { DCHECK(is_uint8(op)); DCHECK(is_uint16(f3) || is_int16(f3)); uint32_t code = getfield<uint32_t, 4, 0, 8>(op) | getfield<uint32_t, 4, 8, 12>(f1) | getfield<uint32_t, 4, 12, 16>(f2) | getfield<uint32_t, 4, 16, 32>(f3); emit4bytes(code); } #define DECLARE_S390_RSI_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register r3, const Operand& i2) { \ rsi_format(op_name, r1.code(), r3.code(), i2.immediate()); \ } S390_RSI_OPCODE_LIST(DECLARE_S390_RSI_INSTRUCTIONS); #undef DECLARE_S390_RSI_INSTRUCTIONS inline void rsl_format(Opcode op, uint16_t f1, int f2, int f3, int f4, int f5) { DCHECK(is_uint16(op)); uint64_t code = getfield<uint64_t, 6, 0, 8>(op >> 8) | getfield<uint64_t, 6, 8, 16>(f1) | getfield<uint64_t, 6, 16, 20>(f2) | getfield<uint64_t, 6, 20, 32>(f3) | getfield<uint64_t, 6, 32, 36>(f4) | getfield<uint64_t, 6, 36, 40>(f5) | getfield<uint64_t, 6, 40, 48>(op & 0x00FF); emit6bytes(code); } #define DECLARE_S390_RSL_A_INSTRUCTIONS(name, op_name, op_value) \ void name(const Operand& l1, Register b1, const Operand& d1) { \ uint16_t L = static_cast<uint16_t>(l1.immediate() << 8); \ rsl_format(op_name, L, b1.code(), d1.immediate(), 0, 0); \ } S390_RSL_A_OPCODE_LIST(DECLARE_S390_RSL_A_INSTRUCTIONS); #undef DECLARE_S390_RSL_A_INSTRUCTIONS #define DECLARE_S390_RSL_B_INSTRUCTIONS(name, op_name, op_value) \ void name(const Operand& l2, Register b2, const Operand& d2, \ Register r1, Condition m3) { \ uint16_t L = static_cast<uint16_t>(l2.immediate()); \ rsl_format(op_name, L, b2.code(), d2.immediate(), r1.code(), m3); \ } S390_RSL_B_OPCODE_LIST(DECLARE_S390_RSL_B_INSTRUCTIONS); #undef DECLARE_S390_RSL_B_INSTRUCTIONS inline void s_format(Opcode op, int f1, int f2) { DCHECK_NE(op & 0xff00, 0); DCHECK(is_uint12(f2)); uint32_t code = getfield<uint32_t, 4, 0, 16>(op) | getfield<uint32_t, 4, 16, 20>(f1) | getfield<uint32_t, 4, 20, 32>(f2); emit4bytes(code); } #define DECLARE_S390_S_INSTRUCTIONS(name, op_name, op_value) \ void name(Register b1, const Operand& d2) { \ Opcode op = op_name; \ if ((op & 0xFF00) == 0) { \ op = (Opcode)(op << 8); \ } \ s_format(op, b1.code(), d2.immediate()); \ } \ void name(const MemOperand& opnd) { \ Operand d2 = Operand(opnd.getDisplacement()); \ name(opnd.getBaseRegister(), d2); \ } S390_S_OPCODE_LIST(DECLARE_S390_S_INSTRUCTIONS); #undef DECLARE_S390_S_INSTRUCTIONS inline void si_format(Opcode op, int f1, int f2, int f3) { uint32_t code = getfield<uint32_t, 4, 0, 8>(op) | getfield<uint32_t, 4, 8, 16>(f1) | getfield<uint32_t, 4, 16, 20>(f2) | getfield<uint32_t, 4, 20, 32>(f3); emit4bytes(code); } #define DECLARE_S390_SI_INSTRUCTIONS(name, op_name, op_value) \ void name(const Operand& i2, Register b1, const Operand& d1) { \ si_format(op_name, i2.immediate(), b1.code(), d1.immediate()); \ } \ void name(const MemOperand& opnd, const Operand& i2) { \ name(i2, opnd.getBaseRegister(), Operand(opnd.getDisplacement())); \ } S390_SI_OPCODE_LIST(DECLARE_S390_SI_INSTRUCTIONS); #undef DECLARE_S390_SI_INSTRUCTIONS inline void siy_format(Opcode op, int f1, int f2, int f3) { DCHECK(is_uint20(f3) || is_int20(f3)); DCHECK(is_uint16(op)); DCHECK(is_uint8(f1) || is_int8(f1)); uint64_t code = getfield<uint64_t, 6, 0, 8>(op >> 8) | getfield<uint64_t, 6, 8, 16>(f1) | getfield<uint64_t, 6, 16, 20>(f2) | getfield<uint64_t, 6, 20, 32>(f3) | getfield<uint64_t, 6, 32, 40>(f3 >> 12) | getfield<uint64_t, 6, 40, 48>(op & 0x00FF); emit6bytes(code); } #define DECLARE_S390_SIY_INSTRUCTIONS(name, op_name, op_value) \ void name(const Operand& i2, Register b1, const Operand& d1) { \ siy_format(op_name, i2.immediate(), b1.code(), d1.immediate()); \ } \ void name(const MemOperand& opnd, const Operand& i2) { \ name(i2, opnd.getBaseRegister(), Operand(opnd.getDisplacement())); \ } S390_SIY_OPCODE_LIST(DECLARE_S390_SIY_INSTRUCTIONS); #undef DECLARE_S390_SIY_INSTRUCTIONS inline void rrs_format(Opcode op, int f1, int f2, int f3, int f4, int f5) { DCHECK(is_uint12(f4)); DCHECK(is_uint16(op)); uint64_t code = getfield<uint64_t, 6, 0, 8>(op >> 8) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 20>(f3) | getfield<uint64_t, 6, 20, 32>(f4) | getfield<uint64_t, 6, 32, 36>(f5) | getfield<uint64_t, 6, 40, 48>(op & 0x00FF); emit6bytes(code); } #define DECLARE_S390_RRS_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register r2, Register b4, const Operand& d4, \ Condition m3) { \ rrs_format(op_name, r1.code(), r2.code(), b4.code(), d4.immediate(), \ m3); \ } \ void name(Register r1, Register r2, Condition m3, \ const MemOperand& opnd) { \ name(r1, r2, opnd.getBaseRegister(), \ Operand(opnd.getDisplacement()), m3); \ } S390_RRS_OPCODE_LIST(DECLARE_S390_RRS_INSTRUCTIONS); #undef DECLARE_S390_RRS_INSTRUCTIONS inline void ris_format(Opcode op, int f1, int f2, int f3, int f4, int f5) { DCHECK(is_uint12(f3)); DCHECK(is_uint16(op)); DCHECK(is_uint8(f5)); uint64_t code = getfield<uint64_t, 6, 0, 8>(op >> 8) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 20>(f3) | getfield<uint64_t, 6, 20, 32>(f4) | getfield<uint64_t, 6, 32, 40>(f5) | getfield<uint64_t, 6, 40, 48>(op & 0x00FF); emit6bytes(code); } #define DECLARE_S390_RIS_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Condition m3, Register b4, const Operand& d4, \ const Operand& i2) { \ ris_format(op_name, r1.code(), m3, b4.code(), d4.immediate(), \ i2.immediate()); \ } \ void name(Register r1, const Operand& i2, Condition m3, \ const MemOperand& opnd) { \ name(r1, m3, opnd.getBaseRegister(), \ Operand(opnd.getDisplacement()), i2); \ } S390_RIS_OPCODE_LIST(DECLARE_S390_RIS_INSTRUCTIONS); #undef DECLARE_S390_RIS_INSTRUCTIONS inline void sil_format(Opcode op, int f1, int f2, int f3) { DCHECK(is_uint12(f2)); DCHECK(is_uint16(op)); DCHECK(is_uint16(f3)); uint64_t code = getfield<uint64_t, 6, 0, 16>(op) | getfield<uint64_t, 6, 16, 20>(f1) | getfield<uint64_t, 6, 20, 32>(f2) | getfield<uint64_t, 6, 32, 48>(f3); emit6bytes(code); } #define DECLARE_S390_SIL_INSTRUCTIONS(name, op_name, op_value) \ void name(Register b1, const Operand& d1, const Operand& i2) { \ sil_format(op_name, b1.code(), d1.immediate(), i2.immediate()); \ } \ void name(const MemOperand& opnd, const Operand& i2) { \ name(opnd.getBaseRegister(), Operand(opnd.getDisplacement()), i2); \ } S390_SIL_OPCODE_LIST(DECLARE_S390_SIL_INSTRUCTIONS); #undef DECLARE_S390_SIL_INSTRUCTIONS inline void rie_d_format(Opcode opcode, int f1, int f2, int f3, int f4) { uint32_t op1 = opcode >> 8; uint32_t op2 = opcode & 0xff; uint64_t code = getfield<uint64_t, 6, 0, 8>(op1) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 32>(f3) | getfield<uint64_t, 6, 32, 40>(f4) | getfield<uint64_t, 6, 40, 48>(op2); emit6bytes(code); } #define DECLARE_S390_RIE_D_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register r3, const Operand& i2) { \ rie_d_format(op_name, r1.code(), r3.code(), i2.immediate(), 0); \ } S390_RIE_D_OPCODE_LIST(DECLARE_S390_RIE_D_INSTRUCTIONS) #undef DECLARE_S390_RIE_D_INSTRUCTIONS inline void rie_e_format(Opcode opcode, int f1, int f2, int f3) { uint32_t op1 = opcode >> 8; uint32_t op2 = opcode & 0xff; uint64_t code = getfield<uint64_t, 6, 0, 8>(op1) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 32>(f3) | getfield<uint64_t, 6, 40, 48>(op2); emit6bytes(code); } #define DECLARE_S390_RIE_E_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register r3, const Operand& i2) { \ rie_e_format(op_name, r1.code(), r3.code(), i2.immediate()); \ } S390_RIE_E_OPCODE_LIST(DECLARE_S390_RIE_E_INSTRUCTIONS) #undef DECLARE_S390_RIE_E_INSTRUCTIONS inline void rie_f_format(Opcode opcode, int f1, int f2, int f3, int f4, int f5) { uint32_t op1 = opcode >> 8; uint32_t op2 = opcode & 0xff; uint64_t code = getfield<uint64_t, 6, 0, 8>(op1) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 24>(f3) | getfield<uint64_t, 6, 24, 32>(f4) | getfield<uint64_t, 6, 32, 40>(f5) | getfield<uint64_t, 6, 40, 48>(op2); emit6bytes(code); } #define DECLARE_S390_RIE_F_INSTRUCTIONS(name, op_name, op_value) \ void name(Register dst, Register src, const Operand& startBit, \ const Operand& endBit, const Operand& shiftAmt) { \ DCHECK(is_uint8(startBit.immediate())); \ DCHECK(is_uint8(endBit.immediate())); \ DCHECK(is_uint8(shiftAmt.immediate())); \ rie_f_format(op_name, dst.code(), src.code(), startBit.immediate(), \ endBit.immediate(), shiftAmt.immediate()); \ } S390_RIE_F_OPCODE_LIST(DECLARE_S390_RIE_F_INSTRUCTIONS) #undef DECLARE_S390_RIE_F_INSTRUCTIONS inline void ss_a_format(Opcode op, int f1, int f2, int f3, int f4, int f5) { DCHECK(is_uint12(f5)); DCHECK(is_uint12(f3)); DCHECK(is_uint8(f1)); DCHECK(is_uint8(op)); uint64_t code = getfield<uint64_t, 6, 0, 8>(op) | getfield<uint64_t, 6, 8, 16>(f1) | getfield<uint64_t, 6, 16, 20>(f2) | getfield<uint64_t, 6, 20, 32>(f3) | getfield<uint64_t, 6, 32, 36>(f4) | getfield<uint64_t, 6, 36, 48>(f5); emit6bytes(code); } #define DECLARE_S390_SS_A_INSTRUCTIONS(name, op_name, op_value) \ void name(Register b1, const Operand& d1, Register b2, \ const Operand& d2, const Operand& length) { \ ss_a_format(op_name, length.immediate(), b1.code(), d1.immediate(), \ b2.code(), d2.immediate()); \ } \ void name(const MemOperand& opnd1, const MemOperand& opnd2, \ const Operand& length) { \ ss_a_format(op_name, length.immediate(), \ opnd1.getBaseRegister().code(), \ opnd1.getDisplacement(), opnd2.getBaseRegister().code(), \ opnd2.getDisplacement()); \ } S390_SS_A_OPCODE_LIST(DECLARE_S390_SS_A_INSTRUCTIONS) #undef DECLARE_S390_SS_A_INSTRUCTIONS // Helper for unconditional branch to Label with update to save register void b(Register r, Label* l) { int32_t halfwords = branch_offset(l) / 2; brasl(r, Operand(halfwords)); } // Conditional Branch Instruction - Generates either BRC / BRCL void branchOnCond(Condition c, int branch_offset, bool is_bound = false); // Helpers for conditional branch to Label void b(Condition cond, Label* l, Label::Distance dist = Label::kFar) { branchOnCond(cond, branch_offset(l), l->is_bound() || (dist == Label::kNear)); } void bc_short(Condition cond, Label* l, Label::Distance dist = Label::kFar) { b(cond, l, Label::kNear); } // Helpers for conditional branch to Label void beq(Label* l, Label::Distance dist = Label::kFar) { b(eq, l, dist); } void bne(Label* l, Label::Distance dist = Label::kFar) { b(ne, l, dist); } void blt(Label* l, Label::Distance dist = Label::kFar) { b(lt, l, dist); } void ble(Label* l, Label::Distance dist = Label::kFar) { b(le, l, dist); } void bgt(Label* l, Label::Distance dist = Label::kFar) { b(gt, l, dist); } void bge(Label* l, Label::Distance dist = Label::kFar) { b(ge, l, dist); } void b(Label* l, Label::Distance dist = Label::kFar) { b(al, l, dist); } void jmp(Label* l, Label::Distance dist = Label::kFar) { b(al, l, dist); } void bunordered(Label* l, Label::Distance dist = Label::kFar) { b(unordered, l, dist); } void bordered(Label* l, Label::Distance dist = Label::kFar) { b(ordered, l, dist); } // Helpers for conditional indirect branch off register void b(Condition cond, Register r) { bcr(cond, r); } void beq(Register r) { b(eq, r); } void bne(Register r) { b(ne, r); } void blt(Register r) { b(lt, r); } void ble(Register r) { b(le, r); } void bgt(Register r) { b(gt, r); } void bge(Register r) { b(ge, r); } void b(Register r) { b(al, r); } void jmp(Register r) { b(al, r); } void bunordered(Register r) { b(unordered, r); } void bordered(Register r) { b(ordered, r); } // wrappers around asm instr void brxh(Register dst, Register inc, Label* L) { int offset_halfwords = branch_offset(L) / 2; CHECK(is_int16(offset_halfwords)); brxh(dst, inc, Operand(offset_halfwords)); } void brxhg(Register dst, Register inc, Label* L) { int offset_halfwords = branch_offset(L) / 2; CHECK(is_int16(offset_halfwords)); brxhg(dst, inc, Operand(offset_halfwords)); } template <class R1, class R2> void ledbr(R1 r1, R2 r2) { ledbra(Condition(0), Condition(0), r1, r2); } template <class R1, class R2> void cdfbr(R1 r1, R2 r2) { cdfbra(Condition(0), Condition(0), r1, r2); } template <class R1, class R2> void cdgbr(R1 r1, R2 r2) { cdgbra(Condition(0), Condition(0), r1, r2); } template <class R1, class R2> void cegbr(R1 r1, R2 r2) { cegbra(Condition(0), Condition(0), r1, r2); } template <class R1, class R2> void cgebr(Condition m3, R1 r1, R2 r2) { cgebra(m3, Condition(0), r1, r2); } template <class R1, class R2> void cgdbr(Condition m3, R1 r1, R2 r2) { cgdbra(m3, Condition(0), r1, r2); } template <class R1, class R2> void cfdbr(Condition m3, R1 r1, R2 r2) { cfdbra(m3, Condition(0), r1, r2); } template <class R1, class R2> void cfebr(Condition m3, R1 r1, R2 r2) { cfebra(m3, Condition(0), r1, r2); } // --------------------------------------------------------------------------- // Code generation // Insert the smallest number of nop instructions // possible to align the pc offset to a multiple // of m. m must be a power of 2 (>= 4). void Align(int m); // Insert the smallest number of zero bytes possible to align the pc offset // to a mulitple of m. m must be a power of 2 (>= 2). void DataAlign(int m); // Aligns code to something that's optimal for a jump target for the platform. void CodeTargetAlign(); void breakpoint(bool do_print) { if (do_print) { PrintF("DebugBreak is inserted to %p\n", static_cast<void*>(pc_)); } #if V8_HOST_ARCH_64_BIT int64_t value = reinterpret_cast<uint64_t>(&v8::base::OS::DebugBreak); int32_t hi_32 = static_cast<int64_t>(value) >> 32; int32_t lo_32 = static_cast<int32_t>(value); iihf(r1, Operand(hi_32)); iilf(r1, Operand(lo_32)); #else iilf(r1, Operand(reinterpret_cast<uint32_t>(&v8::base::OS::DebugBreak))); #endif basr(r14, r1); } void call(Handle<Code> target, RelocInfo::Mode rmode); void jump(Handle<Code> target, RelocInfo::Mode rmode, Condition cond); // S390 instruction generation #define DECLARE_VRR_A_INSTRUCTIONS(name, opcode_name, opcode_value) \ void name(DoubleRegister v1, DoubleRegister v2, Condition m5, Condition m4, \ Condition m3) { \ uint64_t code = (static_cast<uint64_t>(opcode_value & 0xFF00)) * B32 | \ (static_cast<uint64_t>(v1.code())) * B36 | \ (static_cast<uint64_t>(v2.code())) * B32 | \ (static_cast<uint64_t>(m5 & 0xF)) * B20 | \ (static_cast<uint64_t>(m4 & 0xF)) * B16 | \ (static_cast<uint64_t>(m3 & 0xF)) * B12 | \ (static_cast<uint64_t>(opcode_value & 0x00FF)); \ emit6bytes(code); \ } S390_VRR_A_OPCODE_LIST(DECLARE_VRR_A_INSTRUCTIONS) #undef DECLARE_VRR_A_INSTRUCTIONS #define DECLARE_VRR_C_INSTRUCTIONS(name, opcode_name, opcode_value) \ void name(DoubleRegister v1, DoubleRegister v2, DoubleRegister v3, \ Condition m6, Condition m5, Condition m4) { \ uint64_t code = (static_cast<uint64_t>(opcode_value & 0xFF00)) * B32 | \ (static_cast<uint64_t>(v1.code())) * B36 | \ (static_cast<uint64_t>(v2.code())) * B32 | \ (static_cast<uint64_t>(v3.code())) * B28 | \ (static_cast<uint64_t>(m6 & 0xF)) * B20 | \ (static_cast<uint64_t>(m5 & 0xF)) * B16 | \ (static_cast<uint64_t>(m4 & 0xF)) * B12 | \ (static_cast<uint64_t>(opcode_value & 0x00FF)); \ emit6bytes(code); \ } S390_VRR_C_OPCODE_LIST(DECLARE_VRR_C_INSTRUCTIONS) #undef DECLARE_VRR_C_INSTRUCTIONS // Single Element format void vfa(DoubleRegister v1, DoubleRegister v2, DoubleRegister v3) { vfa(v1, v2, v3, static_cast<Condition>(0), static_cast<Condition>(8), static_cast<Condition>(3)); } void vfs(DoubleRegister v1, DoubleRegister v2, DoubleRegister v3) { vfs(v1, v2, v3, static_cast<Condition>(0), static_cast<Condition>(8), static_cast<Condition>(3)); } void vfm(DoubleRegister v1, DoubleRegister v2, DoubleRegister v3) { vfm(v1, v2, v3, static_cast<Condition>(0), static_cast<Condition>(8), static_cast<Condition>(3)); } void vfd(DoubleRegister v1, DoubleRegister v2, DoubleRegister v3) { vfd(v1, v2, v3, static_cast<Condition>(0), static_cast<Condition>(8), static_cast<Condition>(3)); } // Load Address Instructions void larl(Register r, Label* l); // Exception-generating instructions and debugging support void stop(const char* msg, Condition cond = al, int32_t code = kDefaultStopCode, CRegister cr = cr7); void bkpt(uint32_t imm16); // v5 and above // Different nop operations are used by the code generator to detect certain // states of the generated code. enum NopMarkerTypes { NON_MARKING_NOP = 0, GROUP_ENDING_NOP, DEBUG_BREAK_NOP, // IC markers. PROPERTY_ACCESS_INLINED, PROPERTY_ACCESS_INLINED_CONTEXT, PROPERTY_ACCESS_INLINED_CONTEXT_DONT_DELETE, // Helper values. LAST_CODE_MARKER, FIRST_IC_MARKER = PROPERTY_ACCESS_INLINED }; void nop(int type = 0); // 0 is the default non-marking type. void dumy(int r1, int x2, int b2, int d2); // Check the code size generated from label to here. int SizeOfCodeGeneratedSince(Label* label) { return pc_offset() - label->pos(); } // Record a deoptimization reason that can be used by a log or cpu profiler. // Use --trace-deopt to enable. void RecordDeoptReason(DeoptimizeReason reason, SourcePosition position, int id); // Writes a single byte or word of data in the code stream. Used // for inline tables, e.g., jump-tables. void db(uint8_t data); void dd(uint32_t data); void dq(uint64_t data); void dp(uintptr_t data); // Read/patch instructions SixByteInstr instr_at(int pos) { return Instruction::InstructionBits(buffer_ + pos); } template <typename T> void instr_at_put(int pos, T instr) { Instruction::SetInstructionBits<T>(buffer_ + pos, instr); } // Decodes instruction at pos, and returns its length int32_t instr_length_at(int pos) { return Instruction::InstructionLength(buffer_ + pos); } static SixByteInstr instr_at(byte* pc) { return Instruction::InstructionBits(pc); } static Condition GetCondition(Instr instr); static bool IsBranch(Instr instr); #if V8_TARGET_ARCH_S390X static bool Is64BitLoadIntoIP(SixByteInstr instr1, SixByteInstr instr2); #else static bool Is32BitLoadIntoIP(SixByteInstr instr); #endif static bool IsCmpRegister(Instr instr); static bool IsCmpImmediate(Instr instr); static bool IsNop(SixByteInstr instr, int type = NON_MARKING_NOP); // The code currently calls CheckBuffer() too often. This has the side // effect of randomly growing the buffer in the middle of multi-instruction // sequences. // // This function allows outside callers to check and grow the buffer void EnsureSpaceFor(int space_needed); void EmitRelocations(); void emit_label_addr(Label* label); public: byte* buffer_pos() const { return buffer_; } protected: int buffer_space() const { return reloc_info_writer.pos() - pc_; } // Decode instruction(s) at pos and return backchain to previous // label reference or kEndOfChain. int target_at(int pos); // Patch instruction(s) at pos to target target_pos (e.g. branch) void target_at_put(int pos, int target_pos, bool* is_branch = nullptr); // Record reloc info for current pc_ void RecordRelocInfo(RelocInfo::Mode rmode, intptr_t data = 0); private: // Avoid overflows for displacements etc. static const int kMaximalBufferSize = 512 * MB; // Code generation // The relocation writer's position is at least kGap bytes below the end of // the generated instructions. This is so that multi-instruction sequences do // not have to check for overflow. The same is true for writes of large // relocation info entries. static constexpr int kGap = 32; // Relocation info generation // Each relocation is encoded as a variable size value static constexpr int kMaxRelocSize = RelocInfoWriter::kMaxSize; RelocInfoWriter reloc_info_writer; std::vector<DeferredRelocInfo> relocations_; // The bound position, before this we cannot do instruction elimination. int last_bound_pos_; // Code emission void CheckBuffer() { if (buffer_space() <= kGap) { GrowBuffer(); } } void GrowBuffer(int needed = 0); inline void TrackBranch(); inline void UntrackBranch(); // Helper to emit the binary encoding of a 2 byte instruction void emit2bytes(uint16_t x) { CheckBuffer(); #if V8_TARGET_LITTLE_ENDIAN // We need to emit instructions in big endian format as disassembler / // simulator require the first byte of the instruction in order to decode // the instruction length. Swap the bytes. x = ((x & 0x00FF) << 8) | ((x & 0xFF00) >> 8); #endif *reinterpret_cast<uint16_t*>(pc_) = x; pc_ += 2; } // Helper to emit the binary encoding of a 4 byte instruction void emit4bytes(uint32_t x) { CheckBuffer(); #if V8_TARGET_LITTLE_ENDIAN // We need to emit instructions in big endian format as disassembler / // simulator require the first byte of the instruction in order to decode // the instruction length. Swap the bytes. x = ((x & 0x000000FF) << 24) | ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8) | ((x & 0xFF000000) >> 24); #endif *reinterpret_cast<uint32_t*>(pc_) = x; pc_ += 4; } // Helper to emit the binary encoding of a 6 byte instruction void emit6bytes(uint64_t x) { CheckBuffer(); #if V8_TARGET_LITTLE_ENDIAN // We need to emit instructions in big endian format as disassembler / // simulator require the first byte of the instruction in order to decode // the instruction length. Swap the bytes. x = (static_cast<uint64_t>(x & 0xFF) << 40) | (static_cast<uint64_t>((x >> 8) & 0xFF) << 32) | (static_cast<uint64_t>((x >> 16) & 0xFF) << 24) | (static_cast<uint64_t>((x >> 24) & 0xFF) << 16) | (static_cast<uint64_t>((x >> 32) & 0xFF) << 8) | (static_cast<uint64_t>((x >> 40) & 0xFF)); x |= (*reinterpret_cast<uint64_t*>(pc_) >> 48) << 48; #else // We need to pad two bytes of zeros in order to get the 6-bytes // stored from low address. x = x << 16; x |= *reinterpret_cast<uint64_t*>(pc_) & 0xFFFF; #endif // It is safe to store 8-bytes, as CheckBuffer() guarantees we have kGap // space left over. *reinterpret_cast<uint64_t*>(pc_) = x; pc_ += 6; } // Labels void print(Label* L); int max_reach_from(int pos); void bind_to(Label* L, int pos); void next(Label* L); void AllocateAndInstallRequestedHeapObjects(Isolate* isolate); int WriteCodeComments(); friend class RegExpMacroAssemblerS390; friend class RelocInfo; friend class EnsureSpace; }; class EnsureSpace { public: explicit EnsureSpace(Assembler* assembler) { assembler->CheckBuffer(); } }; } // namespace internal } // namespace v8 #endif // V8_S390_ASSEMBLER_S390_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
ae46a06e17c1a9187514d036bfc4bac1e9491e79
2f10f807d3307b83293a521da600c02623cdda82
/deps/boost/win/debug/include/boost/mpl/set/aux_/include_preprocessed.hpp
e7e455895e5e9a9d32b208739377283b0ab8051f
[]
no_license
xpierrohk/dpt-rp1-cpp
2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e
643d053983fce3e6b099e2d3c9ab8387d0ea5a75
refs/heads/master
2021-05-23T08:19:48.823198
2019-07-26T17:35:28
2019-07-26T17:35:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:d014fe3aeb77d984dbcdb21c769c2d8c9c4f8ffc3265b98dac482537fda280f9 size 1189
[ "YLiLarry@gmail.com" ]
YLiLarry@gmail.com
1155eb6019593a66d25280bca0f01b0eafb59f5c
5b6708afab2d064a3040a715e200057a90f47317
/src_lowlatency/components/store/kvstore_test.cc
22f6f3fe5f0be7f6ea88aa70778151419d41f030
[]
no_license
ldanilek/CalvinHDFS
0f032bd4b5d8e13431cfe6402f6826525932fe1d
22059285419519a92c4e6d6c7945ca3824440a3b
refs/heads/master
2020-12-02T11:30:16.998527
2017-05-25T20:42:18
2017-05-25T20:42:18
96,644,617
0
0
null
null
null
null
UTF-8
C++
false
false
2,397
cc
// Author: Alexander Thomson <thomson@cs.yale.edu> // // TODO(agt): Move to btreestore_test.cc // TODO(agt): Test Actions. #include "components/store/kvstore.h" #include "components/store/btreestore.h" #include "components/store/leveldbstore.h" #include <gflags/gflags.h> #include <gtest/gtest.h> #include <glog/logging.h> #include <map> #include <string> #include "common/utils.h" using std::map; template<class KVStoreType> void TestInsertDelete() { KVStoreType s; string result; EXPECT_FALSE(s.Exists("a")); EXPECT_FALSE(s.Get("a", &result)); s.Put("a", "alpha"); EXPECT_TRUE(s.Exists("a")); EXPECT_TRUE(s.Get("a", &result)); EXPECT_EQ("alpha", result); s.Put("b", "bravo"); EXPECT_TRUE(s.Exists("a")); EXPECT_TRUE(s.Get("a", &result)); EXPECT_EQ("alpha", result); EXPECT_TRUE(s.Exists("b")); EXPECT_TRUE(s.Get("b", &result)); EXPECT_EQ("bravo", result); s.Delete("a"); EXPECT_FALSE(s.Exists("a")); EXPECT_FALSE(s.Get("a", &result)); EXPECT_TRUE(s.Exists("b")); EXPECT_TRUE(s.Get("b", &result)); EXPECT_EQ("bravo", result); } TEST(BTreeStoreTest, EmptyIterator) { BTreeStore s; KVStore::Iterator* i = s.GetIterator(); EXPECT_FALSE(i->Valid()); i->Next(); EXPECT_FALSE(i->Valid()); delete i; // TODO(agt): ASSERT_DEATH tests on bad i->Key() and i->Value() calls. } template<class KVStoreType> void TestIterator() { BTreeStore s; map<string, string> m; for (int i = 0; i < 1000; i++) { string k = RandomString(3 + rand() % 7); string v = RandomString(100); s.Put(k, v); m[k] = v; } KVStore::Iterator* i = s.GetIterator(); EXPECT_FALSE(i->Valid()); i->Next(); for (auto j = m.begin(); j != m.end(); ++j) { EXPECT_TRUE(i->Valid()); EXPECT_EQ(j->first, i->Key()); EXPECT_EQ(j->second, i->Value()); i->Next(); } EXPECT_FALSE(i->Valid()); delete i; // TODO(agt): Also test thread safety. } TEST(BTreeStoreTest, InsertDelete) { TestInsertDelete<BTreeStore>(); } TEST(BTreeStoreTest, Iterator) { TestIterator<BTreeStore>(); } TEST(LevelDBStoreTest, InsertDelete) { TestInsertDelete<LevelDBStore>(); } TEST(LevelDBStoreTest, Iterator) { TestIterator<LevelDBStore>(); } int main(int argc, char **argv) { google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "kun.ren@yale.edu" ]
kun.ren@yale.edu
7602f0262c2e8af1dc6e5fbd4beedc47f54ee83c
21b99ea7396881e8a56f41b53e5672e689c805a7
/omnetpp-5.2.1/include/omnetpp/cscheduler.h
1f700bb08652b6ea3085a20f84dbaed9ecfc6a63
[]
no_license
mohammedalasmar/omnetpp-data-transport-model-ndp
7bf8863091345c0c7ce5b5e80052dc739baa8700
cbede62fc2b375e8e0012421a4d60f70f1866d69
refs/heads/master
2023-06-27T06:17:57.433908
2020-10-09T11:30:02
2020-10-09T11:30:02
194,747,934
2
2
null
2021-08-02T17:03:56
2019-07-01T21:54:32
HTML
UTF-8
C++
false
false
7,692
h
//========================================================================= // CSCHEDULER.H - part of // OMNeT++/OMNEST // Discrete System Simulation in C++ // //========================================================================= /*--------------------------------------------------------------* Copyright (C) 2003-2017 Andras Varga Copyright (C) 2006-2017 OpenSim Ltd. This file is distributed WITHOUT ANY WARRANTY. See the file `license' for details on this and other legal matters. *--------------------------------------------------------------*/ #ifndef __OMNETPP_CSCHEDULER_H #define __OMNETPP_CSCHEDULER_H #include "platdep/timeutil.h" // for timeval #include "cobject.h" #include "clifecyclelistener.h" namespace omnetpp { class cEvent; class cSimulation; /** * @brief Abstract class to encapsulate event scheduling. * * The central method is takeNextEvent(). * * To switch to your own scheduler class (reasons you'd like to do that * include real-time simulation, hardware-in-the-loop simulation, * distributed (federated) simulation, parallel distributed simulation), * subclass cScheduler, register your new class with * the Register_Class() macro, then add the following to * <tt>omnetpp.ini</tt>: * * <pre> * [General] * scheduler-class = "MyClass" * </pre> * * @ingroup SimSupport * @ingroup ExtensionPoints */ class SIM_API cScheduler : public cObject, public cISimulationLifecycleListener { protected: cSimulation *sim; protected: /** * A cISimulationLifecycleListener method. Delegates to startRun(), endRun() and * executionResumed(); override if needed. */ virtual void lifecycleEvent(SimulationLifecycleEventType eventType, cObject *details) override; public: /** * Constructor. */ cScheduler(); /** * Destructor. */ virtual ~cScheduler(); /** * Return a short description. This string will be displayed in the Qtenv * and Tkenv GUIs as scheduler information. Returning an empty string means * "default scheduler", and is reserved for cSequentialScheduler. */ virtual std::string str() const override; /** * Pass cSimulation object to scheduler. */ virtual void setSimulation(cSimulation *_sim); /** * Returns the simulation the scheduler belongs to. */ cSimulation *getSimulation() const {return sim;} /** * Called at the beginning of a simulation run. */ virtual void startRun() {} /** * Called at the end of a simulation run. */ virtual void endRun() {} /** * Called every time the user hits the Run button in Tkenv. * Real-time schedulers (e.g. cRealTimeScheduler) may make use of * this callback to pin current simulation time to current * wall clock time. */ virtual void executionResumed() {} /** * Return the likely next event in the simulation. This method is for UI * purposes, it does not play any role in the simulation. A basic * implementation would just return a pointer to the first event in the FES, * which is accurate for sequential simulation; with parallel, distributed or * real-time simulation there might be other events coming from other processes * with a yet smaller timestamp. * * This method should not have side effects, except for discarding stale events * from the FES. */ virtual cEvent *guessNextEvent() = 0; /** * Return the next event to be processed. Normally (with sequential execution), * it just returns the first event in the FES. With parallel and/or real-time * simulation, it is also the scheduler's task to synchronize with real time * and/or with other partitions. * * If there's no more event, it throws cTerminationException. * * A nullptr return value means that there's no error but execution * was stopped by the user (e.g. with STOP button on the GUI) * while takeNextEvent() was waiting for external synchronization. */ virtual cEvent *takeNextEvent() = 0; /** * Undo for takeNextEvent(), approximately: if an event was obtained from * takeNextEvent() but was not yet processed, it is possible to temporarily * put it back to the FES. * * The scheduler class must guarantee that removing the event via * takeNextEvent() again does NOT repeat the side effects of the * first takeNextEvent()! That is, the sequence * * <pre> * e = takeNextEvent(); * putBackEvent(e); * e = takeNextEvent(); * </pre> * * should be equivalent to a single takeNextEvent() call. */ virtual void putBackEvent(cEvent *event) = 0; }; /** * @brief Event scheduler for sequential simulation. * * @ingroup SimSupport */ class SIM_API cSequentialScheduler : public cScheduler { public: /** * Constructor. */ cSequentialScheduler() {} /** * Returns empty string as description. */ virtual std::string str() const override; /** * Returns the first event in the Future Event Set. */ virtual cEvent *guessNextEvent() override; /** * Removes the first event from the Future Event Set, and returns it. */ virtual cEvent *takeNextEvent() override; /** * Puts back the event into the Future Event Set. */ virtual void putBackEvent(cEvent *event) override; }; /** * @brief Real-time scheduler class. * * When installed as scheduler using the scheduler-class omnetpp.ini entry, * it will synchronize simulation execution to real (wall clock) time. * * Operation: a "base time" is determined when startRun() is called. Later on, * the scheduler object calls usleep() from takeNextEvent() to synchronize the * simulation time to real time, that is, to wait until * the current time minus base time becomes equal to the simulation time. * Should the simulation lag behind real time, this scheduler will try to catch up * by omitting sleep calls altogether. * * Scaling is supported via the realtimescheduler-scaling omnetpp.ini entry. * For example, if it is set to 2.0, the simulation will try to execute twice * as fast as real time. * * @ingroup SimSupport */ //TODO soft realtime, hard realtime (that is: tries to catch up, or resynchronizes on each event) class SIM_API cRealTimeScheduler : public cScheduler { protected: // configuration: bool doScaling; double factor; // state: timeval baseTime; protected: virtual void startRun() override; bool waitUntil(const timeval& targetTime); public: /** * Constructor. */ cRealTimeScheduler(); /** * Destructor. */ virtual ~cRealTimeScheduler(); /** * Returns a description that depends on the parametrization of this class. */ virtual std::string str() const override; /** * Recalculates "base time" from current wall clock time. */ virtual void executionResumed() override; /** * Returns the first event in the Future Event Set. */ virtual cEvent *guessNextEvent() override; /** * Scheduler function -- it comes from cScheduler interface. * This function synchronizes to real time: before returning the * first event from the FES, it waits (using usleep()) until * the real time reaches the time of that simulation event. */ virtual cEvent *takeNextEvent() override; /** * Puts back the event into the Future Event Set. */ virtual void putBackEvent(cEvent *event) override; }; } // namespace omnetpp #endif
[ "mohammedzsalasmar@gmail.com" ]
mohammedzsalasmar@gmail.com
224e33f06ee86e3c2566ca1191cf2820190c4e62
39a14ada3b83a1c873fb9eab216ce136fe63acb2
/TETRIS_VS_Server/TETRIS_VS_Server/RoomManager.h
2433545cbad58e1fb548263379c27d581776c6ea
[]
no_license
shield1203/TETRIS_VS_Server
d725c58da040278fee512d0d1832bea904691e5b
02821837db4bfdffb2debdd644cbf4f606a4f249
refs/heads/master
2021-01-02T02:27:36.255157
2020-03-05T17:45:04
2020-03-05T17:45:04
239,449,317
0
0
null
null
null
null
UTF-8
C++
false
false
522
h
#pragma once class GameUser; class PacketManager; enum ROOM_MANAGER { FULL_USER_COUNT = 2 }; struct GameRoom { int roomNum = 0; list<PacketManager*>gameUserList; }; class RoomManager { private: static RoomManager* Inst; RoomManager(); public: list<GameRoom*>m_roomList; public: static RoomManager* getInstance(); void CreateGameRoom(PacketManager*); bool EnterRoom(int, PacketManager*); void ExitRoom(int); void CheckRoom(GameRoom*); void GameStartRoom(int); void SetGameResult(int); ~RoomManager(); };
[ "57628185+shield1203@users.noreply.github.com" ]
57628185+shield1203@users.noreply.github.com
7bc63bd72caca2f993780a10e12a197cee0663fd
f538e176b90909c0907cca87525567d596731b0c
/multiServer/client.cc
6433b1999dbc602675d7a94f1c85cb06d91d1862
[]
no_license
GzhuFlyer/Unix_demo
d9655117300ad614c9077b1679ced278b4c3ecf8
f684773913bbe176a3e1a7d0bce41ab3b15f10b3
refs/heads/master
2023-02-01T11:40:43.200894
2020-12-21T16:55:55
2020-12-21T16:55:55
317,797,840
0
0
null
null
null
null
UTF-8
C++
false
false
1,108
cc
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <unistd.h> #define ERR_EXIT(M) \ do \ { \ perror(M); \ exit(EXIT_FAILURE); \ }while(0) int main(void) { int sock; if((sock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) < 0) ERR_EXIT("socket"); struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(5188); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // servaddr.sin_addr.s_addr = inet_addr("47.112.152.139"); if(connect(sock,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) ERR_EXIT("connect"); // printf("error connect\n"); char sendbuf[1024] = {0}; char recvbuf[1024] = {0}; while(fgets(sendbuf,sizeof(sendbuf),stdin) != NULL) { write(sock,sendbuf,strlen(sendbuf)); read(sock,recvbuf,sizeof(recvbuf)); fputs(recvbuf,stdout); } close(sock); return 0; }
[ "gzhuflyer@foxmail.com" ]
gzhuflyer@foxmail.com
064aa3ba8f940a41b6dfd3385812727306567a2c
c11460ee58386012ef30fa4089c43d715e231a4c
/lib/tsan/rtl/relacy/schedulers/tsan_fixed_window_scheduler.h
015b7917888a8ef25d86d2388bd4a8f391639866
[ "NCSA", "MIT" ]
permissive
dorooleg/compiler-rt
5589396b2c74e5e5d7ec82ce9809d2d5f2cb63df
13ea846316c3986099c6a536f1973d75838ad675
refs/heads/schedulers
2022-01-25T14:17:39.004550
2019-07-08T19:37:14
2019-07-08T19:37:14
128,505,427
0
0
NOASSERTION
2019-07-08T19:37:56
2018-04-07T07:13:42
C
UTF-8
C++
false
false
858
h
#ifndef TSAN_FIXED_WINDOW_SCHEDULER_H #define TSAN_FIXED_WINDOW_SCHEDULER_H #include "rtl/relacy/tsan_scheduler.h" #include "rtl/relacy/tsan_shared_vector.h" #include "rtl/relacy/tsan_threads_box.h" namespace __tsan { namespace __relacy { class FixedWindowScheduler : public Scheduler { public: FixedWindowScheduler(ThreadsBox& threads_box, int window_size); ThreadContext* Yield() override; void Start() override; void Finish() override; bool IsEnd() override; void Initialize() override; SchedulerType GetType() override; private: ThreadsBox& threads_box_; SharedVector<int> window_paths_; SharedVector<int> window_border_; uptr offset_; SharedValue<uptr> depth_; SharedValue<int> invalidate_pos_; int window_size_; bool is_end_; uptr iteration_; }; } } #endif //TSAN_FIXED_WINDOW_SCHEDULER_H
[ "dorooleg@yandex.ru" ]
dorooleg@yandex.ru
9a3de840c4dbae563c3192d145700ff9cbffb07a
f8542f61530d7b8028e5a920c0b9a19036ba21c5
/Euler_336/Euler_336.cpp
4c02b77dd1b3161f8ab44ffcf5f0ed6da1311997
[]
no_license
datahaven/Project-Euler
f73bcdbd4d15818754d4d6648fa89a6d9b4fb1b5
74fc175fc6c9f18ae9a84585d563212f16ec6958
refs/heads/master
2020-04-21T09:55:25.767633
2019-07-13T21:55:27
2019-07-13T21:55:27
4,118,662
1
0
null
null
null
null
UTF-8
C++
false
false
2,137
cpp
// Project Euler 336 // Adrian Dale // 23/05/2011 // // Answer: CAGBIHEFJDK // // My code cheats a little in that I ran a first pass to find out what the maximum // maximix number is, then I run again counting solutions up to that number. // Not clever or especially efficient, but runs in a couple of seconds. // Not convinced that mixcount is bugfree for all inputs but it works for this puzzle. // Solution relies on next_permutation being able to run through 11! permutations // (ie 39 million) and check each one very easily on a modern computer. Took a few mins // to write code to check that this wouldn't take too long with a bit of string // manipulation for each value and after that it seemed sensible to proceed with this // approach. // Also helpful that next_permutation produces permutations in lexicographical order #include <iostream> #include <algorithm> #include <string> using namespace std; // NB pass by value as code messes with s int mixcount(string s) { string a = "ABCDEFGHIJK"; int mcnt = 0; for( int i=0; i<a.length()-2; ++i ) { // No flipping needed if coach is already in the right place if (a[i] == s[i]) continue; // Find next coach we need string::size_type mpos = s.find(a[i]); // and if it isn't at end of list ... if ( mpos != s.length()-1 ) { reverse( s.begin()+mpos, s.end() ); ++mcnt; reverse(s.begin()+i, s.end()); ++mcnt; } else { // next coach is at end of list reverse( s.begin(), s.end() ); ++mcnt; } } // Last two coaches need swapping if ( a[a.length()-2] != s[a.length()-2] ) { ++mcnt; // Don't need to actually swap the chars, but did it // like this so I could display string whilst testing // reverse(s.begin()+a.length()-2, s.end()); } return mcnt; } int main() { string s = "ABCDEFGHIJK"; int maxmc = 0; int pcnt = 0; do { int mc = mixcount(s); maxmc = max(maxmc, mc); if ( mc == 19 ) // value calculated in previous run { ++pcnt; if ( pcnt == 2011 ) break; } } while (next_permutation( s.begin(), s.end() ) ); cout << "maxmc=" << maxmc << endl; cout << s << endl; return 0; }
[ "adrian@adriandale.com" ]
adrian@adriandale.com
5dd2849e3bc77c03135eb50c025edc182ba92279
40295e5de2f76e184cbf3385d432f003ef45d611
/ChartShow_new/moc_chartshow.cpp
b8bba5ea2e06e5ae702efe91d411dd183ca34d78
[]
no_license
alive2202/pukh_chart_lnx
1e67409b066dc71b633547dbd47e5de2a5b85127
992d5102f3c4674642275a4db8ac6738d67ccf6e
refs/heads/master
2020-11-27T10:13:03.433931
2019-12-21T08:42:21
2019-12-21T08:42:21
229,398,114
0
0
null
null
null
null
UTF-8
C++
false
false
5,191
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'chartshow.h' ** ** Created: Wed Jan 9 16:23:39 2019 ** by: The Qt Meta Object Compiler version 63 (Qt 4.8.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "chartshow.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'chartshow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_ChartShow[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 19, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 11, 10, 10, 10, 0x0a, 26, 10, 10, 10, 0x0a, 45, 10, 10, 10, 0x0a, 64, 10, 10, 10, 0x0a, 90, 10, 10, 10, 0x0a, 117, 10, 10, 10, 0x0a, 143, 10, 10, 10, 0x0a, 164, 10, 10, 10, 0x0a, 194, 10, 10, 10, 0x0a, 218, 10, 10, 10, 0x0a, 247, 10, 10, 10, 0x0a, 274, 10, 10, 10, 0x0a, 300, 10, 10, 10, 0x0a, 325, 10, 10, 10, 0x0a, 356, 10, 10, 10, 0x0a, 390, 10, 10, 10, 0x0a, 426, 10, 10, 10, 0x0a, 458, 10, 10, 10, 0x0a, 492, 10, 10, 10, 0x0a, 0 // eod }; static const char qt_meta_stringdata_ChartShow[] = { "ChartShow\0\0makeRandData()\0chbTData_clicked()\0" "btnClose_clicked()\0PushButtonStart_clicked()\0" "PushButtonOffAll_clicked()\0" "PushButtonOnAll_clicked()\0" "CheckBoxLK_clicked()\0PushButtonIshRazmDN_clicked()\0" "CheckBoxRegKK_clicked()\0" "PushButtonStartOsc_clicked()\0" "PushButtonAccept_clicked()\0" "PushButtonNoise_clicked()\0" "PushButtonSigs_clicked()\0" "PushButtonIshRazmOsc_clicked()\0" "ComboBoxPoints_activated(QString)\0" "SpinBoxCanals_valueChanged(QString)\0" "LineEditUp_textChanged(QString)\0" "LineEditDown_textChanged(QString)\0" "LineEditData_textChanged(QString)\0" }; void ChartShow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); ChartShow *_t = static_cast<ChartShow *>(_o); switch (_id) { case 0: _t->makeRandData(); break; case 1: _t->chbTData_clicked(); break; case 2: _t->btnClose_clicked(); break; case 3: _t->PushButtonStart_clicked(); break; case 4: _t->PushButtonOffAll_clicked(); break; case 5: _t->PushButtonOnAll_clicked(); break; case 6: _t->CheckBoxLK_clicked(); break; case 7: _t->PushButtonIshRazmDN_clicked(); break; case 8: _t->CheckBoxRegKK_clicked(); break; case 9: _t->PushButtonStartOsc_clicked(); break; case 10: _t->PushButtonAccept_clicked(); break; case 11: _t->PushButtonNoise_clicked(); break; case 12: _t->PushButtonSigs_clicked(); break; case 13: _t->PushButtonIshRazmOsc_clicked(); break; case 14: _t->ComboBoxPoints_activated((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 15: _t->SpinBoxCanals_valueChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 16: _t->LineEditUp_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 17: _t->LineEditDown_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 18: _t->LineEditData_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; default: ; } } } const QMetaObjectExtraData ChartShow::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject ChartShow::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_ChartShow, qt_meta_data_ChartShow, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &ChartShow::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *ChartShow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *ChartShow::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_ChartShow)) return static_cast<void*>(const_cast< ChartShow*>(this)); return QWidget::qt_metacast(_clname); } int ChartShow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 19) qt_static_metacall(this, _c, _id, _a); _id -= 19; } return _id; } QT_END_MOC_NAMESPACE
[ "pukhalexander@gmail.com" ]
pukhalexander@gmail.com
1032316f973bc8db22e17c2dca2bf131a635c36d
18e4ea8a882ffd5add41ce001522d60e0ce556e8
/hw6-1/simple_shape_main.cc
121270ed5780549c64c164c17d217d016e37c1f0
[]
no_license
2018008613/CreativeSoftwareProgramming
b36c5f7d992c7b4b5d55dab632c15380191a0605
fddee907bd08772fca0bd9da868474859c671505
refs/heads/master
2022-04-21T09:04:48.937091
2020-04-15T12:43:09
2020-04-15T12:43:09
255,913,012
0
0
null
null
null
null
UTF-8
C++
false
false
492
cc
#include <iostream> #include <string> #include "simple_shape.h" using namespace std; int main() { while (1) { string a; Circle c; Rectangle t; cout << "shape?" << endl; cin >> a; if (a == "C") { c.cgets(); cout << "area: " << c.CircleArea() << ", perimeter: " << c.CirclePerimeter() << endl; } if (a == "R") { t.rgets(); cout << "area: " << t.RectangleArea() << ", perimeter: " << t.RectanglePerimeter() << endl; } if (a == "Q") { break; } } }
[ "picosw@hanyang.ac.kr" ]
picosw@hanyang.ac.kr
7f6a11197bac3e7b61a0a73dbdebf7aa4706137e
ec259beef8c61f42d2e9eb8e851cacd36cf5e391
/FinalProjectArchive/code/UserSettings.h
8d87d59359e1ee50d21f7b2c9835ec7feb9bf71f
[]
no_license
AlexanderJHill/Software-Engineering
4b19844b01f8b9213d6d884a808667d8ed9b2009
63ac151d57b60a752e9307cbc5a129861c1c2ff6
refs/heads/master
2021-01-01T16:45:27.099696
2015-05-09T20:41:26
2015-05-09T20:41:26
31,767,606
0
0
null
2015-04-27T14:59:25
2015-03-06T12:06:11
C++
UTF-8
C++
false
false
1,226
h
#ifndef _USERSETTINGS_H_ #define _USERSETTINGS_H_ //! \file usersettings.h //! \brief contains the users global simulation parameters. //! \brief contains the users global simulation parameters. class UserSettings{ public: UserSettings(); int getfisherNum(); /*!< Returns the number of Fishers to use in the simulation*/ int getfishLoc(); /*!< Returns the number of different locations */ int getfishType(); /*!< Returns the number of fish types.*/ int getfishPop(); /*!< Returns the inital population of fish when the simulation starts. */ int getfishTemp(); /*!< Returns the conditions: overcast, snow, rain. */ int getRuntime(); /*!< Returns the number of days to run the simulation. */ protected: int fisherNum; /*!< The number of Fishers to use in the simulation*/ int fishLoc; /*!< The number of different locations */ int fishType; /*!< The number of fish types. */ int fishPop; /*!< The inital population of fish when the simulation starts. */ int fishTemp; /*!< The conditions: overcast, snow, rain */ int runtime; /*!< The number of days to run the simulation */ }; #endif
[ "ahill6984@gmail.com" ]
ahill6984@gmail.com
28d1c00d0258837e3801155a33077549f1beff26
50b10c0019c0e1a641024c2f1cb1713f57294a4a
/series2_handout/hyp_sys_1d/src/ancse/runge_kutta.cpp
7411835c5db4185a51395321f04ef70d5109ee33
[ "MIT" ]
permissive
BeatHubmann/19H-AdvNCSE
37e2a65f3d2fb90a1685cfb64b1816943d608223
3979f768da933de82bd6ab29bbf31ea9fc31e501
refs/heads/master
2020-07-29T11:10:09.216346
2019-12-08T22:49:42
2019-12-08T22:49:42
209,775,272
1
1
null
null
null
null
UTF-8
C++
false
false
2,020
cpp
#include <ancse/runge_kutta.hpp> #include <ancse/includes.hpp> #include <ancse/config.hpp> #include <fmt/format.h> #define REGISTER_FVM_RUNGE_KUTTA(token, RKType) \ if (rk_key == token) { \ return std::make_shared<RKType>( \ rate_of_change, boundary_condition, nullptr, n_vars, n_cells); \ } /// make Runge Kutta for FVM std::shared_ptr<RungeKutta> make_runge_kutta(const nlohmann::json &config, const std::shared_ptr<RateOfChange> &rate_of_change, const std::shared_ptr<BoundaryCondition> &boundary_condition, int n_vars, int n_cells) { std::string rk_key = config["time_integrator"]; REGISTER_FVM_RUNGE_KUTTA("forward_euler", ForwardEuler) // Register your SSP2 class. throw std::runtime_error( fmt::format("Unknown time-integrator. [{}]", rk_key)); } #undef REGISTER_FVM_RUNGE_KUTTA #define REGISTER_DG_RUNGE_KUTTA(token, RKType) \ if (rk_key == token) { \ return std::make_shared<RKType>( \ rate_of_change, boundary_condition, dg_limiting, n_vars, n_cells); \ } /// make Runge Kutta for DG std::shared_ptr<RungeKutta> make_runge_kutta(const nlohmann::json &config, const std::shared_ptr<RateOfChange> &rate_of_change, const std::shared_ptr<BoundaryCondition> &boundary_condition, const std::shared_ptr<Limiting> &dg_limiting, int n_vars, int n_cells) { std::string rk_key = config["time_integrator"]; REGISTER_DG_RUNGE_KUTTA("forward_euler", ForwardEuler) // Register your SSP2 class. throw std::runtime_error( fmt::format("Unknown time-integrator. [{}]", rk_key)); } #undef REGISTER_DG_RUNGE_KUTTA
[ "BeatHubmann@users.noreply.github.com" ]
BeatHubmann@users.noreply.github.com
412a88248a3dbc80ac3a655c4df69467f01d4d69
1d11ed2f1fdba2fd9472f6d762d8ab2369bd0fc8
/Spaghetti/Spaghetti/src/Spaghetti/CCollision.h
ede2d93210813cfc98e0cdf00227dce11acae08c
[]
no_license
SamOatesUniversity/Year-3---Physics---Spaghetti
339c8c9e72c04ecdcba17e5e76176608c21aeb12
0785a2cfcc87048b04f95fca5f81d108cf5c57d8
refs/heads/master
2021-03-12T20:36:06.364559
2013-06-06T09:21:30
2013-06-06T09:21:30
41,171,737
0
0
null
null
null
null
UTF-8
C++
false
false
257
h
#pragma once #include <Ogre/Ogre.h> class CSpaghettiRigidBody; class CCollision { public: CSpaghettiRigidBody *bodyOne; CSpaghettiRigidBody *bodyTwo; Ogre::Vector3 collisionPoint; Ogre::Vector3 collisionNormal; float penetration; };
[ "sam@samoatesgames.com" ]
sam@samoatesgames.com
6f10decb3fb7fdccc21a5afb410c1c402a63c10d
6e98a5d1588baaff7870316210c8033631fd7d3c
/programs/create_genesis/genesis_mapper.hpp
9b3c9794827c2152b9738bb0f26d11c3027d170b
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
scorum/scorum
f2ca45a678e46638d1bd0ebe868bed0431a53492
f660e3f8ead05f90e412f4d83f92e34ada13a61b
refs/heads/develop
2022-08-16T19:09:03.918951
2022-06-09T08:45:52
2022-06-09T10:04:56
106,838,543
57
30
NOASSERTION
2023-08-31T15:33:27
2017-10-13T15:01:17
C++
UTF-8
C++
false
false
1,292
hpp
#pragma once #include <map> #include <string> #include <scorum/chain/genesis/genesis_state.hpp> #include <fc/static_variant.hpp> namespace scorum { namespace util { using scorum::chain::genesis_state_type; using account_type = genesis_state_type::account_type; using steemit_bounty_account_type = genesis_state_type::steemit_bounty_account_type; using scorum::protocol::asset; using scorum::protocol::public_key_type; using genesis_account_info_item_type = fc::static_variant<account_type, steemit_bounty_account_type>; class genesis_mapper { public: genesis_mapper(); void reset(const genesis_state_type&); void update(const genesis_account_info_item_type&); void update(const std::string& name, const public_key_type&, const asset& scr_amount, const asset& sp_amount); void save(genesis_state_type&); private: void calculate_and_set_supply_rest(genesis_state_type& genesis); using genesis_account_info_item_map_by_type = std::map<int, genesis_account_info_item_type>; using genesis_account_info_items_type = std::map<std::string, genesis_account_info_item_map_by_type>; genesis_account_info_items_type _uniq_items; asset _accounts_supply = asset(0, SCORUM_SYMBOL); asset _steemit_bounty_accounts_supply = asset(0, SP_SYMBOL); }; } }
[ "andrew.masilevich@scorum.com" ]
andrew.masilevich@scorum.com
31bf6e308cd11ffef511d6c96f843a8e29ec01d5
2fd0fae47b85ce8661edaf2ea4fab2377a69eaf8
/OOPaufgabenblatt2a6.cpp
ddee6c5bc0d645caa2c245270a29197f10748cd1
[]
no_license
Seakuh/OOP
1277bb32a7bb5db09a2e6992ac27fa63efc9e6b0
aa9fe6e88b92126223a4b0c713bbf34d883e93ea
refs/heads/master
2020-12-13T04:06:35.957386
2020-01-16T11:49:19
2020-01-16T11:49:19
234,308,392
0
0
null
null
null
null
UTF-8
C++
false
false
794
cpp
#include <iostream> #include "letzteaufg copy.h" int main() { double k = 50; double j = 0.5; Arraylist<double> neu = Arraylist<double>(k); Arraylist<double> vergleich = Arraylist<double>(7); Arraylist<double> zuweisen = Arraylist<double>(7); Arraylist<double> zuweisen1 = Arraylist<double>(7); Arraylist<float> zuweisen3 = Arraylist<float>(7); //Zuweisungsoperator Test try { for (int i = 0; i < 7; i++) { zuweisen.set(i, i); } } catch (const char *e) { std::cout << e << std::endl; }; std::cout << zuweisen1 << std::endl; zuweisen1 = zuweisen; std::cout << "Zuweisen Test" << std::endl; std::cout << zuweisen << std::endl; std::cout << zuweisen1 << std::endl; }
[ "eteranimal@protonmail.com" ]
eteranimal@protonmail.com
cc92a8aab28153ad880885f9b8bd35adb2e2eff2
c47b47e5768549da37b768ea270abe62db43a390
/Lab6/avltree.h
84b45115ae1c6a22fa51fbcdb7888c262e32cb0a
[]
no_license
tiennm99/CTDL-GT
69ec46eb74618e08acb5e92aa222360b073974c5
9da63ab2407446f8334aff7ed8c75cafe80c6c96
refs/heads/master
2021-10-10T13:53:50.056119
2019-01-11T13:27:28
2019-01-11T13:27:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,175
h
#ifndef AVLTREE_H #define AVLTREE_H #include <stack> #include "avlnode.h" template <class T> class AVLTree { private: AVLNode<T> *root = nullptr; AVLNode<T> *rotateLeft(AVLNode<T> *node); AVLNode<T> *rotateRight(AVLNode<T> *node); int getHeight(AVLNode<T> *node); void rebalance(AVLNode<T> *node); public: AVLTree(); ~AVLTree(); bool insert(AVLNode<T> *newNode); AVLNode<T> *search(T searchData); bool remove(const T removeData); void printAsList(); void printNLR(); template <class U> friend ostream &operator << (ostream &os, AVLTree<U> *tree); }; template <class T> AVLTree<T>::AVLTree() { this->root = nullptr; } template <class T> AVLTree<T>::~AVLTree() { delete this->root; this->root = nullptr; } template <class T> void AVLTree<T>::rebalance(AVLNode<T> *node) { if (node == nullptr) return; node->update(); if (node->balance > 1) { if (node->left->balance < -1) node->left = rotateLeft(node->left); node = rotateRight(node); } else if (node->balance < -1) { if (node->right->balance > 1) node->right = rotateRight(node->right); node = rotateLeft(node); } if (node->parent == nullptr) this->root = node; else rebalance(node->parent); } template <class T> AVLNode<T> *AVLTree<T>::rotateLeft(AVLNode<T> *node) { AVLNode<T> *temp = node->right; AVLNode<T> *tmp = temp->left; AVLNode<T> *parent = node->parent; temp->parent = parent; node->right = tmp; if (tmp != nullptr) { tmp->parent = node; } temp->left = node; node->parent = temp; if (parent != nullptr) { if (parent->left == node) parent->left = temp; else parent->right = temp; } node->update(); temp->update(); return temp; } template <class T> AVLNode<T> *AVLTree<T>::rotateRight(AVLNode<T> *node) { AVLNode<T> *temp = node->left; AVLNode<T> *tmp = temp->right; AVLNode<T> *parent = node->parent; temp->parent = parent; node->left = tmp; if (tmp != nullptr) { tmp->parent = node; } temp->right = node; node->parent = temp; if (parent != nullptr) { if (parent->left == node) parent->left = temp; else parent->right = temp; } node->update(); temp->update(); return temp; } template <class T> int AVLTree<T>::getHeight(AVLNode<T> *node) { if (node == nullptr) return 0; return node->height; } template <class T> bool AVLTree<T>::insert(AVLNode<T> *newNode) { if (newNode == nullptr) return false; if (this->root == nullptr) { this->root = newNode; return true; } AVLNode<T> *temp = this->root; AVLNode<T> *parent; while (true) { if (temp->data == newNode->data) return false; parent = temp; bool goLeft = (newNode->data < temp->data); temp = goLeft ? temp->left : temp->right; if (temp == nullptr) { if (goLeft) { parent->left = newNode; newNode->parent = parent; } else { parent->right = newNode; newNode->parent = parent; } rebalance(parent); return true; } } } template <class T> bool AVLTree<T>::remove(const T removeData) { AVLNode<T> *temp = this->root; while (temp != nullptr) { if (removeData < temp->data) temp = temp->left; else if (removeData > temp->data) temp = temp->right; else break; } if (temp == nullptr) return false; AVLNode<T> *del = temp; if (temp->left != nullptr) { del = temp->left; while (del->right != nullptr) del = del->right; } AVLNode<T> *parent = nullptr; if (del == this->root) { this->root = this->root->right; if (this->root != nullptr) this->root->parent = nullptr; } else if (del != temp) { temp->data = del->data; parent = del->parent; if (parent->left == del) parent->left = del->left; else parent->right = del->left; if (del->left != nullptr) del->left->parent = parent; } else { parent = del->parent; if (parent->left == del) parent->left = del->right; else parent->right = del->right; if (del->right != nullptr) del->right->parent = parent; } if (parent != nullptr) this->rebalance(parent); return true; } template <class T> void AVLTree<T>::printNLR() { stack<AVLNode<T> *> sAVLNode; stack<int> sNodeLevel; sAVLNode.push(this->root); sNodeLevel.push(0); while (!sAVLNode.empty()) { AVLNode<T> *tNode = sAVLNode.top(); sAVLNode.pop(); int tLevel = sNodeLevel.top(); sNodeLevel.pop(); for (int i = 0; i < tLevel; ++i) { cout << " "; } if (tNode == nullptr) { cout << "NULL" << endl; continue; } cout << tNode->data << "(" << tNode->balance << ")" << endl; sAVLNode.push(tNode->right); sNodeLevel.push(tLevel + 1); sAVLNode.push(tNode->left); sNodeLevel.push(tLevel + 1); } } template <class T> AVLNode<T> *AVLTree<T>::search(T searchData) { AVLNode<T> *temp = this->root; while (temp != nullptr) { if (searchData < temp->data) temp = temp->left; else if (searchData > temp->data) temp = temp->right; else return temp; } return nullptr; } template <class T> void printLNR(AVLNode<T> *subroot) { if (subroot == nullptr) return; printLNR(subroot->left); cout << subroot->data << endl; printLNR(subroot->right); } template <class T> void AVLTree<T>::printAsList() { printLNR(this->root); } template <class T> ostream &operator << (ostream &os, AVLTree<T> *tree) { os << tree->root; return os; } #endif // AVLTREE_H
[ "minhtienit99@gmail.com" ]
minhtienit99@gmail.com
6e2313369c2d56080acba8d41e9e6be1e31a9e5b
ae51b683aae1549b6af8143b538199bceb57a1e6
/Intermediate/Build/Win64/UE4Editor/Inc/ResidentEvil/BTTaskMoveToPlayer.generated.h
42200b0c5cb30d316fe1e2288709820886728f52
[]
no_license
kvtuyen0315/Unreal-Resident-Evil
2b2a6f346702b705d0fd26b693fc0f7b8f6047fa
42707bbd9d928b03619c84b3982b2e20acc3df02
refs/heads/master
2021-10-26T10:30:27.581789
2019-04-12T00:04:00
2019-04-12T00:04:00
177,728,663
0
0
null
null
null
null
UTF-8
C++
false
false
4,892
h
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "ObjectMacros.h" #include "ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef RESIDENTEVIL_BTTaskMoveToPlayer_generated_h #error "BTTaskMoveToPlayer.generated.h already included, missing '#pragma once' in BTTaskMoveToPlayer.h" #endif #define RESIDENTEVIL_BTTaskMoveToPlayer_generated_h #define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_RPC_WRAPPERS #define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_RPC_WRAPPERS_NO_PURE_DECLS #define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUBTTaskMoveToPlayer(); \ friend RESIDENTEVIL_API class UClass* Z_Construct_UClass_UBTTaskMoveToPlayer(); \ public: \ DECLARE_CLASS(UBTTaskMoveToPlayer, UBTTask_BlackboardBase, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/ResidentEvil"), NO_API) \ DECLARE_SERIALIZER(UBTTaskMoveToPlayer) \ enum {IsIntrinsic=COMPILED_IN_INTRINSIC}; #define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_INCLASS \ private: \ static void StaticRegisterNativesUBTTaskMoveToPlayer(); \ friend RESIDENTEVIL_API class UClass* Z_Construct_UClass_UBTTaskMoveToPlayer(); \ public: \ DECLARE_CLASS(UBTTaskMoveToPlayer, UBTTask_BlackboardBase, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/ResidentEvil"), NO_API) \ DECLARE_SERIALIZER(UBTTaskMoveToPlayer) \ enum {IsIntrinsic=COMPILED_IN_INTRINSIC}; #define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UBTTaskMoveToPlayer(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UBTTaskMoveToPlayer) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UBTTaskMoveToPlayer); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UBTTaskMoveToPlayer); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UBTTaskMoveToPlayer(UBTTaskMoveToPlayer&&); \ NO_API UBTTaskMoveToPlayer(const UBTTaskMoveToPlayer&); \ public: #define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_ENHANCED_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UBTTaskMoveToPlayer(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UBTTaskMoveToPlayer(UBTTaskMoveToPlayer&&); \ NO_API UBTTaskMoveToPlayer(const UBTTaskMoveToPlayer&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UBTTaskMoveToPlayer); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UBTTaskMoveToPlayer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UBTTaskMoveToPlayer) #define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_PRIVATE_PROPERTY_OFFSET #define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_13_PROLOG #define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_PRIVATE_PROPERTY_OFFSET \ Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_RPC_WRAPPERS \ Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_INCLASS \ Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_PRIVATE_PROPERTY_OFFSET \ Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_RPC_WRAPPERS_NO_PURE_DECLS \ Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_INCLASS_NO_PURE_DECLS \ Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
[ "kvtuyen0315@gmail.com" ]
kvtuyen0315@gmail.com
0705f9f98dee1239960481b1586f85783e301c54
0b68534e02bbcce3b93be85e2b8974a6b224f0cc
/chtho/net/http/HTTPContext.cpp
75a4da904dd26a809aae83e5382ceaca830d496f
[ "MIT" ]
permissive
WineChord/chtho
f2b9ffe1b05faf4276d03cf7864dd3987e71ef38
f43c56a1c2faf83e5f48361ca1b06366ce061aab
refs/heads/main
2023-04-10T18:50:38.818174
2021-04-25T17:21:22
2021-04-25T17:21:22
340,803,506
0
0
null
null
null
null
UTF-8
C++
false
false
2,264
cpp
// Copyright (c) 2021 Qizhou Guo // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #include "HTTPContext.h" #include "net/Buffer.h" namespace chtho { namespace net { /* request structure GET /hello.txt HTTP/1.1 User-Agent: curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3 Host: www.example.com Accept-Language: en, mi */ bool HTTPContext::parse(Buffer* buf, Timestamp rcvTime) { bool ok = true, more = true; while(more) { if(state_ == ExpReq) { const char* crlf = buf->findCRLF(); if(crlf) { ok = procReq(buf->peek(), crlf); if(ok) { request_.setRcvTime(rcvTime); buf->retrieveUntil(crlf+2); state_ = ExpHeader; } else more = false; } else more = false; } else if(state_ == ExpHeader) // retrieve headers { const char* crlf = buf->findCRLF(); if(crlf) { const char* colon = std::find(buf->peek(), crlf, ':'); if(colon != crlf) request_.addHeader(buf->peek(), colon, crlf); else // no more headers { state_ = Done; more = false; } buf->retrieveUntil(crlf+2); } else more = false; } } return ok; } /* request line, something like GET /hello HTTP/1.1 */ bool HTTPContext::procReq(const char* begin, const char* end) { const char* space = std::find(begin, end, ' '); if(space == end) return false; if(!request_.setMethod(begin, space)) return false; begin = space + 1; // move to something like '/hello' space = std::find(begin, end, ' '); if(space == end) return false; const char* question = std::find(begin, space, '?'); if(question != space) { request_.setPath(begin, question); request_.setQuery(question, space); } else { request_.setPath(begin, space); } begin = space + 1; // should be either 'HTTP/1.0' or 'HTTP/1.1' if(end - begin != 8) return false; if(!std::equal(begin, end-1, "HTTP/1.")) return false; if(*(end-1) == '1') request_.setVersion(HTTPRequest::HTTP11); else if(*(end-1) == '0') request_.setVersion(HTTPRequest::HTTP10); else return false; return true; } } // namespace net } // namespace chtho
[ "guoqizhou123123@qq.com" ]
guoqizhou123123@qq.com
4b8b9a1d08b8e250ce3e81db85c2d097dfa65e4a
2d34422361367d6fb28167c713f689ee7084d5c0
/libraries/reducedElasticForceModel/reducedLinearStVKForceModel.cpp
5b4f42a0a69fca70c6cc5b70dddd20aa643f3a9a
[]
no_license
kengwit/VegaFEM-v3.0
5c307de1f2a2f57c2cc7d111c1da989fe07202f4
6eb4822f8d301d502d449d28bcfb5b9dbb916f08
refs/heads/master
2021-12-10T15:03:14.828219
2016-08-24T12:04:03
2016-08-24T12:04:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,311
cpp
/************************************************************************* * * * Vega FEM Simulation Library Version 3.0 * * * * "elasticForceModel" library , Copyright (C) 2007 CMU, 2009 MIT, * * 2016 USC * * All rights reserved. * * * * Code author: Jernej Barbic * * http://www.jernejbarbic.com/code * * * * Research: Jernej Barbic, Fun Shing Sin, Daniel Schroeder, * * Doug L. James, Jovan Popovic * * * * Funding: National Science Foundation, Link Foundation, * * Singapore-MIT GAMBIT Game Lab, * * Zumberge Research and Innovation Fund at USC * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the BSD-style license that is * * included with this library in the file LICENSE.txt * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * * LICENSE.TXT for more details. * * * *************************************************************************/ #include "matrixMacros.h" #include "reducedLinearStVKForceModel.h" ReducedLinearStVKForceModel::ReducedLinearStVKForceModel(StVKReducedStiffnessMatrix * stVKReducedStiffnessMatrix) { r = stVKReducedStiffnessMatrix->Getr(); K = (double*) malloc (sizeof(double) * r * r); double * zero = (double*) calloc (r, sizeof(double)); stVKReducedStiffnessMatrix->Evaluate(zero,K); free(zero); } ReducedLinearStVKForceModel::ReducedLinearStVKForceModel(int r, double * K) { this->r = r; this->K = (double*) malloc (sizeof(double) * r * r); memcpy(this->K, K, sizeof(double) * r * r); } void ReducedLinearStVKForceModel::GetInternalForce(double * q, double * internalForces) { // internalForces = K * q memset(internalForces, 0, sizeof(double) * r); for(int i=0; i<r; i++) for(int j=0; j<r; j++) internalForces[i] += K[ELT(r,i,j)] * q[j]; } void ReducedLinearStVKForceModel::GetTangentStiffnessMatrix(double * q, double * tangentStiffnessMatrix) { memcpy(tangentStiffnessMatrix, K, sizeof(double) * r * r); } void ReducedLinearStVKForceModel::GetTangentHessianTensor(double * q, double * tangentHessianTensor) { memset(tangentHessianTensor, 0, sizeof(double) * r * r*(r+1)/2); }
[ "jslee02@gmail.com" ]
jslee02@gmail.com
402b2e38e96968c2be87195a55c5914872561c93
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/bma/src/v20210624/model/CreateCRDesktopCodeRequest.cpp
6ede5969fa5358c0a2abd3fd237f1cfbc00122de
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
2,582
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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. */ #include <tencentcloud/bma/v20210624/model/CreateCRDesktopCodeRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Bma::V20210624::Model; using namespace std; CreateCRDesktopCodeRequest::CreateCRDesktopCodeRequest() : m_tortIdHasBeenSet(false), m_desktopCodeHasBeenSet(false) { } string CreateCRDesktopCodeRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_tortIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TortId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_tortId, allocator); } if (m_desktopCodeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DesktopCode"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_desktopCode.c_str(), allocator).Move(), allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } int64_t CreateCRDesktopCodeRequest::GetTortId() const { return m_tortId; } void CreateCRDesktopCodeRequest::SetTortId(const int64_t& _tortId) { m_tortId = _tortId; m_tortIdHasBeenSet = true; } bool CreateCRDesktopCodeRequest::TortIdHasBeenSet() const { return m_tortIdHasBeenSet; } string CreateCRDesktopCodeRequest::GetDesktopCode() const { return m_desktopCode; } void CreateCRDesktopCodeRequest::SetDesktopCode(const string& _desktopCode) { m_desktopCode = _desktopCode; m_desktopCodeHasBeenSet = true; } bool CreateCRDesktopCodeRequest::DesktopCodeHasBeenSet() const { return m_desktopCodeHasBeenSet; }
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
59cddcf1832916fe599dcf4d6066e18c9a8c7a40
46ea21ab2cdf51d78d960299e14e94400c22bf49
/iniFileOprattion/FileOpration.cpp
5bb58cd6ea0250d149fbf7784e7235559e91ad47
[]
no_license
liujunzhang007/IniFileOperation
8072364b3607e1cdb0f5dc8b578b8cae361f4c60
f353c1d5705e24d01055564455b3ac92c5e63f51
refs/heads/master
2020-04-02T18:22:57.145016
2019-08-21T15:06:50
2019-08-21T15:06:50
154,697,885
0
0
null
null
null
null
UTF-8
C++
false
false
2,104
cpp
#include "FileOpration.h" #include<QSettings> #include <QGuiApplication> #include<QFile> #include<QDebug> FileOpration::FileOpration() { } void FileOpration::fileCreate(){ QString appPath = QCoreApplication::applicationDirPath() + "/languages.ini"; qDebug()<<"QFile.exists()----Ture-------"<<appPath; //QSettings构造函数的第一个参数是ini文件的路径,第二个参数表示针对ini文件,第三个参数可以缺省 QSettings *configIniWrite = new QSettings(appPath, QSettings::IniFormat); //向ini文件中写入内容,setValue函数的两个参数是键值对 //向ini文件的第一个节写入内容,ip节下的第一个参数 configIniWrite->setValue("/ip/first", "192.168.0.1"); //向ini文件的第一个节写入内容,ip节下的第二个参数 configIniWrite->setValue("ip/second", "127.0.0.1"); //向ini文件的第二个节写入内容,port节下的第一个参数 configIniWrite->setValue("port/open", "2222"); //写入完成后删除指针 delete configIniWrite; } void FileOpration::fileRead(){ QSettings *pIni = new QSettings(QCoreApplication::applicationDirPath()+"/languages.ini", QSettings::IniFormat); QString sArg = ""; sArg = pIni->value("/ip/first").toString(); qDebug("arg1 = %s\n", sArg.toStdString().data()); sArg = ""; sArg = pIni->value("ip/second").toString(); qDebug("arg2 = %s\n", sArg.toStdString().data()); sArg = ""; sArg = pIni->value("port/open").toString(); qDebug("arg3 = %s\n", sArg.toStdString().data()); delete pIni; } void FileOpration::fileWrite(){ QSettings *pIni = new QSettings(QCoreApplication::applicationDirPath()+"/languages.ini", QSettings::IniFormat); if(!pIni->contains("Data/Language")){ pIni->setValue("Data/Language","alreadySave"); qDebug()<<"Data/Language already writed! === "<<pIni->value("Data/Language").toString().toStdString().data(); }else { qDebug()<<"Data/Language already exisited! === "<<pIni->value("Data/Language").toString().toStdString().data(); } delete pIni; }
[ "liujunzhang007@sina.cn" ]
liujunzhang007@sina.cn
d3bd9db65e2c325ba54a66351af98dcb1e53c5c1
6bd0b2a34bd546e9371c38103a281ce78575e6b6
/src/engine/file_system.cpp
2a791942d0abf606be129b7350ba5bdf92754e7a
[ "MIT" ]
permissive
khyveasna/LumixEngine
efe131faa31b69bdf9173339e69dae46ad9606dd
b32bbc4558978dcc0eb73d48a63ac545418ccaab
refs/heads/master
2022-01-20T21:27:20.364696
2019-07-19T19:28:07
2019-07-19T19:28:07
197,835,659
1
0
null
2019-07-19T20:10:05
2019-07-19T20:10:05
null
UTF-8
C++
false
false
9,477
cpp
#include "engine/file_system.h" #include "engine/allocator.h" #include "engine/array.h" #include "engine/crc32.h" #include "engine/delegate_list.h" #include "engine/flag_set.h" #include "engine/hash_map.h" #include "engine/log.h" #include "engine/mt/sync.h" #include "engine/mt/task.h" #include "engine/os.h" #include "engine/path.h" #include "engine/path_utils.h" #include "engine/profiler.h" #include "engine/queue.h" #include "engine/stream.h" #include "engine/string.h" #ifdef _WIN32 #include <Windows.h> #endif namespace Lumix { struct TarHeader { char name[100]; char mode[8]; char uid[8]; char gid[8]; char size[12]; char mtime[12]; char chksum[8]; char typeflag; char linkname[100]; char magic[6]; char version[2]; char uname[32]; char gname[32]; char devmajor[8]; char devminor[8]; char prefix[155]; }; struct AsyncItem { enum class Flags : u32 { FAILED = 1 << 0, CANCELED = 1 << 1, }; AsyncItem(IAllocator& allocator) : data(allocator) {} bool isFailed() const { return flags.isSet(Flags::FAILED); } bool isCanceled() const { return flags.isSet(Flags::CANCELED); } FileSystem::ContentCallback callback; Array<u8> data; StaticString<MAX_PATH_LENGTH> path; u32 id = 0; FlagSet<Flags, u32> flags; }; struct FileSystemImpl; class FSTask final : public MT::Task { public: FSTask(FileSystemImpl& fs, IAllocator& allocator) : MT::Task(allocator) , m_fs(fs) { } ~FSTask() = default; void stop(); int task() override; private: FileSystemImpl& m_fs; bool m_finish = false; }; struct FileSystemImpl final : public FileSystem { explicit FileSystemImpl(const char* base_path, IAllocator& allocator) : m_allocator(allocator) , m_queue(allocator) , m_finished(allocator) , m_last_id(0) , m_semaphore(0, 0xffFF) , m_bundled(allocator) , m_bundled_map(allocator) { setBasePath(base_path); loadBundled(); m_task = LUMIX_NEW(m_allocator, FSTask)(*this, m_allocator); m_task->create("Filesystem", true); } ~FileSystemImpl() { m_task->stop(); m_task->destroy(); LUMIX_DELETE(m_allocator, m_task); } void loadBundled() { #ifdef _WIN32 HRSRC hrsrc = FindResource(GetModuleHandle(NULL), MAKEINTRESOURCE(102), "TAR"); if (!hrsrc) return; HGLOBAL hglobal = LoadResource(GetModuleHandle(NULL), hrsrc); if (!hglobal) return; const DWORD size = SizeofResource(GetModuleHandle(NULL), hrsrc); if (size == 0) return; const void* res_mem = LockResource(hglobal); if (!res_mem) return; TCHAR exe_path[MAX_PATH_LENGTH]; GetModuleFileName(NULL, exe_path, MAX_PATH_LENGTH); m_bundled_last_modified = OS::getLastModified(exe_path); m_bundled.resize((int)size); memcpy(m_bundled.begin(), res_mem, m_bundled.byte_size()); InputMemoryStream str(m_bundled.begin(), m_bundled.byte_size()); UnlockResource(res_mem); TarHeader header; while (str.getPosition() < str.size()) { const u8* ptr = (const u8*)str.getData() + str.getPosition(); str.read(&header, sizeof(header)); u32 size; fromCStringOctal(header.size, sizeof(header.size), &size); if (header.name[0] && header.typeflag == 0 || header.typeflag == '0') { Path path(header.name); m_bundled_map.insert(path.getHash(), ptr); } str.setPosition(str.getPosition() + (512 - str.getPosition() % 512) % 512); str.setPosition(str.getPosition() + size + (512 - size % 512) % 512); } #endif } bool hasWork() override { MT::CriticalSectionLock lock(m_mutex); return !m_queue.empty(); } const char* getBasePath() const override { return m_base_path; } void setBasePath(const char* dir) override { PathUtils::normalize(dir, m_base_path.data, lengthOf(m_base_path.data)); if (!endsWith(m_base_path, "/") && !endsWith(m_base_path, "\\")) { m_base_path << '/'; } } bool getContentSync(const Path& path, Array<u8>* content) override { OS::InputFile file; StaticString<MAX_PATH_LENGTH> full_path(m_base_path, path.c_str()); if (!file.open(full_path)) { auto iter = m_bundled_map.find(path.getHash()); if (iter.isValid()) { const TarHeader* header = (const TarHeader*)iter.value(); u32 size; fromCStringOctal(header->size, sizeof(header->size), &size); content->resize(size); copyMemory(content->begin(), iter.value() + 512, content->byte_size()); return true; } return false; } content->resize((int)file.size()); if (!file.read(content->begin(), content->byte_size())) { file.close(); return false; } file.close(); return true; } AsyncHandle getContent(const Path& file, const ContentCallback& callback) override { if (!file.isValid()) return AsyncHandle::invalid(); MT::CriticalSectionLock lock(m_mutex); AsyncItem& item = m_queue.emplace(m_allocator); ++m_last_id; if (m_last_id == 0) ++m_last_id; item.id = m_last_id; item.path = file.c_str(); item.callback = callback; m_semaphore.signal(); return AsyncHandle(item.id); } void cancel(AsyncHandle async) override { MT::CriticalSectionLock lock(m_mutex); for (AsyncItem& item : m_queue) { if (item.id == async.value) { item.flags.set(AsyncItem::Flags::CANCELED); return; } } for (AsyncItem& item : m_finished) { if (item.id == async.value) { item.flags.set(AsyncItem::Flags::CANCELED); return; } } } bool open(const char* path, OS::InputFile* file) override { ASSERT(file); StaticString<MAX_PATH_LENGTH> full_path(m_base_path, path); return file->open(full_path); } bool open(const char* path, OS::OutputFile* file) override { ASSERT(file); StaticString<MAX_PATH_LENGTH> full_path(m_base_path, path); return file->open(full_path); } bool copyFile(const char* from, const char* to) override { StaticString<MAX_PATH_LENGTH> full_path_from(m_base_path, from); StaticString<MAX_PATH_LENGTH> full_path_to(m_base_path, to); if (OS::copyFile(full_path_from, full_path_to)) return true; auto iter = m_bundled_map.find(crc32(from)); if(!iter.isValid()) return false; OS::OutputFile file; if(!file.open(full_path_to)) return false; u32 size; TarHeader* header = (TarHeader*)iter.value(); fromCStringOctal(header->size, sizeof(header->size), &size); const bool res = file.write(iter.value() + 512, size); file.close(); return res; } bool fileExists(const char* path) override { StaticString<MAX_PATH_LENGTH> full_path(m_base_path, path); if (!OS::fileExists(full_path)) { return (m_bundled_map.find(crc32(path)).isValid()); } return true; } u64 getLastModified(const char* path) override { StaticString<MAX_PATH_LENGTH> full_path(m_base_path, path); const u64 res = OS::getLastModified(full_path); if (!res && m_bundled_map.find(crc32(path)).isValid()) { return m_bundled_last_modified; } return res; } OS::FileIterator* createFileIterator(const char* dir) override { StaticString<MAX_PATH_LENGTH> path(m_base_path, dir); return OS::createFileIterator(path, m_allocator); } void updateAsyncTransactions() override { PROFILE_FUNCTION(); for(;;) { m_mutex.enter(); if (m_finished.empty()) { m_mutex.exit(); break; } AsyncItem item = static_cast<AsyncItem&&>(m_finished[0]); m_finished.erase(0); m_mutex.exit(); if(!item.isCanceled()) { item.callback.invoke(item.data.size(), item.data.begin(), !item.isFailed()); } } } IAllocator& m_allocator; FSTask* m_task; StaticString<MAX_PATH_LENGTH> m_base_path; Array<AsyncItem> m_queue; Array<AsyncItem> m_finished; Array<u8> m_bundled; HashMap<u32, const u8*> m_bundled_map; u64 m_bundled_last_modified; MT::CriticalSection m_mutex; MT::Semaphore m_semaphore; u32 m_last_id; }; int FSTask::task() { while (!m_finish) { m_fs.m_semaphore.wait(); if (m_finish) break; StaticString<MAX_PATH_LENGTH> path; { MT::CriticalSectionLock lock(m_fs.m_mutex); ASSERT(!m_fs.m_queue.empty()); path = m_fs.m_queue[0].path; if (m_fs.m_queue[0].isCanceled()) { m_fs.m_queue.erase(0); continue; } } bool success = true; Array<u8> data(m_fs.m_allocator); OS::InputFile file; StaticString<MAX_PATH_LENGTH> full_path(m_fs.m_base_path, path); if (file.open(full_path)) { data.resize((int)file.size()); if (!file.read(data.begin(), data.byte_size())) { success = false; } file.close(); } else { auto iter = m_fs.m_bundled_map.find(crc32(path)); if (iter.isValid()) { const TarHeader* header = (const TarHeader*)iter.value(); u32 size; fromCStringOctal(header->size, sizeof(header->size), &size); data.resize(size); copyMemory(data.begin(), iter.value() + 512, data.byte_size()); success = true; } else { success = false; } } { MT::CriticalSectionLock lock(m_fs.m_mutex); if (!m_fs.m_queue[0].isCanceled()) { m_fs.m_finished.emplace(static_cast<AsyncItem&&>(m_fs.m_queue[0])); m_fs.m_finished.back().data = static_cast<Array<u8>&&>(data); if(!success) { m_fs.m_finished.back().flags.set(AsyncItem::Flags::FAILED); } m_fs.m_queue.erase(0); } } } return 0; } void FSTask::stop() { m_finish = true; m_fs.m_semaphore.signal(); } FileSystem* FileSystem::create(const char* base_path, IAllocator& allocator) { return LUMIX_NEW(allocator, FileSystemImpl)(base_path, allocator); } void FileSystem::destroy(FileSystem* fs) { LUMIX_DELETE(static_cast<FileSystemImpl*>(fs)->m_allocator, fs); } } // namespace Lumix
[ "mikulas.florek@gamedev.sk" ]
mikulas.florek@gamedev.sk
0e704dec214cf8eb6cb5a3d2d9197763a2f2e327
cb2fe0a9a10a7418bc683df6eedb238c657f4c8a
/Basics of C++/tutorial_11_do_while.cpp
9c5434620b885770f5311a26932f22777c10a84f
[]
no_license
withoutwaxaryan/programming-basics
bf33c32545e89deba13c6ab33a1568e69f40c693
93c0c57bf36acd1190f65ec3f2b6d316d59eaaf0
refs/heads/master
2023-03-07T04:58:37.451151
2021-02-20T12:26:14
2021-02-20T12:26:14
181,515,433
0
0
null
null
null
null
UTF-8
C++
false
false
147
cpp
#include<iostream> using namespace std; int main() { int x =1; do { cout<<"yo"<<endl; } while (x<1); return 0; }
[ "aryangupta973@gmail.com" ]
aryangupta973@gmail.com
af7eab081e8ec9c4a82d4aebf4c590e4d5f82f86
8b29d172daa0adf10150bff5791723c787bf4874
/include/FeatureDetect.h
eb615b878adfcc53ed17ddda1b31a0065b4f5e93
[]
no_license
bazinga-IIIIII/slam
b2b1c55ef926a518f09626e9b552c76be780a2eb
45b3c77a93ad2ebd841a021ddc10267c97f08c1e
refs/heads/master
2021-01-21T04:42:28.457018
2016-05-24T06:42:49
2016-05-24T06:42:49
54,100,090
0
0
null
null
null
null
UTF-8
C++
false
false
1,138
h
/* * FeatureDetect.h * * Created on: Mar 30, 2016 * Author: wei */ #ifndef FEATUREDETECT_H_ #define FEATUREDETECT_H_ #include "rgbdframe.h" using namespace rgbd_tutor; using namespace cv; class FeatureDetect { public: FeatureDetect(); virtual ~FeatureDetect(); public: OrbFeatureDetector feature_detector; OrbDescriptorExtractor feature_extractor; double good_match_threshold; int min_inliers; double keyframe_threshold; double max_norm; public: void Detect_orb(RGBDFrame::Ptr& frame); void Detect_sift(RGBDFrame::Ptr& frame); void Detect_surf(RGBDFrame::Ptr& frame); RESULT_OF_PNP Match_orb(RGBDFrame::Ptr& src, RGBDFrame::Ptr& dst, CAMERA_INTRINSIC_PARAMETERS cam); RESULT_OF_PNP Match_sift(RGBDFrame::Ptr& src, RGBDFrame::Ptr& dst, CAMERA_INTRINSIC_PARAMETERS cam); RESULT_OF_PNP Match_surf(RGBDFrame::Ptr& src, RGBDFrame::Ptr& dst, CAMERA_INTRINSIC_PARAMETERS cam); int Key_Frame_Judge(RESULT_OF_PNP result_of_pnp); public: double normofTransform(cv::Mat rvec, cv::Mat tvec) { return fabs(min(cv::norm(rvec), 2 * M_PI - cv::norm(rvec))) + fabs(cv::norm(tvec)); } }; #endif /* FEATUREDETECT_H_ */
[ "liuwei.unique@gmail.com" ]
liuwei.unique@gmail.com
2e6d230f3813d328f3eacc7cf144d9d9206e641b
0f1ce772c2fb5c92baab3305d2bd0d392860d0ac
/2018_exam/authentication.cpp
56cf222c7fc5592f3c52d54a7196df37fa4ddeeb
[]
no_license
seyone22/dev
110342dca9cf4413af09c1de132c2ea0079c242b
901b0e6e0bd11cdea9154060898787a41e8abcef
refs/heads/master
2023-08-24T16:01:52.830400
2021-10-27T11:07:21
2021-10-27T11:07:21
384,070,046
4
0
null
null
null
null
UTF-8
C++
false
false
1,386
cpp
#include <iostream> #include <sstream> #include <string> using namespace std; string getinput(string description = "No description provided") { string input; cout << description << "\n>>"; getline(cin, input); return input; } int main() { int attempts = 0; while (true) { if (attempts == 3) { return 0; } string username = getinput("Please enter your username"); string pwd = getinput("Please enter your password"); string pwdCon = getinput("Please reenter your password"); int pwdInt = stoi(pwd); if (pwd == pwdCon) { if ((pwdInt >= 1000 && pwdInt <= 9999) || pwdInt == 0000) //checks all numerical values from 0000 to 1000 { cout << "Access granted. Good day, " << username << "!" << endl; break; } else { cout << "The password is incorrect. Please try again.\n"; attempts += 1; cout << "Remaining attempts: " << attempts << endl; } } else { cout << "The passwords do not match. Please try again.\n"; attempts += 1; cout << "Remaining attempts: " << attempts << endl; } }; cout << "successful break\n"; system("pause"); return 0; }
[ "s.g.seyone@protonmail.com" ]
s.g.seyone@protonmail.com
72f2814bb364c7eeb37e394058533fa925ab173e
a7e3dac1fff4bb7f6b3af4bd33b84f5fefdfe9fe
/ABC/abc098/arc098_a_6400694.cpp
37f7a06f49e592bb4952aebd509d01bffd2e94ed
[]
no_license
2019Shun/atcoder_submission
b6794a0bb1e8d2aa5c4663a15ae561dbe59d50cb
a511da6de51ed4eabd25bf2f823b9867f7650649
refs/heads/master
2023-04-01T14:53:46.164877
2021-03-28T15:00:13
2021-03-28T15:00:13
316,533,181
0
0
null
null
null
null
UTF-8
C++
false
false
1,650
cpp
#include <bits/stdc++.h> #include <vector> #include <numeric> #define PI 3.14159265358979323846 #define MAXINF (1e18L) #define INF (1e9L) #define EPS (1e-9) #define MOD ((ll)(1e9+7)) #define REP(i, n) for(int i=0;i<int(n);++i) #define Rep(i,sta,n) for(int i=sta;i<n;i++) #define RREP(i, n) for(int i=int(n)-1;i>=0;--i) #define ALL(v) v.begin(),v.end() #define FIND(v,x) (binary_search(ALL(v),(x))) #define SORT(v) sort(ALL(v)) #define RSORT(v) sort(ALL(v));reverse(ALL(v)) #define DEBUG(x) cerr<<#x<<": "<<x<<endl; #define DEBUG_VEC(v) cerr<<#v<<":";for(int i=0;i<v.size();i++) cerr<<" "<<v[i]; cerr<<endl #define Yes(n) cout<<((n)?"Yes":"No")<<endl #define YES(n) cout<<((n)?"YES":"NO")<<endl #define pb push_back #define fi first #define se second using namespace std; template<class A>void pr(A a){cout << (a) << endl;} template<class A,class B>void pr(A a,B b){cout << a << " " ;pr(b);} template<class A,class B,class C>void pr(A a,B b,C c){cout << a << " " ;pr(b,c);} template<class A,class B,class C,class D>void pr(A a,B b,C c,D d){cout << a << " " ;pr(b,c,d);} template<class T> inline bool chmin(T& a, T b){return a>b ? a=b, true : false;} template<class T> inline bool chmax(T& a, T b){return a<b ? a=b, true : false;} typedef long long ll; typedef pair<int, int> pii; typedef pair<ll,ll> pll; int main(void) { int n; cin >> n; string s; cin >> s; vector<int> l(n, 0); Rep(i, 1, n){ if(s[i] == 'E') l[0]++; } Rep(i, 1, n){ l[i] = l[i-1]; if(s[i-1] == 'W') l[i]++; if(s[i] == 'E') l[i]--; } SORT(l); pr(l[0]); }
[ "taka.shun.2018@gmail.com" ]
taka.shun.2018@gmail.com
78892b817dce2eda9aa709c78090e1a2c23dd348
1331d6a97ca637306c233c07351e9f941ac2832b
/Gateway_Test/src/main.cpp
dc1a5cc2da5f4e802f231488262bb453d18b77f5
[]
no_license
christiamrojas/OI_MeasureTemperature
c45c5dbe1427450c507717663069a1588d3ad1c1
d38b611d0b9df18443d038884e92164e332e8f54
refs/heads/master
2023-06-12T08:22:51.822581
2021-07-05T15:09:21
2021-07-05T15:09:21
377,896,953
0
0
null
null
null
null
UTF-8
C++
false
false
5,334
cpp
//----------------------------------------------- // Libraries //----------------------------------------------- #include "Global.h" #include "Task_ModBus.h" #include "Task_LoRa.h" #include "Task_Rtc.h" #include "Task_Serial.h" uint8_t Register[64]; uint8_t DevSamp[8]; char* ssid = ""; char* password = "Diacsa4723128"; WiFiServer server(80); IPAddress ip(192, 168, 10, 10); IPAddress gateway(192, 168, 10, 1); IPAddress subnet(255, 255, 255, 0); Rtc_struct Rtc; //----------------------------------------------- // Main Program //----------------------------------------------- void setup() { Serial.begin(115200); delay(100); pinMode(PinLed,OUTPUT); digitalWrite(PinLed,LOW); xTaskCreate(ModTcp_Task,"Task_ModbusTcp",20480,NULL,2,NULL); xTaskCreate(LoRa_Task,"Task_LoRaReception",10240,NULL,2,NULL); xTaskCreate(Rtc_Task,"Task_Rtc",4096,NULL,2,NULL); xTaskCreate(Serial_Task,"Task_Serial",4096,NULL,2,NULL); } void loop() {} //------------------------------------------------------------------------ // Modbus TCP Task //------------------------------------------------------------------------ void ModTcp_Task(void *pvParameters) { uint8_t cad[128]; uint8_t b,start,idx; WiFiClient client; unsigned long tini; long t; start = idx = 0; ModTcp_WiFiConn(&server,ssid,password,&ip,&gateway,&subnet); while(1) { vTaskDelay(0); client=server.available(); if(!client) continue; Serial.println("Client connected"); while(client.connected()) { vTaskDelay(0); if(client.available()==0) continue; b = client.read(); #ifdef Modbus_Debug Serial.print(b,HEX); Serial.print(" "); #endif if(start==0) { tini = millis(); start=1; } t = millis()-tini; if((t<0)||(t>5000)) { idx=0; start=0; } if( (b==0xff) && (idx==0) ) continue; cad[idx++] = b; if(idx<12) continue; idx = 0; if(ModTcp_RxTx(&client,cad,Register)==0) Serial.println("Request: Incorrect format"); else Serial.println("Request: Responded"); } Serial.println("Client disconnected"); } } //------------------------------------------------------------------------ // Lora task //------------------------------------------------------------------------ void LoRa_Task(void *pvParameters) { int packetLen; uint8_t data[256],i,d; DevSamp[1] = DevSamp[3] = 0xff; for(uint8_t d=0;d<64;d++) Register[d] = 0xff; LoRa_Init(); LoRa.receive(); while(1) { delay(10); Lora_CheckTxConfig(DevSamp); packetLen = LoRa.parsePacket(); if(packetLen==0) continue; if(packetLen!=10){ Serial.println("LoRa: Packet length error"); while(LoRa.available()) d = LoRa.read(); continue; } #ifdef Lora_Debug Serial.print("LoRa Debug: "); #endif digitalWrite(PinLed,HIGH); while(LoRa.available()){ data[i]= LoRa.read(); #ifdef Lora_Debug Serial.print(data[i],HEX); Serial.print(" "); #endif i++; } i=0; #ifdef Lora_Debug Serial.println(""); #endif uint8_t node; if(Lora_ParseNodePacket(data,Register,&Rtc,&node)==true) { Serial.print("Node-"); Serial.print(node); Serial.print(" "); Serial.print(Register[node*16]);Serial.print(":");Serial.print(Register[node*16+1]);Serial.print(":");Serial.print(Register[node*16+2]);Serial.print(" "); Serial.print(Register[node*16+3]);Serial.print("/");Serial.print(Register[node*16+4]);Serial.print("/");Serial.print(Register[node*16+5]); Serial.print(" - "); for(uint8_t j=0;j<10;j++) { Serial.print(Register[16*node+2*j+6],HEX); Serial.print(Register[16*node+2*j+7],HEX); Serial.print(" "); } Serial.println(""); } digitalWrite(PinLed,LOW); } } void Rtc_Task(void *pvParameters) { Rtc.day = 3; Rtc.month = 5; Rtc.year = 21; Rtc.hour = 1; Rtc.minute = 20; Rtc.second = 03; while(1) { vTaskDelay(105); Rtc_UpdateRtc(&Rtc); } } void Serial_Task(void *pvParameters) { uint8_t cadRx[50],i; while(1) { vTaskDelay(100); if(Serial.available()==0) continue; while(Serial.available()!=0) { if(i>=50) i=0; cadRx[i++] = Serial.read(); if( (cadRx[i-1]==10) ) break; } i=0; if(Serial_UpdateTime(cadRx, &Rtc)==true) continue; if(Serial_UpdateDeviceSampling(cadRx,DevSamp)==true) continue; Serial.println("Unknow command"); } }
[ "crojas@diacsa.com" ]
crojas@diacsa.com
657371e198c8432a210112097386edb68d064c07
f9e2744ff3e630d3416843b243e6451ad2030263
/src/qt/sendcoinsdialog.cpp
bcf7b3e5e15b826ff466a11d8af759e85caa2cea
[ "MIT" ]
permissive
bincoinus/Bincoin
0623e166b288ff7279fe0fa85efd2db66e949a63
6bc3afc8bb03f7eb3c6618ba2303c04b6795619d
refs/heads/master
2020-06-11T23:37:03.614478
2016-12-05T10:15:24
2016-12-05T10:15:24
75,612,846
0
0
null
null
null
null
UTF-8
C++
false
false
17,900
cpp
#include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "init.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "addressbookpage.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QLocale> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { 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 #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a BinCoin address (e.g. 1B4e4ah2nr6nfwYhBmGXcFP2Po1NpRUEiK8km2)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont()); 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 &))); // 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 low output"), 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); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address)); } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(recipients); else sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: 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."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { delete ui->entries->takeAt(0)->widget(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } 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())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); QCoreApplication::instance()->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { delete entry; updateRemoveEnabled(); } 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->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } 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); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(stake); Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance())); } } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { QApplication::clipboard()->setText(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { QApplication::clipboard()->setText(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // 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(); } // 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 (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString & text) { if (model) { CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get(); // label for the change address ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); if (text.isEmpty()) ui->labelCoinControlChangeLabel->setText(""); else if (!CBitcoinAddress(text.toStdString()).IsValid()) { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: Invalid BinCoin address")); } else { QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else { CPubKey pubkey; CKeyID keyid; CBitcoinAddress(text.toStdString()).GetKeyID(keyid); if (model->getPubKey(keyid, pubkey)) ui->labelCoinControlChangeLabel->setText(tr("(no label)")); else { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: unknown change address")); } } } } } // 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(); } }
[ "team@bincoin.us" ]
team@bincoin.us
cd0bf51f186ccf0db1712b0624e0dbc238afbaed
cbfd948b53734a5a22993dc3e8b82d86d3807548
/GtkMouse201608311200/Program.cpp
8ab0f0b8567f4aafbe3678c3924f0041288c3220
[ "CC0-1.0" ]
permissive
ytyaru/GtkMouse201608311200
bf33a0604ee4accda3eeffa12f9e3a52efed6b37
2f1c957f7698a163165bc431a34d8a3c261419f5
refs/heads/master
2020-09-16T21:52:26.739256
2016-08-31T22:36:55
2016-08-31T22:36:55
67,078,293
0
0
null
null
null
null
UTF-8
C++
false
false
2,277
cpp
#include <gtk-2.0/gtk/gtk.h> #include <cairo.h> #include <glib.h> #include <glib/gprintf.h> // g_sprintf int g_mouseX = 0; int g_mouseY = 0; GtkWidget *drawing_area = NULL; gboolean Draw(GtkWidget *widget, GdkEventExpose *event, gpointer data) { cairo_t *cr; cr = gdk_cairo_create(widget->window); cairo_select_font_face (cr, "Serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size(cr, 24); gchar posStr[256] = ""; g_sprintf(posStr, "(%d,%d)", (int)g_mouseX, (int)g_mouseY); cairo_set_source_rgba(cr, 1, 0, 0, 1); cairo_move_to(cr, (int)g_mouseX, (int)g_mouseY); cairo_show_text(cr, posStr); cairo_destroy(cr); return FALSE; } gint delete_event(GtkWidget *widget, GdkEvent *event, gpointer data) { g_print ("delete_event\n"); return FALSE; // windowが"delete_event"により破棄される //return TRUE; // windowが"delete_event"により破棄されない } void destroy(GtkWidget *widget, gpointer data) { g_print ("destroy\n"); gtk_main_quit (); } gint motion_notify_event (GtkWidget *widget, GdkEventMotion *event) { g_mouseX = (int)event->x; g_mouseY = (int)event->y; g_print("motion_notify_event (%f,%f)\n", event->x, event->y); gtk_widget_queue_draw_area( drawing_area, 0, 0, 400, 300); return TRUE; } int main(int argc, char* argv[]) { gtk_set_locale(); gtk_init(&argc, &argv); GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "Mouse Point Draw"); gtk_window_set_default_size(GTK_WINDOW(window), 400, 300); gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (delete_event), NULL); gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (destroy), NULL); drawing_area = gtk_drawing_area_new(); gtk_widget_set_size_request (drawing_area, 400, 300); gtk_container_add(GTK_CONTAINER(window), drawing_area); g_signal_connect(G_OBJECT(drawing_area), "expose_event", G_CALLBACK(Draw), NULL); gtk_signal_connect (GTK_OBJECT (drawing_area), "motion_notify_event", (GtkSignalFunc) motion_notify_event, NULL); gtk_widget_set_events(drawing_area, GDK_POINTER_MOTION_MASK ); gtk_widget_show_all(window); gtk_main(); return 0; }
[ "ytyaru@outlook.jp" ]
ytyaru@outlook.jp
663e83919d360dad9de88c94859264d7856bfcd0
57ed0d32c96ee0e1adf0f1dedfb0a1a782cccd21
/lib/Target/DCPU16/DCPU16ISelLowering.cpp
00fc5e877bd150206950e6e35462ace6d3844be8
[ "NCSA" ]
permissive
Blei/llvm-dcpu16
61fe3af6de3fedd10bcb84b68ef5d337ba27627c
d9995cc702576cc489c6ac1bcdbcd3b01f351038
refs/heads/main
2021-01-17T16:25:32.596393
2012-04-07T18:14:25
2012-04-07T18:14:25
3,963,745
1
0
null
null
null
null
UTF-8
C++
false
false
45,661
cpp
//===-- DCPU16ISelLowering.cpp - DCPU16 DAG Lowering Implementation ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the DCPU16TargetLowering class. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "dcpu16-lower" #include "DCPU16ISelLowering.h" #include "DCPU16.h" #include "DCPU16MachineFunctionInfo.h" #include "DCPU16TargetMachine.h" #include "DCPU16Subtarget.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/Intrinsics.h" #include "llvm/CallingConv.h" #include "llvm/GlobalVariable.h" #include "llvm/GlobalAlias.h" #include "llvm/CodeGen/CallingConvLower.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; typedef enum { NoHWMult, HWMultIntr, HWMultNoIntr } HWMultUseMode; static cl::opt<HWMultUseMode> HWMultMode("dcpu16-hwmult-mode", cl::desc("Hardware multiplier use mode"), cl::init(HWMultNoIntr), cl::values( clEnumValN(NoHWMult, "no", "Do not use hardware multiplier"), clEnumValN(HWMultIntr, "interrupts", "Assume hardware multiplier can be used inside interrupts"), clEnumValN(HWMultNoIntr, "use", "Assume hardware multiplier cannot be used inside interrupts"), clEnumValEnd)); DCPU16TargetLowering::DCPU16TargetLowering(DCPU16TargetMachine &tm) : TargetLowering(tm, new TargetLoweringObjectFileELF()), Subtarget(*tm.getSubtargetImpl()), TM(tm) { TD = getTargetData(); // Set up the register classes. addRegisterClass(MVT::i8, DCPU16::GR8RegisterClass); addRegisterClass(MVT::i16, DCPU16::GR16RegisterClass); // Compute derived properties from the register classes computeRegisterProperties(); // Provide all sorts of operation actions // Division is expensive setIntDivIsCheap(false); setStackPointerRegisterToSaveRestore(DCPU16::SPW); setBooleanContents(ZeroOrOneBooleanContent); setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct? // We have post-incremented loads / stores. setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal); setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal); setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote); setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote); setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand); setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand); // We don't have any truncstores setTruncStoreAction(MVT::i16, MVT::i8, Expand); setOperationAction(ISD::SRA, MVT::i8, Custom); setOperationAction(ISD::SHL, MVT::i8, Custom); setOperationAction(ISD::SRL, MVT::i8, Custom); setOperationAction(ISD::SRA, MVT::i16, Custom); setOperationAction(ISD::SHL, MVT::i16, Custom); setOperationAction(ISD::SRL, MVT::i16, Custom); setOperationAction(ISD::ROTL, MVT::i8, Expand); setOperationAction(ISD::ROTR, MVT::i8, Expand); setOperationAction(ISD::ROTL, MVT::i16, Expand); setOperationAction(ISD::ROTR, MVT::i16, Expand); setOperationAction(ISD::GlobalAddress, MVT::i16, Custom); setOperationAction(ISD::ExternalSymbol, MVT::i16, Custom); setOperationAction(ISD::BlockAddress, MVT::i16, Custom); setOperationAction(ISD::BR_JT, MVT::Other, Expand); setOperationAction(ISD::BR_CC, MVT::i8, Custom); setOperationAction(ISD::BR_CC, MVT::i16, Custom); setOperationAction(ISD::BRCOND, MVT::Other, Expand); setOperationAction(ISD::SETCC, MVT::i8, Custom); setOperationAction(ISD::SETCC, MVT::i16, Custom); setOperationAction(ISD::SELECT, MVT::i8, Expand); setOperationAction(ISD::SELECT, MVT::i16, Expand); setOperationAction(ISD::SELECT_CC, MVT::i8, Custom); setOperationAction(ISD::SELECT_CC, MVT::i16, Custom); setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Custom); setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand); setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand); setOperationAction(ISD::CTTZ, MVT::i8, Expand); setOperationAction(ISD::CTTZ, MVT::i16, Expand); setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i8, Expand); setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Expand); setOperationAction(ISD::CTLZ, MVT::i8, Expand); setOperationAction(ISD::CTLZ, MVT::i16, Expand); setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8, Expand); setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Expand); setOperationAction(ISD::CTPOP, MVT::i8, Expand); setOperationAction(ISD::CTPOP, MVT::i16, Expand); setOperationAction(ISD::SHL_PARTS, MVT::i8, Expand); setOperationAction(ISD::SHL_PARTS, MVT::i16, Expand); setOperationAction(ISD::SRL_PARTS, MVT::i8, Expand); setOperationAction(ISD::SRL_PARTS, MVT::i16, Expand); setOperationAction(ISD::SRA_PARTS, MVT::i8, Expand); setOperationAction(ISD::SRA_PARTS, MVT::i16, Expand); setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); // FIXME: Implement efficiently multiplication by a constant setOperationAction(ISD::MUL, MVT::i8, Expand); setOperationAction(ISD::MULHS, MVT::i8, Expand); setOperationAction(ISD::MULHU, MVT::i8, Expand); setOperationAction(ISD::SMUL_LOHI, MVT::i8, Expand); setOperationAction(ISD::UMUL_LOHI, MVT::i8, Expand); setOperationAction(ISD::MUL, MVT::i16, Expand); setOperationAction(ISD::MULHS, MVT::i16, Expand); setOperationAction(ISD::MULHU, MVT::i16, Expand); setOperationAction(ISD::SMUL_LOHI, MVT::i16, Expand); setOperationAction(ISD::UMUL_LOHI, MVT::i16, Expand); setOperationAction(ISD::UDIV, MVT::i8, Expand); setOperationAction(ISD::UDIVREM, MVT::i8, Expand); setOperationAction(ISD::UREM, MVT::i8, Expand); setOperationAction(ISD::SDIV, MVT::i8, Expand); setOperationAction(ISD::SDIVREM, MVT::i8, Expand); setOperationAction(ISD::SREM, MVT::i8, Expand); setOperationAction(ISD::UDIV, MVT::i16, Expand); setOperationAction(ISD::UDIVREM, MVT::i16, Expand); setOperationAction(ISD::UREM, MVT::i16, Expand); setOperationAction(ISD::SDIV, MVT::i16, Expand); setOperationAction(ISD::SDIVREM, MVT::i16, Expand); setOperationAction(ISD::SREM, MVT::i16, Expand); // Libcalls names. if (HWMultMode == HWMultIntr) { setLibcallName(RTLIB::MUL_I8, "__mulqi3hw"); setLibcallName(RTLIB::MUL_I16, "__mulhi3hw"); } else if (HWMultMode == HWMultNoIntr) { setLibcallName(RTLIB::MUL_I8, "__mulqi3hw_noint"); setLibcallName(RTLIB::MUL_I16, "__mulhi3hw_noint"); } setMinFunctionAlignment(1); setPrefFunctionAlignment(2); } SDValue DCPU16TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { switch (Op.getOpcode()) { case ISD::SHL: // FALLTHROUGH case ISD::SRL: case ISD::SRA: return LowerShifts(Op, DAG); case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG); case ISD::SETCC: return LowerSETCC(Op, DAG); case ISD::BR_CC: return LowerBR_CC(Op, DAG); case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG); case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); default: llvm_unreachable("unimplemented operand"); } } //===----------------------------------------------------------------------===// // DCPU16 Inline Assembly Support //===----------------------------------------------------------------------===// /// getConstraintType - Given a constraint letter, return the type of /// constraint it is for this target. TargetLowering::ConstraintType DCPU16TargetLowering::getConstraintType(const std::string &Constraint) const { if (Constraint.size() == 1) { switch (Constraint[0]) { case 'r': return C_RegisterClass; default: break; } } return TargetLowering::getConstraintType(Constraint); } std::pair<unsigned, const TargetRegisterClass*> DCPU16TargetLowering:: getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const { if (Constraint.size() == 1) { // GCC Constraint Letters switch (Constraint[0]) { default: break; case 'r': // GENERAL_REGS if (VT == MVT::i8) return std::make_pair(0U, DCPU16::GR8RegisterClass); return std::make_pair(0U, DCPU16::GR16RegisterClass); } } return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); } //===----------------------------------------------------------------------===// // Calling Convention Implementation //===----------------------------------------------------------------------===// #include "DCPU16GenCallingConv.inc" SDValue DCPU16TargetLowering::LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, DebugLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { switch (CallConv) { default: llvm_unreachable("Unsupported calling convention"); case CallingConv::C: case CallingConv::Fast: return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals); case CallingConv::DCPU16_INTR: if (Ins.empty()) return Chain; report_fatal_error("ISRs cannot have arguments"); } } SDValue DCPU16TargetLowering::LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, bool doesNotRet, bool &isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, const SmallVectorImpl<ISD::InputArg> &Ins, DebugLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { // DCPU16 target does not yet support tail call optimization. isTailCall = false; switch (CallConv) { default: llvm_unreachable("Unsupported calling convention"); case CallingConv::Fast: case CallingConv::C: return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall, Outs, OutVals, Ins, dl, DAG, InVals); case CallingConv::DCPU16_INTR: report_fatal_error("ISRs cannot be called directly"); } } /// LowerCCCArguments - transform physical registers into virtual registers and /// generate load operations for arguments places on the stack. // FIXME: struct return stuff // FIXME: varargs SDValue DCPU16TargetLowering::LowerCCCArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, DebugLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { MachineFunction &MF = DAG.getMachineFunction(); MachineFrameInfo *MFI = MF.getFrameInfo(); MachineRegisterInfo &RegInfo = MF.getRegInfo(); // Assign locations to all of the incoming arguments. SmallVector<CCValAssign, 16> ArgLocs; CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), getTargetMachine(), ArgLocs, *DAG.getContext()); CCInfo.AnalyzeFormalArguments(Ins, CC_DCPU16); assert(!isVarArg && "Varargs not supported yet"); for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { CCValAssign &VA = ArgLocs[i]; if (VA.isRegLoc()) { // Arguments passed in registers EVT RegVT = VA.getLocVT(); switch (RegVT.getSimpleVT().SimpleTy) { default: { #ifndef NDEBUG errs() << "LowerFormalArguments Unhandled argument type: " << RegVT.getSimpleVT().SimpleTy << "\n"; #endif llvm_unreachable(0); } case MVT::i16: unsigned VReg = RegInfo.createVirtualRegister(DCPU16::GR16RegisterClass); RegInfo.addLiveIn(VA.getLocReg(), VReg); SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT); // If this is an 8-bit value, it is really passed promoted to 16 // bits. Insert an assert[sz]ext to capture this, then truncate to the // right size. if (VA.getLocInfo() == CCValAssign::SExt) ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, DAG.getValueType(VA.getValVT())); else if (VA.getLocInfo() == CCValAssign::ZExt) ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, DAG.getValueType(VA.getValVT())); if (VA.getLocInfo() != CCValAssign::Full) ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); InVals.push_back(ArgValue); } } else { // Sanity check assert(VA.isMemLoc()); // Load the argument to a virtual register unsigned ObjSize = VA.getLocVT().getSizeInBits()/8; if (ObjSize > 2) { errs() << "LowerFormalArguments Unhandled argument type: " << EVT(VA.getLocVT()).getEVTString() << "\n"; } // Create the frame index object for this incoming parameter... int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset(), true); // Create the SelectionDAG nodes corresponding to a load //from this parameter SDValue FIN = DAG.getFrameIndex(FI, MVT::i16); InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN, MachinePointerInfo::getFixedStack(FI), false, false, false, 0)); } } return Chain; } SDValue DCPU16TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, DebugLoc dl, SelectionDAG &DAG) const { // CCValAssign - represent the assignment of the return value to a location SmallVector<CCValAssign, 16> RVLocs; // ISRs cannot return any value. if (CallConv == CallingConv::DCPU16_INTR && !Outs.empty()) report_fatal_error("ISRs cannot return any value"); // CCState - Info about the registers and stack slot. CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), getTargetMachine(), RVLocs, *DAG.getContext()); // Analize return values. CCInfo.AnalyzeReturn(Outs, RetCC_DCPU16); // If this is the first return lowered for this function, add the regs to the // liveout set for the function. if (DAG.getMachineFunction().getRegInfo().liveout_empty()) { for (unsigned i = 0; i != RVLocs.size(); ++i) if (RVLocs[i].isRegLoc()) DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg()); } SDValue Flag; // Copy the result values into the output registers. for (unsigned i = 0; i != RVLocs.size(); ++i) { CCValAssign &VA = RVLocs[i]; assert(VA.isRegLoc() && "Can only return in registers!"); Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag); // Guarantee that all emitted copies are stuck together, // avoiding something bad. Flag = Chain.getValue(1); } unsigned Opc = (CallConv == CallingConv::DCPU16_INTR ? DCPU16ISD::RETI_FLAG : DCPU16ISD::RET_FLAG); if (Flag.getNode()) return DAG.getNode(Opc, dl, MVT::Other, Chain, Flag); // Return Void return DAG.getNode(Opc, dl, MVT::Other, Chain); } /// LowerCCCCallTo - functions arguments are copied from virtual regs to /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted. /// TODO: sret. SDValue DCPU16TargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, bool isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, const SmallVectorImpl<ISD::InputArg> &Ins, DebugLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { // Analyze operands of the call, assigning locations to each operand. SmallVector<CCValAssign, 16> ArgLocs; CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), getTargetMachine(), ArgLocs, *DAG.getContext()); CCInfo.AnalyzeCallOperands(Outs, CC_DCPU16); // Get a count of how many bytes are to be pushed on the stack. unsigned NumBytes = CCInfo.getNextStackOffset(); Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes, getPointerTy(), true)); SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass; SmallVector<SDValue, 12> MemOpChains; SDValue StackPtr; // Walk the register/memloc assignments, inserting copies/loads. for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { CCValAssign &VA = ArgLocs[i]; SDValue Arg = OutVals[i]; // Promote the value if needed. switch (VA.getLocInfo()) { default: llvm_unreachable("Unknown loc info!"); case CCValAssign::Full: break; case CCValAssign::SExt: Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); break; case CCValAssign::ZExt: Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); break; case CCValAssign::AExt: Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); break; } // Arguments that can be passed on register must be kept at RegsToPass // vector if (VA.isRegLoc()) { RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); } else { assert(VA.isMemLoc()); if (StackPtr.getNode() == 0) StackPtr = DAG.getCopyFromReg(Chain, dl, DCPU16::SPW, getPointerTy()); SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, DAG.getIntPtrConstant(VA.getLocMemOffset())); MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo(),false, false, 0)); } } // Transform all store nodes into one single node because all store nodes are // independent of each other. if (!MemOpChains.empty()) Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &MemOpChains[0], MemOpChains.size()); // Build a sequence of copy-to-reg nodes chained together with token chain and // flag operands which copy the outgoing args into registers. The InFlag in // necessary since all emitted instructions must be stuck together. SDValue InFlag; for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, RegsToPass[i].second, InFlag); InFlag = Chain.getValue(1); } // If the callee is a GlobalAddress node (quite common, every direct call is) // turn it into a TargetGlobalAddress node so that legalize doesn't hack it. // Likewise ExternalSymbol -> TargetExternalSymbol. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i16); else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16); // Returns a chain & a flag for retval copy to use. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); SmallVector<SDValue, 8> Ops; Ops.push_back(Chain); Ops.push_back(Callee); // Add argument registers to the end of the list so that they are // known live into the call. for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) Ops.push_back(DAG.getRegister(RegsToPass[i].first, RegsToPass[i].second.getValueType())); if (InFlag.getNode()) Ops.push_back(InFlag); Chain = DAG.getNode(DCPU16ISD::CALL, dl, NodeTys, &Ops[0], Ops.size()); InFlag = Chain.getValue(1); // Create the CALLSEQ_END node. Chain = DAG.getCALLSEQ_END(Chain, DAG.getConstant(NumBytes, getPointerTy(), true), DAG.getConstant(0, getPointerTy(), true), InFlag); InFlag = Chain.getValue(1); // Handle result values, copying them out of physregs into vregs that we // return. return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, InVals); } /// LowerCallResult - Lower the result values of a call into the /// appropriate copies out of appropriate physical registers. /// SDValue DCPU16TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, DebugLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { // Assign locations to each value returned by this call. SmallVector<CCValAssign, 16> RVLocs; CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), getTargetMachine(), RVLocs, *DAG.getContext()); CCInfo.AnalyzeCallResult(Ins, RetCC_DCPU16); // Copy all of the result registers out of their specified physreg. for (unsigned i = 0; i != RVLocs.size(); ++i) { Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(), RVLocs[i].getValVT(), InFlag).getValue(1); InFlag = Chain.getValue(2); InVals.push_back(Chain.getValue(0)); } return Chain; } SDValue DCPU16TargetLowering::LowerShifts(SDValue Op, SelectionDAG &DAG) const { unsigned Opc = Op.getOpcode(); SDNode* N = Op.getNode(); EVT VT = Op.getValueType(); DebugLoc dl = N->getDebugLoc(); // Expand non-constant shifts to loops: if (!isa<ConstantSDNode>(N->getOperand(1))) switch (Opc) { default: llvm_unreachable("Invalid shift opcode!"); case ISD::SHL: return DAG.getNode(DCPU16ISD::SHL, dl, VT, N->getOperand(0), N->getOperand(1)); case ISD::SRA: return DAG.getNode(DCPU16ISD::SRA, dl, VT, N->getOperand(0), N->getOperand(1)); case ISD::SRL: return DAG.getNode(DCPU16ISD::SRL, dl, VT, N->getOperand(0), N->getOperand(1)); } uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); // Expand the stuff into sequence of shifts. // FIXME: for some shift amounts this might be done better! // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N SDValue Victim = N->getOperand(0); if (Opc == ISD::SRL && ShiftAmount) { // Emit a special goodness here: // srl A, 1 => clrc; rrc A Victim = DAG.getNode(DCPU16ISD::RRC, dl, VT, Victim); ShiftAmount -= 1; } while (ShiftAmount--) Victim = DAG.getNode((Opc == ISD::SHL ? DCPU16ISD::RLA : DCPU16ISD::RRA), dl, VT, Victim); return Victim; } SDValue DCPU16TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); // Create the TargetGlobalAddress node, folding in the constant offset. SDValue Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), getPointerTy(), Offset); return DAG.getNode(DCPU16ISD::Wrapper, Op.getDebugLoc(), getPointerTy(), Result); } SDValue DCPU16TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { DebugLoc dl = Op.getDebugLoc(); const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol(); SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy()); return DAG.getNode(DCPU16ISD::Wrapper, dl, getPointerTy(), Result); } SDValue DCPU16TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { DebugLoc dl = Op.getDebugLoc(); const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), /*isTarget=*/true); return DAG.getNode(DCPU16ISD::Wrapper, dl, getPointerTy(), Result); } static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC, ISD::CondCode CC, DebugLoc dl, SelectionDAG &DAG) { // FIXME: Handle bittests someday assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet"); // FIXME: Handle jump negative someday DCPU16CC::CondCodes TCC = DCPU16CC::COND_INVALID; switch (CC) { default: llvm_unreachable("Invalid integer condition!"); case ISD::SETEQ: TCC = DCPU16CC::COND_E; // aka COND_Z // Minor optimization: if LHS is a constant, swap operands, then the // constant can be folded into comparison. if (LHS.getOpcode() == ISD::Constant) std::swap(LHS, RHS); break; case ISD::SETNE: TCC = DCPU16CC::COND_NE; // aka COND_NZ // Minor optimization: if LHS is a constant, swap operands, then the // constant can be folded into comparison. if (LHS.getOpcode() == ISD::Constant) std::swap(LHS, RHS); break; case ISD::SETULE: std::swap(LHS, RHS); // FALLTHROUGH case ISD::SETUGE: // Turn lhs u>= rhs with lhs constant into rhs u< lhs+1, this allows us to // fold constant into instruction. if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) { LHS = RHS; RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0)); TCC = DCPU16CC::COND_LO; break; } TCC = DCPU16CC::COND_HS; // aka COND_C break; case ISD::SETUGT: std::swap(LHS, RHS); // FALLTHROUGH case ISD::SETULT: // Turn lhs u< rhs with lhs constant into rhs u>= lhs+1, this allows us to // fold constant into instruction. if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) { LHS = RHS; RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0)); TCC = DCPU16CC::COND_HS; break; } TCC = DCPU16CC::COND_LO; // aka COND_NC break; case ISD::SETLE: std::swap(LHS, RHS); // FALLTHROUGH case ISD::SETGE: // Turn lhs >= rhs with lhs constant into rhs < lhs+1, this allows us to // fold constant into instruction. if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) { LHS = RHS; RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0)); TCC = DCPU16CC::COND_L; break; } TCC = DCPU16CC::COND_GE; break; case ISD::SETGT: std::swap(LHS, RHS); // FALLTHROUGH case ISD::SETLT: // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to // fold constant into instruction. if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) { LHS = RHS; RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0)); TCC = DCPU16CC::COND_GE; break; } TCC = DCPU16CC::COND_L; break; } TargetCC = DAG.getConstant(TCC, MVT::i8); return DAG.getNode(DCPU16ISD::CMP, dl, MVT::Glue, LHS, RHS); } SDValue DCPU16TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { SDValue Chain = Op.getOperand(0); ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); SDValue LHS = Op.getOperand(2); SDValue RHS = Op.getOperand(3); SDValue Dest = Op.getOperand(4); DebugLoc dl = Op.getDebugLoc(); SDValue TargetCC; SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG); return DAG.getNode(DCPU16ISD::BR_CC, dl, Op.getValueType(), Chain, Dest, TargetCC, Flag); } SDValue DCPU16TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { SDValue LHS = Op.getOperand(0); SDValue RHS = Op.getOperand(1); DebugLoc dl = Op.getDebugLoc(); // If we are doing an AND and testing against zero, then the CMP // will not be generated. The AND (or BIT) will generate the condition codes, // but they are different from CMP. // FIXME: since we're doing a post-processing, use a pseudoinstr here, so // lowering & isel wouldn't diverge. bool andCC = false; if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { if (RHSC->isNullValue() && LHS.hasOneUse() && (LHS.getOpcode() == ISD::AND || (LHS.getOpcode() == ISD::TRUNCATE && LHS.getOperand(0).getOpcode() == ISD::AND))) { andCC = true; } } ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); SDValue TargetCC; SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG); // Get the condition codes directly from the status register, if its easy. // Otherwise a branch will be generated. Note that the AND and BIT // instructions generate different flags than CMP, the carry bit can be used // for NE/EQ. bool Invert = false; bool Shift = false; bool Convert = true; switch (cast<ConstantSDNode>(TargetCC)->getZExtValue()) { default: Convert = false; break; case DCPU16CC::COND_HS: // Res = SRW & 1, no processing is required break; case DCPU16CC::COND_LO: // Res = ~(SRW & 1) Invert = true; break; case DCPU16CC::COND_NE: if (andCC) { // C = ~Z, thus Res = SRW & 1, no processing is required } else { // Res = ~((SRW >> 1) & 1) Shift = true; Invert = true; } break; case DCPU16CC::COND_E: Shift = true; // C = ~Z for AND instruction, thus we can put Res = ~(SRW & 1), however, // Res = (SRW >> 1) & 1 is 1 word shorter. break; } EVT VT = Op.getValueType(); SDValue One = DAG.getConstant(1, VT); if (Convert) { SDValue SR = DAG.getCopyFromReg(DAG.getEntryNode(), dl, DCPU16::SRW, MVT::i16, Flag); if (Shift) // FIXME: somewhere this is turned into a SRL, lower it MSP specific? SR = DAG.getNode(ISD::SRA, dl, MVT::i16, SR, One); SR = DAG.getNode(ISD::AND, dl, MVT::i16, SR, One); if (Invert) SR = DAG.getNode(ISD::XOR, dl, MVT::i16, SR, One); return SR; } else { SDValue Zero = DAG.getConstant(0, VT); SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); SmallVector<SDValue, 4> Ops; Ops.push_back(One); Ops.push_back(Zero); Ops.push_back(TargetCC); Ops.push_back(Flag); return DAG.getNode(DCPU16ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size()); } } SDValue DCPU16TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { SDValue LHS = Op.getOperand(0); SDValue RHS = Op.getOperand(1); SDValue TrueV = Op.getOperand(2); SDValue FalseV = Op.getOperand(3); ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); DebugLoc dl = Op.getDebugLoc(); SDValue TargetCC; SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG); SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); SmallVector<SDValue, 4> Ops; Ops.push_back(TrueV); Ops.push_back(FalseV); Ops.push_back(TargetCC); Ops.push_back(Flag); return DAG.getNode(DCPU16ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size()); } SDValue DCPU16TargetLowering::LowerSIGN_EXTEND(SDValue Op, SelectionDAG &DAG) const { SDValue Val = Op.getOperand(0); EVT VT = Op.getValueType(); DebugLoc dl = Op.getDebugLoc(); assert(VT == MVT::i16 && "Only support i16 for now!"); return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val), DAG.getValueType(Val.getValueType())); } SDValue DCPU16TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const { MachineFunction &MF = DAG.getMachineFunction(); DCPU16MachineFunctionInfo *FuncInfo = MF.getInfo<DCPU16MachineFunctionInfo>(); int ReturnAddrIndex = FuncInfo->getRAIndex(); if (ReturnAddrIndex == 0) { // Set up a frame object for the return address. uint64_t SlotSize = TD->getPointerSize(); ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize, true); FuncInfo->setRAIndex(ReturnAddrIndex); } return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy()); } SDValue DCPU16TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const { MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); MFI->setReturnAddressIsTaken(true); unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); DebugLoc dl = Op.getDebugLoc(); if (Depth > 0) { SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); SDValue Offset = DAG.getConstant(TD->getPointerSize(), MVT::i16); return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), DAG.getNode(ISD::ADD, dl, getPointerTy(), FrameAddr, Offset), MachinePointerInfo(), false, false, false, 0); } // Just load the return address. SDValue RetAddrFI = getReturnAddressFrameIndex(DAG); return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), RetAddrFI, MachinePointerInfo(), false, false, false, 0); } SDValue DCPU16TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); MFI->setFrameAddressIsTaken(true); EVT VT = Op.getValueType(); DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, DCPU16::FPW, VT); while (Depth--) FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, MachinePointerInfo(), false, false, false, 0); return FrameAddr; } /// getPostIndexedAddressParts - returns true by value, base pointer and /// offset pointer and addressing mode by reference if this node can be /// combined with a load / store to form a post-indexed load / store. bool DCPU16TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { LoadSDNode *LD = cast<LoadSDNode>(N); if (LD->getExtensionType() != ISD::NON_EXTLOAD) return false; EVT VT = LD->getMemoryVT(); if (VT != MVT::i8 && VT != MVT::i16) return false; if (Op->getOpcode() != ISD::ADD) return false; if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { uint64_t RHSC = RHS->getZExtValue(); if ((VT == MVT::i16 && RHSC != 2) || (VT == MVT::i8 && RHSC != 1)) return false; Base = Op->getOperand(0); Offset = DAG.getConstant(RHSC, VT); AM = ISD::POST_INC; return true; } return false; } const char *DCPU16TargetLowering::getTargetNodeName(unsigned Opcode) const { switch (Opcode) { default: return NULL; case DCPU16ISD::RET_FLAG: return "DCPU16ISD::RET_FLAG"; case DCPU16ISD::RETI_FLAG: return "DCPU16ISD::RETI_FLAG"; case DCPU16ISD::RRA: return "DCPU16ISD::RRA"; case DCPU16ISD::RLA: return "DCPU16ISD::RLA"; case DCPU16ISD::RRC: return "DCPU16ISD::RRC"; case DCPU16ISD::CALL: return "DCPU16ISD::CALL"; case DCPU16ISD::Wrapper: return "DCPU16ISD::Wrapper"; case DCPU16ISD::BR_CC: return "DCPU16ISD::BR_CC"; case DCPU16ISD::CMP: return "DCPU16ISD::CMP"; case DCPU16ISD::SELECT_CC: return "DCPU16ISD::SELECT_CC"; case DCPU16ISD::SHL: return "DCPU16ISD::SHL"; case DCPU16ISD::SRA: return "DCPU16ISD::SRA"; } } bool DCPU16TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) return false; return (Ty1->getPrimitiveSizeInBits() > Ty2->getPrimitiveSizeInBits()); } bool DCPU16TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { if (!VT1.isInteger() || !VT2.isInteger()) return false; return (VT1.getSizeInBits() > VT2.getSizeInBits()); } bool DCPU16TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { // DCPU16 implicitly zero-extends 8-bit results in 16-bit registers. return 0 && Ty1->isIntegerTy(8) && Ty2->isIntegerTy(16); } bool DCPU16TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { // DCPU16 implicitly zero-extends 8-bit results in 16-bit registers. return 0 && VT1 == MVT::i8 && VT2 == MVT::i16; } //===----------------------------------------------------------------------===// // Other Lowering Code //===----------------------------------------------------------------------===// MachineBasicBlock* DCPU16TargetLowering::EmitShiftInstr(MachineInstr *MI, MachineBasicBlock *BB) const { MachineFunction *F = BB->getParent(); MachineRegisterInfo &RI = F->getRegInfo(); DebugLoc dl = MI->getDebugLoc(); const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo(); unsigned Opc; const TargetRegisterClass * RC; switch (MI->getOpcode()) { default: llvm_unreachable("Invalid shift opcode!"); case DCPU16::Shl8: Opc = DCPU16::SHL8r1; RC = DCPU16::GR8RegisterClass; break; case DCPU16::Shl16: Opc = DCPU16::SHL16r1; RC = DCPU16::GR16RegisterClass; break; case DCPU16::Sra8: Opc = DCPU16::SAR8r1; RC = DCPU16::GR8RegisterClass; break; case DCPU16::Sra16: Opc = DCPU16::SAR16r1; RC = DCPU16::GR16RegisterClass; break; case DCPU16::Srl8: Opc = DCPU16::SAR8r1c; RC = DCPU16::GR8RegisterClass; break; case DCPU16::Srl16: Opc = DCPU16::SAR16r1c; RC = DCPU16::GR16RegisterClass; break; } const BasicBlock *LLVM_BB = BB->getBasicBlock(); MachineFunction::iterator I = BB; ++I; // Create loop block MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB); F->insert(I, LoopBB); F->insert(I, RemBB); // Update machine-CFG edges by transferring all successors of the current // block to the block containing instructions after shift. RemBB->splice(RemBB->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)), BB->end()); RemBB->transferSuccessorsAndUpdatePHIs(BB); // Add adges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB BB->addSuccessor(LoopBB); BB->addSuccessor(RemBB); LoopBB->addSuccessor(RemBB); LoopBB->addSuccessor(LoopBB); unsigned ShiftAmtReg = RI.createVirtualRegister(DCPU16::GR8RegisterClass); unsigned ShiftAmtReg2 = RI.createVirtualRegister(DCPU16::GR8RegisterClass); unsigned ShiftReg = RI.createVirtualRegister(RC); unsigned ShiftReg2 = RI.createVirtualRegister(RC); unsigned ShiftAmtSrcReg = MI->getOperand(2).getReg(); unsigned SrcReg = MI->getOperand(1).getReg(); unsigned DstReg = MI->getOperand(0).getReg(); // BB: // cmp 0, N // je RemBB BuildMI(BB, dl, TII.get(DCPU16::CMP8ri)) .addReg(ShiftAmtSrcReg).addImm(0); BuildMI(BB, dl, TII.get(DCPU16::JCC)) .addMBB(RemBB) .addImm(DCPU16CC::COND_E); // LoopBB: // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB] // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB] // ShiftReg2 = shift ShiftReg // ShiftAmt2 = ShiftAmt - 1; BuildMI(LoopBB, dl, TII.get(DCPU16::PHI), ShiftReg) .addReg(SrcReg).addMBB(BB) .addReg(ShiftReg2).addMBB(LoopBB); BuildMI(LoopBB, dl, TII.get(DCPU16::PHI), ShiftAmtReg) .addReg(ShiftAmtSrcReg).addMBB(BB) .addReg(ShiftAmtReg2).addMBB(LoopBB); BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2) .addReg(ShiftReg); BuildMI(LoopBB, dl, TII.get(DCPU16::SUB8ri), ShiftAmtReg2) .addReg(ShiftAmtReg).addImm(1); BuildMI(LoopBB, dl, TII.get(DCPU16::JCC)) .addMBB(LoopBB) .addImm(DCPU16CC::COND_NE); // RemBB: // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB] BuildMI(*RemBB, RemBB->begin(), dl, TII.get(DCPU16::PHI), DstReg) .addReg(SrcReg).addMBB(BB) .addReg(ShiftReg2).addMBB(LoopBB); MI->eraseFromParent(); // The pseudo instruction is gone now. return RemBB; } MachineBasicBlock* DCPU16TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *BB) const { unsigned Opc = MI->getOpcode(); if (Opc == DCPU16::Shl8 || Opc == DCPU16::Shl16 || Opc == DCPU16::Sra8 || Opc == DCPU16::Sra16 || Opc == DCPU16::Srl8 || Opc == DCPU16::Srl16) return EmitShiftInstr(MI, BB); const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo(); DebugLoc dl = MI->getDebugLoc(); assert((Opc == DCPU16::Select16 || Opc == DCPU16::Select8) && "Unexpected instr type to insert"); // To "insert" a SELECT instruction, we actually have to insert the diamond // control-flow pattern. The incoming instruction knows the destination vreg // to set, the condition code register to branch on, the true/false values to // select between, and a branch opcode to use. const BasicBlock *LLVM_BB = BB->getBasicBlock(); MachineFunction::iterator I = BB; ++I; // thisMBB: // ... // TrueVal = ... // cmpTY ccX, r1, r2 // jCC copy1MBB // fallthrough --> copy0MBB MachineBasicBlock *thisMBB = BB; MachineFunction *F = BB->getParent(); MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB); F->insert(I, copy0MBB); F->insert(I, copy1MBB); // Update machine-CFG edges by transferring all successors of the current // block to the new block which will contain the Phi node for the select. copy1MBB->splice(copy1MBB->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)), BB->end()); copy1MBB->transferSuccessorsAndUpdatePHIs(BB); // Next, add the true and fallthrough blocks as its successors. BB->addSuccessor(copy0MBB); BB->addSuccessor(copy1MBB); BuildMI(BB, dl, TII.get(DCPU16::JCC)) .addMBB(copy1MBB) .addImm(MI->getOperand(3).getImm()); // copy0MBB: // %FalseValue = ... // # fallthrough to copy1MBB BB = copy0MBB; // Update machine-CFG edges BB->addSuccessor(copy1MBB); // copy1MBB: // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] // ... BB = copy1MBB; BuildMI(*BB, BB->begin(), dl, TII.get(DCPU16::PHI), MI->getOperand(0).getReg()) .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB) .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB); MI->eraseFromParent(); // The pseudo instruction is gone now. return BB; }
[ "imkrasin@gmail.com" ]
imkrasin@gmail.com
406912235a33cc2dc15f265c6cceb001312713de
f3e6fa8f406e57726b511540a64b4863228833ca
/segmentation/Caffe_Segmentation/src/caffe/layers/image_data_layer.cpp
214d8192566564c473f585ef106213e70735057a
[ "BSD-2-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
USCDataScience/cmu-fg-bg-similarity
acb2336db015d195e8db0eb80f30be080a59d1d8
d8fc9a53937551f7a052bc2c6f442bcc29ea2615
refs/heads/master
2023-09-04T07:30:56.714233
2020-04-20T04:40:15
2020-04-20T04:40:15
255,199,739
8
0
null
null
null
null
UTF-8
C++
false
false
5,332
cpp
#include <fstream> // NOLINT(readability/streams) #include <iostream> // NOLINT(readability/streams) #include <string> #include <utility> #include <vector> #include "caffe/data_layers.hpp" #include "caffe/layer.hpp" #include "caffe/util/io.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/util/rng.hpp" namespace caffe { template <typename Dtype> ImageDataLayer<Dtype>::~ImageDataLayer<Dtype>() { this->JoinPrefetchThread(); } template <typename Dtype> void ImageDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { const int new_height = this->layer_param_.image_data_param().new_height(); const int new_width = this->layer_param_.image_data_param().new_width(); CHECK((new_height == 0 && new_width == 0) || (new_height > 0 && new_width > 0)) << "Current implementation requires " "new_height and new_width to be set at the same time."; // Read the file with filenames and labels const string& source = this->layer_param_.image_data_param().source(); LOG(INFO) << "Opening file " << source; std::ifstream infile(source.c_str()); string filename; int label; while (infile >> filename >> label) { lines_.push_back(std::make_pair(filename, label)); } if (this->layer_param_.image_data_param().shuffle()) { // randomly shuffle data LOG(INFO) << "Shuffling data"; const unsigned int prefetch_rng_seed = caffe_rng_rand(); prefetch_rng_.reset(new Caffe::RNG(prefetch_rng_seed)); ShuffleImages(); } LOG(INFO) << "A total of " << lines_.size() << " images."; lines_id_ = 0; // Check if we would need to randomly skip a few data points if (this->layer_param_.image_data_param().rand_skip()) { unsigned int skip = caffe_rng_rand() % this->layer_param_.image_data_param().rand_skip(); LOG(INFO) << "Skipping first " << skip << " data points."; CHECK_GT(lines_.size(), skip) << "Not enough points to skip"; lines_id_ = skip; } // Read a data point, and use it to initialize the top blob. Datum datum; CHECK(ReadImageToDatum(lines_[lines_id_].first, lines_[lines_id_].second, new_height, new_width, &datum)); // image const int crop_size = this->layer_param_.transform_param().crop_size(); const int batch_size = this->layer_param_.image_data_param().batch_size(); if (crop_size > 0) { (*top)[0]->Reshape(batch_size, datum.channels(), crop_size, crop_size); this->prefetch_data_.Reshape(batch_size, datum.channels(), crop_size, crop_size); } else { (*top)[0]->Reshape(batch_size, datum.channels(), datum.height(), datum.width()); this->prefetch_data_.Reshape(batch_size, datum.channels(), datum.height(), datum.width()); } LOG(INFO) << "output data size: " << (*top)[0]->num() << "," << (*top)[0]->channels() << "," << (*top)[0]->height() << "," << (*top)[0]->width(); // label (*top)[1]->Reshape(batch_size, 1, 1, 1); this->prefetch_label_.Reshape(batch_size, 1, 1, 1); // datum size this->datum_channels_ = datum.channels(); this->datum_height_ = datum.height(); this->datum_width_ = datum.width(); this->datum_size_ = datum.channels() * datum.height() * datum.width(); } template <typename Dtype> void ImageDataLayer<Dtype>::ShuffleImages() { caffe::rng_t* prefetch_rng = static_cast<caffe::rng_t*>(prefetch_rng_->generator()); shuffle(lines_.begin(), lines_.end(), prefetch_rng); } // This function is used to create a thread that prefetches the data. template <typename Dtype> void ImageDataLayer<Dtype>::InternalThreadEntry() { Datum datum; CHECK(this->prefetch_data_.count()); Dtype* top_data = this->prefetch_data_.mutable_cpu_data(); Dtype* top_label = this->prefetch_label_.mutable_cpu_data(); ImageDataParameter image_data_param = this->layer_param_.image_data_param(); const int batch_size = image_data_param.batch_size(); const int new_height = image_data_param.new_height(); const int new_width = image_data_param.new_width(); // datum scales const int lines_size = lines_.size(); for (int item_id = 0; item_id < batch_size; ++item_id) { // get a blob CHECK_GT(lines_size, lines_id_); if (!ReadImageToDatum(lines_[lines_id_].first, lines_[lines_id_].second, new_height, new_width, &datum)) { continue; } if (this->layer_param_.transform_param().is_seg()) { this->data_transformer_.Transform(lines_id_, item_id, datum, this->mean_, top_data, /* resetLocData= */ false); // resetLocData is not required here because this layer is mostly used in training, where new images are // not being provided at the real time } else { // Apply transformations (mirror, crop...) to the data this->data_transformer_.Transform(item_id, datum, this->mean_, top_data); } top_label[item_id] = datum.label().Get(0); // go to the next iter lines_id_++; if (lines_id_ >= lines_size) { // We have reached the end. Restart from the first. DLOG(INFO) << "Restarting data prefetching from start."; lines_id_ = 0; if (this->layer_param_.image_data_param().shuffle()) { ShuffleImages(); } } } } INSTANTIATE_CLASS(ImageDataLayer); } // namespace caffe
[ "chris.a.mattmann@jpl.nasa.gov" ]
chris.a.mattmann@jpl.nasa.gov
b8f50d1f3caf751f93ceab44d568def8af44d7e0
939543a016b324fc6b273a4c0f3ed462f2a4eb3c
/SampleBaseStation/SampleBaseStation/UdpSocket.cpp
3474429367d5cae6897b9fe3b555b64174c8918f
[]
no_license
BadgerRoboticMiningTeam/Comms
51cf15753fbc0581749d1043dabb3c848b564b7f
e80f7d9939eab519b534c808eee74a8f9a3bb1a3
refs/heads/master
2021-01-12T17:08:18.909329
2017-03-28T14:11:30
2017-03-28T14:11:30
71,515,535
0
1
null
null
null
null
UTF-8
C++
false
false
2,096
cpp
#include "UdpSocket.hpp" #include <cstring> constexpr _socket_t INVALID_SOCKET_HANDLE = ((_socket_t)(-1)); UdpSocket::UdpSocket(int port) { this->port = port; this->isOpen = false; } UdpSocket::~UdpSocket() { if (this->isOpen) this->Close(); } bool UdpSocket::Open() { _socket_t sock_handle; struct sockaddr_in socket_addr; #ifdef _WIN32 WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) return false; #endif #ifdef _WIN32 #define OPEN_FAIL() { WSACleanup(); return false; } #else #define OPEN_FAIL() { return false; } #endif sock_handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock_handle == INVALID_SOCKET_HANDLE) OPEN_FAIL(); std::memset(&socket_addr, 0, sizeof(struct sockaddr_in)); socket_addr.sin_addr.s_addr = htonl(INADDR_ANY); socket_addr.sin_family = AF_INET; socket_addr.sin_port = htons(port); if (bind(sock_handle, (struct sockaddr *) &socket_addr, sizeof(struct sockaddr)) != 0) OPEN_FAIL(); this->handle = sock_handle; this->isOpen = true; return true; #undef OPEN_FAIL } void UdpSocket::Close() { if (!this->isOpen) return; this->isOpen = false; #ifdef _WIN32 closesocket(handle); #else close(handle); #endif } int UdpSocket::Write(const void *buffer, unsigned int size, struct sockaddr *dest_addr) { if (buffer == nullptr || dest_addr == nullptr) return -1; return sendto(handle, (const char *)buffer, size, 0, dest_addr, sizeof(struct sockaddr)); } int UdpSocket::Read(void *buffer, unsigned int size, struct sockaddr *source_addr) { socklen_t source_addr_size; if (buffer == nullptr) return -1; source_addr_size = sizeof(struct sockaddr); if (source_addr) return recvfrom(handle, (char *)buffer, size, 0, source_addr, &source_addr_size); else return recvfrom(handle, (char *)buffer, size, 0, nullptr, nullptr); } int UdpSocket::GetPort() const { return port; } bool UdpSocket::IsOpen() const { return this->isOpen; }
[ "wjen@wisc.edu" ]
wjen@wisc.edu
6f09f5635be528d9f1e704524abb734a49da8932
f1aaed1e27416025659317d1f679f7b3b14d654e
/MenuMate/MenuMate/Source/SmartCards/SmartCardAPI.h
2933cb71dd8198a534fc1cc6187b506f1979dd1f
[]
no_license
radtek/Pos
cee37166f89a7fcac61de9febb3760d12b823ce5
f117845e83b41d65f18a4635a98659144d66f435
refs/heads/master
2020-11-25T19:49:37.755286
2016-09-16T14:55:17
2016-09-16T14:55:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,528
h
// --------------------------------------------------------------------------- #ifndef SmartCardAPIH #define SmartCardAPIH #include "MM_DBCore.h" #include "Contact.h" #include "SystemEvents.h" #include "ContactPoints.h" #include "SmartCardDefs.h" #include "ManagerSyndCode.h" #include "SmartCardVer2API.h" #include "SmartCardVer3API.h" #include "SmartCardVer5API.h" #include "SmartCardVer6API.h" #include "SmartCardException.h" #include "MMMessageBox.h" /* Packet Block on card. 1 ) A block Length includes the CRC for corruption. 2 ) Data in brackets ()is encrypted. 3 ) ... Is padding out to Block Length - 2. .Card Ver Block. [Card Ver] .Customer Info Block. ([Customer Data][SYND CRC]...)[Coruption CRC] .Customer Points. ([Points][SYND CRC]...)[Coruption CRC] */ // --------------------------------------------------------------------------- class TManagerSmartCard { private: SCARDCONTEXT hCardContext; SCARDHANDLE hCard; BYTE VerificationCode[3]; std::map <int, TSyndCode> SyndCodes; AnsiString fCardReader; UnicodeString LastErrorMessage; int LastErrorCode; TSmartCardGUID TransactionCardGuid; void StartMonitoringThread(); void StopMonitoringThread(); bool VerifyFactoryCard(); bool VerifySyndicateCard(); void FormatCard(); LONG CardConnect(); void CardDisconnect(); LONG CardReadMainMemory(int BlockStart, int BlockEnd, TMemoryStream &Stream); LONG CardReadProtectedMemory(TMemoryStream &Stream); LONG CardReadSecurityMemory(TMemoryStream &Stream); bool CheckStreamCRC(TMemoryStream *Stream); // void Encrypt(TMemoryStream &InData); void Decrypt(TMemoryStream &InData, AnsiString SyndicateCode); void StreamGetVersion(TSmartCardBlock &CardBlock, TMemoryStream &Stream); void LoadCardBlock(TSmartCardBlock &CardBlock); std::auto_ptr <TSmartCard> SmartCard; bool CardReaderEventsActive; void Reset(); public: void Initialise(bool inUserEnabled , std::map <int, TSyndCode> inSyndCodes); UnicodeString LoadCardGUID(); bool CheckCorrectCard(TSmartCardGUID &SmartCardGUID); bool ContactInfoMatches(TMMContactInfo &inContactInfo); void SaveContactInfo(TMMContactInfo &inContactInfo); void SaveContactPoints(TContactPoints Points); void SaveCardGUID(TSmartCardGUID &CardGuid); int GetCardBlockVersion(TSmartCardBlock &CardBlock); void GetReaders(TStringList *ReaderList); void SetReader(UnicodeString inReaderName); bool CardInserted; bool CardBlank; bool CardOk; bool CardUnknown; bool CardCorrupt; bool CardSyndicate; bool CardFactory; bool CardUnreadable; bool Registered; bool Enabled; void SmartCardRemoved(); void SmartCardInserted(); void FormatCardToNewUser(); bool FormatCardToFactory(); void CardReaderEventsOn(); void CardReaderEventsOff(); // Card Reader Events TSystemEvents OnCardInserted; TSystemEvents OnCardRemoved; // Card Events. TSystemEvents OnNewCardInserted; TSystemEvents OnUnknownCardInserted; TSystemEvents OnUnableToDecodeCard; TSystemEvents OnCardUpdated; TSystemEvents OnCardCorrupt; TSystemEvents OnCardUnreadable; TSmartCardBlock *GetRestorePoint(); void GetSyndCodeInfo(TSyndCode &SyndCode); bool GetSyndCodeValid(); TSyndCode GetDefaultSyndCode(); const TSmartCardGUID *GetCardGUID(); void RestoreToRestorePoint(TSmartCardBlock &RestorePoint); void UpdateViewers(); TManagerSmartCard(); virtual ~TManagerSmartCard(); class TMonitoringThread : public TThread { public: TMonitoringThread(SCARDCONTEXT &hCardContext, UnicodeString infCardReader /* , TCardStatusChangedEvent OnCardStatusChanged */ ); void Cancel(); // Call if terminating the application while running! UnicodeString ErrorMsg; private: SCARDCONTEXT hCardContext; SCARD_READERSTATE fReaderState; UnicodeString fCardReader; void __fastcall Execute(); void __fastcall SetStatus(); }; TMonitoringThread *fMonitoringThread; /* Used be the Calling programs to "lock in a card". If the card changes between transaction calls any writes to the card fails. */ void BeginTransaction(); void EndTransaction(); GetContactInfo(TMMContactInfo & ContactInfo); // void __fastcall fMonitoringThreadTerminate(TObject *Sender); bool UpgradeCardToVersion(int version, int newVersion, std::map <int, TSyndCode> SyndCodes, bool cardUnlocked = false); int GetCurrentCardVersion(); TSyndCode GetCurrentSyndicateCode(); }; #endif
[ "ravish.sharma@menumate.com" ]
ravish.sharma@menumate.com
5bdbc0640801ba3f34800dcc5bc09169d3a72865
8ff320e31e8ad83c75c93cd8f71347a38e718e71
/src/lib/Basic/status.cpp
b3d6bb4a40fb037cd741cd0d1417cc857561493d
[]
no_license
tavu/karakaxa
60ff6e3e79196f5a3e079c5dc1cc1c430d9ff1be
03f3df0f22a6a001438589d72c42c34a3f3dd519
refs/heads/master
2021-01-01T18:22:49.392260
2013-09-04T13:42:02
2013-09-04T13:42:02
4,357,814
2
0
null
null
null
null
UTF-8
C++
false
false
758
cpp
#include"status.h" #include<QDebug> Basic::status::status() { } void Basic::status::error(const QString& s) { emit errorMessage(s); } void Basic::status::logErr(const QString& s) { qDebug()<<"[ERR] "<<s; } void Basic::status::info(const QString& s) { emit infoMessage(s); } void Basic::status::logInfo(const QString& s) { qDebug()<<"[INF] "<<s; } void Basic::status::init() { if(_instance==0) { _instance=new status(); } } void Basic::status::cleanUp() { if(_instance!=0) { delete _instance; } _instance=0; } Basic::status* Basic::status::instance() { return _instance; } Basic::status* Basic::status::_instance=0; Basic::status* Basic::msg() { return status::instance(); }
[ "tavu@linux-t06i.site" ]
tavu@linux-t06i.site
0acff8625d077189314db75bd0be6539d7c10415
a8fc76656166b3ccd46a0c276febb1a31bb71cc3
/mgmt.cpp
bc6677df88fe4cd19236285c69d57deb3b0f1e2c
[]
no_license
benwu232/agre
7693cb0ab89d13e0af92d3b1d49f1ca65cb24437
b7ea96319893e4bc05ac2e733a4fba3ccf6856c7
refs/heads/master
2016-09-06T02:21:19.202674
2013-04-20T12:48:55
2013-04-20T12:48:55
9,562,356
2
0
null
null
null
null
UTF-8
C++
false
false
2,248
cpp
#include <QString> #include <QMessageBox> #include <QtDebug> #include <QDir> #include "mgmt.h" #include <qdatetime.h> extern void WiimoteRun(); CMgmt::CMgmt(QString HomeDir) { //CMgmt(); TrIdx = 0; UserDirName = "user/"; UserDirPath = HomeDir + UserDirName; UserDir = QDir(UserDirPath); if (!UserDir.exists()) UserDir.mkpath(UserDir.absolutePath()); TemplateDir = QDir(HomeDir + "template"); if (!TemplateDir.exists()) TemplateDir.mkpath(TemplateDir.absolutePath()); ImageDir = QDir(HomeDir + "image"); if (!ImageDir.exists()) ImageDir.mkpath(ImageDir.absolutePath()); GestureDir = QDir(HomeDir + "gesture"); if (!GestureDir.exists()) GestureDir.mkpath(GestureDir.absolutePath()); } void CMgmt::GenUserList() { //qDebug("into GenUserList"); //if (!UserDir.exists()) //UserDir.mkpath(UserDir.absolutePath()); if (!UserDir.cd(UserDir.absolutePath())) qDebug("Error: Can't go into UserDir!"); UserList = UserDir.entryList(QDir::Dirs); // Remove '.' and '..' UserList.removeAt(0); UserList.removeAt(0); //return UserList; //UserDir = //qDebug("UserDirName = %s", UserDirName); //qDebug()<<"UserDirName ="<<UserDirName; /* QMessageBox::warning(this, "Message!", UserDirName, QMessageBox::Ok, QMessageBox::Ok);*/ //QMessageBox::information(this,"Quit...","Really Quit?",QMessageBox::Ok,QMessageBox::Cancel); } QStringList& CMgmt::GetUserList() { return UserList; } void CMgmt::AddUser(const QString& UserName) { UserDir.cd(UserDir.absolutePath()); UserDir.mkdir(UserName); UserDir.cd(UserName); UserDir.mkdir("training"); UserDir.mkdir("recognizing"); UserDir.cdUp(); } void CMgmt::SetCurUser(QString User) { CurUser = User; } QString& CMgmt::GetCurUser() { return CurUser; } QDir& CMgmt::GetUserDir() { return UserDir; } QDir& CMgmt::GetTemplateDir() { return TemplateDir; } QDir& CMgmt::GetImageDir() { return ImageDir; } QDir& CMgmt::GetGestureDir() { return GestureDir; } void CDataPro::run() { WiimoteRun(); }
[ "benwu232@gmail.com" ]
benwu232@gmail.com
f3df8ae5374e585b9c217824dddbb9069e0b7839
569ae08ce03206bc7afcf8e48b0c74d89525735e
/lib/skia/type_converters.h
36b98228c9b702e3ce0cf6e70b0a0edbb4f14b5b
[ "BSD-3-Clause" ]
permissive
rzel/mozart
77ef8bc73697a19a9c2296950fe64ad4fb3d7552
f97aaccd05f79f115e85ca47330452e485623357
refs/heads/master
2021-01-12T14:09:48.789400
2016-09-30T23:43:54
2016-09-30T23:43:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,613
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef APPS_MOZART_LIB_SKIA_TYPE_CONVERTERS_H_ #define APPS_MOZART_LIB_SKIA_TYPE_CONVERTERS_H_ #include "mojo/public/cpp/bindings/type_converter.h" #include "mojo/services/geometry/interfaces/geometry.mojom.h" #include "third_party/skia/include/core/SkMatrix.h" #include "third_party/skia/include/core/SkMatrix44.h" #include "third_party/skia/include/core/SkPoint.h" #include "third_party/skia/include/core/SkRRect.h" #include "third_party/skia/include/core/SkRect.h" // The TypeConverter template is defined in the mojo namespace. namespace mojo { template <> struct TypeConverter<SkIPoint, mojo::Point> { static SkIPoint Convert(const mojo::Point& input); }; template <> struct TypeConverter<mojo::Point, SkIPoint> { static mojo::Point Convert(const SkIPoint& input); }; template <> struct TypeConverter<SkPoint, mojo::PointF> { static SkPoint Convert(const mojo::PointF& input); }; template <> struct TypeConverter<mojo::PointF, SkPoint> { static mojo::PointF Convert(const SkPoint& input); }; template <> struct TypeConverter<SkIRect, mojo::Rect> { static SkIRect Convert(const mojo::Rect& input); }; template <> struct TypeConverter<mojo::Rect, SkIRect> { static mojo::Rect Convert(const SkIRect& input); }; template <> struct TypeConverter<SkRect, mojo::RectF> { static SkRect Convert(const mojo::RectF& input); }; template <> struct TypeConverter<mojo::RectF, SkRect> { static mojo::RectF Convert(const SkRect& input); }; template <> struct TypeConverter<SkRRect, mojo::RRectF> { static SkRRect Convert(const mojo::RRectF& input); }; template <> struct TypeConverter<mojo::RRectF, SkRRect> { static mojo::RRectF Convert(const SkRRect& input); }; // Note: This transformation is lossy since Transform is 4x4 whereas // SkMatrix is only 3x3 so we drop the 3rd row and column. template <> struct TypeConverter<SkMatrix, mojo::TransformPtr> { static SkMatrix Convert(const mojo::TransformPtr& input); }; template <> struct TypeConverter<mojo::TransformPtr, SkMatrix> { static mojo::TransformPtr Convert(const SkMatrix& input); }; // Note: This transformation is lossless. template <> struct TypeConverter<SkMatrix44, mojo::TransformPtr> { static SkMatrix44 Convert(const mojo::TransformPtr& input); }; template <> struct TypeConverter<mojo::TransformPtr, SkMatrix44> { static mojo::TransformPtr Convert(const SkMatrix44& input); }; } // namespace mojo #endif // APPS_MOZART_LIB_SKIA_TYPE_CONVERTERS_H_
[ "jeffbrown@google.com" ]
jeffbrown@google.com
a4cf85022bc103078155da64a732582b7e86ce1a
24f26275ffcd9324998d7570ea9fda82578eeb9e
/extensions/browser/image_sanitizer.cc
861355aa8e5daf3b66a2e3ab1cb8ba9e8b06fe12
[ "BSD-3-Clause" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
8,866
cc
// Copyright 2018 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 "extensions/browser/image_sanitizer.h" #include "base/bind.h" #include "base/files/file_util.h" #include "base/task_runner_util.h" #include "extensions/browser/extension_file_task_runner.h" #include "extensions/common/extension_resource_path_normalizer.h" #include "services/service_manager/public/cpp/connector.h" #include "ui/gfx/codec/png_codec.h" namespace extensions { namespace { // We don't expect icons and other extension's images to be big. // We use this limit to prevent from opening too large images. const int kMaxImageCanvas = 4096 * 4096; // 16MB // Reads the file in |path| and then deletes it. // Returns a tuple containing: the file content, whether the read was // successful, whether the delete was successful. std::tuple<std::vector<uint8_t>, bool, bool> ReadAndDeleteBinaryFile( const base::FilePath& path) { std::vector<uint8_t> contents; bool read_success = false; int64_t file_size; if (base::GetFileSize(path, &file_size)) { contents.resize(file_size); read_success = base::ReadFile(path, reinterpret_cast<char*>(contents.data()), file_size) == file_size; } bool delete_success = base::DeleteFile(path, /*recursive=*/false); return std::make_tuple(std::move(contents), read_success, delete_success); } std::pair<bool, std::vector<unsigned char>> EncodeImage(const SkBitmap& image) { std::vector<unsigned char> image_data; bool success = gfx::PNGCodec::EncodeBGRASkBitmap( image, /*discard_transparency=*/false, &image_data); return std::make_pair(success, std::move(image_data)); } int WriteFile(const base::FilePath& path, const std::vector<unsigned char>& data) { return base::WriteFile(path, reinterpret_cast<const char*>(data.data()), base::checked_cast<int>(data.size())); } } // namespace // static std::unique_ptr<ImageSanitizer> ImageSanitizer::CreateAndStart( service_manager::Connector* connector, const service_manager::ServiceFilter& service_filter, const base::FilePath& image_dir, const std::set<base::FilePath>& image_paths, ImageDecodedCallback image_decoded_callback, SanitizationDoneCallback done_callback) { std::unique_ptr<ImageSanitizer> sanitizer(new ImageSanitizer( image_dir, image_paths, std::move(image_decoded_callback), std::move(done_callback))); sanitizer->Start(connector, service_filter); return sanitizer; } ImageSanitizer::ImageSanitizer( const base::FilePath& image_dir, const std::set<base::FilePath>& image_relative_paths, ImageDecodedCallback image_decoded_callback, SanitizationDoneCallback done_callback) : image_dir_(image_dir), image_paths_(image_relative_paths), image_decoded_callback_(std::move(image_decoded_callback)), done_callback_(std::move(done_callback)) {} ImageSanitizer::~ImageSanitizer() = default; void ImageSanitizer::Start( service_manager::Connector* connector, const service_manager::ServiceFilter& service_filter) { if (image_paths_.empty()) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&ImageSanitizer::ReportSuccess, weak_factory_.GetWeakPtr())); return; } connector->Connect(service_filter, image_decoder_.BindNewPipeAndPassReceiver()); image_decoder_.set_disconnect_handler( base::BindOnce(&ImageSanitizer::ReportError, weak_factory_.GetWeakPtr(), Status::kServiceError, base::FilePath())); std::set<base::FilePath> normalized_image_paths; for (const base::FilePath& path : image_paths_) { // Normalize paths as |image_paths_| can contain duplicates like "icon.png" // and "./icon.png" to avoid unpacking the same image twice. base::FilePath normalized_path; if (path.IsAbsolute() || path.ReferencesParent() || !NormalizeExtensionResourcePath(path, &normalized_path)) { // Report the error asynchronously so the caller stack has chance to // unwind. base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&ImageSanitizer::ReportError, weak_factory_.GetWeakPtr(), Status::kImagePathError, path)); return; } normalized_image_paths.insert(normalized_path); } // Update |image_paths_| as some of the path might have been changed by // normalization. image_paths_ = std::move(normalized_image_paths); // Note that we use 2 for loops instead of one to prevent a race and flakyness // in tests: if |image_paths_| contains 2 paths, a valid one that points to a // file that does not exist and an invalid one, there is a race that can cause // either error to be reported (kImagePathError or kFileReadError). for (const base::FilePath& path : image_paths_) { base::FilePath full_image_path = image_dir_.Append(path); base::PostTaskAndReplyWithResult( extensions::GetExtensionFileTaskRunner().get(), FROM_HERE, base::BindOnce(&ReadAndDeleteBinaryFile, full_image_path), base::BindOnce(&ImageSanitizer::ImageFileRead, weak_factory_.GetWeakPtr(), path)); } } void ImageSanitizer::ImageFileRead( const base::FilePath& image_path, std::tuple<std::vector<uint8_t>, bool, bool> read_and_delete_result) { if (!std::get<1>(read_and_delete_result)) { ReportError(Status::kFileReadError, image_path); return; } if (!std::get<2>(read_and_delete_result)) { ReportError(Status::kFileDeleteError, image_path); return; } const std::vector<uint8_t>& image_data = std::get<0>(read_and_delete_result); image_decoder_->DecodeImage( image_data, data_decoder::mojom::ImageCodec::DEFAULT, /*shrink_to_fit=*/false, kMaxImageCanvas, gfx::Size(), base::BindOnce(&ImageSanitizer::ImageDecoded, weak_factory_.GetWeakPtr(), image_path)); } void ImageSanitizer::ImageDecoded(const base::FilePath& image_path, const SkBitmap& decoded_image) { if (decoded_image.isNull()) { ReportError(Status::kDecodingError, image_path); return; } if (image_decoded_callback_) image_decoded_callback_.Run(image_path, decoded_image); // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even // though they may originally be .jpg, etc. Figure something out. // http://code.google.com/p/chromium/issues/detail?id=12459 base::PostTaskAndReplyWithResult( extensions::GetExtensionFileTaskRunner().get(), FROM_HERE, base::BindOnce(&EncodeImage, decoded_image), base::BindOnce(&ImageSanitizer::ImageReencoded, weak_factory_.GetWeakPtr(), image_path)); } void ImageSanitizer::ImageReencoded( const base::FilePath& image_path, std::pair<bool, std::vector<unsigned char>> result) { bool success = result.first; std::vector<unsigned char> image_data = std::move(result.second); if (!success) { ReportError(Status::kEncodingError, image_path); return; } int size = base::checked_cast<int>(image_data.size()); base::PostTaskAndReplyWithResult( extensions::GetExtensionFileTaskRunner().get(), FROM_HERE, base::BindOnce(&WriteFile, image_dir_.Append(image_path), std::move(image_data)), base::BindOnce(&ImageSanitizer::ImageWritten, weak_factory_.GetWeakPtr(), image_path, size)); } void ImageSanitizer::ImageWritten(const base::FilePath& image_path, int expected_size, int actual_size) { if (expected_size != actual_size) { ReportError(Status::kFileWriteError, image_path); return; } // We have finished with this path. size_t removed_count = image_paths_.erase(image_path); DCHECK_EQ(1U, removed_count); if (image_paths_.empty()) { // This was the last path, we are done. ReportSuccess(); } } void ImageSanitizer::ReportSuccess() { CleanUp(); std::move(done_callback_).Run(Status::kSuccess, base::FilePath()); } void ImageSanitizer::ReportError(Status status, const base::FilePath& path) { CleanUp(); // Prevent any other task from reporting, we want to notify only once. weak_factory_.InvalidateWeakPtrs(); std::move(done_callback_).Run(status, path); } void ImageSanitizer::CleanUp() { image_decoder_.reset(); // It's important to clear the repeating callback as it may cause a circular // reference (the callback holds a ref to an object that has a ref to |this|) // that would cause a leak. image_decoded_callback_.Reset(); } } // namespace extensions
[ "rjkroege@chromium.org" ]
rjkroege@chromium.org
b3e8432d6c2255ea3b003c12643069d0abf5fc95
6d56b944956ef43477ff2399a0d56d96aa507ed7
/Source/Main/Main/T_pool.cpp
89d8e3f6cd22f765b4fd0e1bf89ff3a96ebfeb05
[]
no_license
koe22kr/T_Pool
7decc0dd6cf52e11350469591a8e716868dd4c51
d3b5cefb51f7b55147d5cdc5dca71c0115c14e0f
refs/heads/master
2022-07-25T18:38:35.931987
2020-05-20T10:25:59
2020-05-20T10:25:59
260,671,888
0
1
null
null
null
null
UTF-8
C++
false
false
20
cpp
#include "T_pool.h"
[ "50091267+seoaplo@users.noreply.github.com" ]
50091267+seoaplo@users.noreply.github.com
acfcaa2f81ead05b6b9f3d44b8934892a8ba114d
9ab722e6b9e4ce741cc6f865ba97e0fdc0ad14e5
/library/ui_base/win/shell.cpp
af883c2997b62ef7fd4ff4bffa44042ad9b3e5cf
[ "MIT" ]
permissive
csjy309450/PuTTY-ng
b892c6474c8ff797f1d0bf555b08351da4fe617b
0af73729d45d51936810f675d481c47e5588407b
refs/heads/master
2022-12-24T13:31:22.786842
2020-03-08T16:53:51
2020-03-08T16:53:51
296,880,184
1
0
MIT
2020-09-19T13:54:25
2020-09-19T13:54:24
null
UTF-8
C++
false
false
4,144
cpp
#include "shell.h" #include <shellapi.h> #include <shlobj.h> #include "base/file_path.h" #include "base/native_library.h" #include "base/win/scoped_comptr.h" #include "base/win/win_util.h" #include "base/win/windows_version.h" namespace ui { namespace win { namespace { const wchar_t kShell32[] = L"shell32.dll"; const char kSHGetPropertyStoreForWindow[] = "SHGetPropertyStoreForWindow"; // Define the type of SHGetPropertyStoreForWindow is SHGPSFW. typedef DECLSPEC_IMPORT HRESULT (STDAPICALLTYPE *SHGPSFW)(HWND hwnd, REFIID riid, void** ppv); } // Open an item via a shell execute command. Error code checking and casting // explanation: http://msdn2.microsoft.com/en-us/library/ms647732.aspx bool OpenItemViaShell(const FilePath& full_path) { HINSTANCE h = ::ShellExecuteW( NULL, NULL, full_path.value().c_str(), NULL, full_path.DirName().value().c_str(), SW_SHOWNORMAL); LONG_PTR error = reinterpret_cast<LONG_PTR>(h); if(error > 32) { return true; } if((error == SE_ERR_NOASSOC)) { return OpenItemWithExternalApp(full_path.value()); } return false; } bool OpenItemViaShellNoZoneCheck(const FilePath& full_path) { SHELLEXECUTEINFO sei = { sizeof(sei) }; sei.fMask = SEE_MASK_NOZONECHECKS | SEE_MASK_FLAG_DDEWAIT; sei.nShow = SW_SHOWNORMAL; sei.lpVerb = NULL; sei.lpFile = full_path.value().c_str(); if(::ShellExecuteExW(&sei)) { return true; } LONG_PTR error = reinterpret_cast<LONG_PTR>(sei.hInstApp); if((error == SE_ERR_NOASSOC)) { return OpenItemWithExternalApp(full_path.value()); } return false; } // Show the Windows "Open With" dialog box to ask the user to pick an app to // open the file with. bool OpenItemWithExternalApp(const string16& full_path) { SHELLEXECUTEINFO sei = { sizeof(sei) }; sei.fMask = SEE_MASK_FLAG_DDEWAIT; sei.nShow = SW_SHOWNORMAL; sei.lpVerb = L"openas"; sei.lpFile = full_path.c_str(); return (TRUE == ::ShellExecuteExW(&sei)); } void SetAppIdForWindow(const string16& app_id, HWND hwnd) { // This functionality is only available on Win7+. if(base::win::GetVersion() < base::win::VERSION_WIN7) { return; } // Load Shell32.dll into memory. // TODO(brg): Remove this mechanism when the Win7 SDK is available in trunk. std::wstring shell32_filename(kShell32); FilePath shell32_filepath(shell32_filename); base::NativeLibrary shell32_library = base::LoadNativeLibrary(shell32_filepath); if(!shell32_library) { return; } // Get the function pointer for SHGetPropertyStoreForWindow. void* function = base::GetFunctionPointerFromNativeLibrary( shell32_library, kSHGetPropertyStoreForWindow); if(!function) { base::UnloadNativeLibrary(shell32_library); return; } // Set the application's name. base::win::ScopedComPtr<IPropertyStore> pps; SHGPSFW SHGetPropertyStoreForWindow = static_cast<SHGPSFW>(function); HRESULT result = SHGetPropertyStoreForWindow( hwnd, __uuidof(*pps), reinterpret_cast<void**>(pps.Receive())); if(S_OK == result) { base::win::SetAppIdForPropertyStore(pps, app_id.c_str()); } // Cleanup. base::UnloadNativeLibrary(shell32_library); } } //namespace win } //namespace ui
[ "wlwlxj@gmail.com@b2b8c3b8-ce47-b78c-ec54-380d862a5473" ]
wlwlxj@gmail.com@b2b8c3b8-ce47-b78c-ec54-380d862a5473
b2c484b1bdc99e7ba796228d13fb7de5c8578973
6abb92d99ff4218866eafab64390653addbf0d64
/AtCoder/arc/arc014/c.cpp
1f64aa8e573b6c3bb1feeda1921dee47f7beff79
[]
no_license
Johannyjm/c-pro
38a7b81aff872b2246e5c63d6e49ef3dfb0789ae
770f2ac419b31bb0d47c4ee93c717c0c98c1d97d
refs/heads/main
2023-08-18T01:02:23.761499
2023-08-07T15:13:58
2023-08-07T15:13:58
217,938,272
0
0
null
2023-06-25T15:11:37
2019-10-28T00:51:09
C++
UTF-8
C++
false
false
431
cpp
#include <iostream> #include <string> #include <vector> using namespace std; int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); int n; cin >> n; string s; cin >> s; vector<int> cnt(3, 0); for(int i = 0; i < n; ++i){ if(s[i] == 'R') ++cnt[0]; else if(s[i] == 'G') ++cnt[1]; else ++cnt[2]; } cout << cnt[0]%2 + cnt[1]%2 + cnt[2]%2 << endl; return 0; }
[ "meetpastarts@gmail.com" ]
meetpastarts@gmail.com
5dfecab5457f081b9618bf420bebb38f58e44b05
cfceffb372a31d6bec816857d4310c4224543995
/Übung 8/src/math/Matrix.cpp
314aef933722a4ac5145f1daa5a4c2716859cd0c
[]
no_license
themightyoarfish/intro-to-c
f7ad417f3b30413caace0324430577f8d297b106
27bdd1f69a7f6919c780a325c311cc6776736ca6
refs/heads/master
2021-01-10T02:28:47.859425
2015-01-18T12:05:56
2015-01-18T12:05:56
47,020,894
0
1
null
2018-11-14T17:06:29
2015-11-28T11:31:28
C++
UTF-8
C++
false
false
11,658
cpp
/* * Matrix.hpp * * @date 26.08.2008 * @author Thomas Wiemann (twiemann@uos.de) */ #include "Matrix.hpp" namespace asteroids { Matrix::Matrix() { for(int i = 0; i < 16; i++) m[i] = 0; m[0] = m[5] = m[10] = m[15] = 1; } Matrix::Matrix(float* matrix) { for(int i = 0; i < 16; i++) m[i] = matrix[i]; } Matrix::Matrix(const Matrix& other) { for(int i = 0; i < 16; i++) m[i] = other[i]; } Matrix::Matrix(Vertex axis, float angle) { // Check for gimbal lock if(fabs(angle) < 0.0001) { bool invert_z = axis.z < 0; //Angle to yz-plane float pitch = atan2(axis.z, axis.x) - M_PI_2; if(pitch < 0.0f) pitch += 2.0f * M_PI; if(axis.x == 0.0f && axis.z == 0.0) pitch = 0.0f; //Transform axis into yz-plane axis.x = axis.x * cos(pitch) + axis.z * sin(pitch); axis.z = -axis.x * sin(pitch) + axis.z * cos(pitch); //Angle to y-Axis float yaw = atan2(axis.y, axis.z); if(yaw < 0) yaw += 2 * M_PI; Matrix m1, m2, m3; if(invert_z) yaw = -yaw; cout << "YAW: " << yaw << " PITCH: " << pitch << endl; if(fabs(yaw) > 0.0001){ m2 = Matrix(Vertex(1.0, 0.0, 0.0), yaw); m3 = m3 * m2; } if(fabs(pitch) > 0.0001){ m1 = Matrix(Vertex(0.0, 1.0, 0.0), pitch); m3 = m3 * m1; } for(int i = 0; i < 16; i++) m[i] = m3[i]; } else { float c = cos(angle); float s = sin(angle); float t = 1.0f - c; float tmp1, tmp2; // Normalize axis Vertex a(axis); a.normalize(); m[ 0] = c + a.x * a.x * t; m[ 5] = c + a.y * a.y * t; m[10] = c + a.z * a.z * t; tmp1 = a.x * a.y * t; tmp2 = a.z * s; m[ 4] = tmp1 + tmp2; m[ 1] = tmp1 - tmp2; tmp1 = a.x * a.z * t; tmp2 = a.y * s; m[ 8] = tmp1 - tmp2; m[ 2] = tmp1 + tmp2; tmp1 = a.y * a.z * t; tmp2 = a.x * s; m[ 9] = tmp1 + tmp2; m[ 6] = tmp1 - tmp2; m[ 3] = m[ 7] = m[11] = 0.0; m[12] = m[13] = m[14] = 0.0; m[15] = 1.0; } } Matrix::Matrix(const Vertex &position, const Vertex &angles) { float sx = sin(angles[0]); float cx = cos(angles[0]); float sy = sin(angles[1]); float cy = cos(angles[1]); float sz = sin(angles[2]); float cz = cos(angles[2]); m[0] = cy*cz; m[1] = sx*sy*cz + cx*sz; m[2] = -cx*sy*cz + sx*sz; m[3] = 0.0; m[4] = -cy*sz; m[5] = -sx*sy*sz + cx*cz; m[6] = cx*sy*sz + sx*cz; m[7] = 0.0; m[8] = sy; m[9] = -sx*cy; m[10] = cx*cy; m[11] = 0.0; m[12] = position[0]; m[13] = position[1]; m[14] = position[2]; m[15] = 1; } Matrix::~Matrix() { } Matrix Matrix::operator*(const float &scale) const { float new_matrix[16]; for(int i = 0; i < 16; i++){ new_matrix[i] = m[i] * scale; } return Matrix(new_matrix); } Matrix Matrix::operator*(const Matrix &other) const { float new_matrix[16]; new_matrix[ 0] = m[ 0] * other[ 0] + m[ 4] * other[ 1] + m[ 8] * other[ 2] + m[12] * other[ 3]; new_matrix[ 1] = m[ 1] * other[ 0] + m[ 5] * other[ 1] + m[ 9] * other[ 2] + m[13] * other[ 3]; new_matrix[ 2] = m[ 2] * other[ 0] + m[ 6] * other[ 1] + m[10] * other[ 2] + m[14] * other[ 3]; new_matrix[ 3] = m[ 3] * other[ 0] + m[ 7] * other[ 1] + m[11] * other[ 2] + m[15] * other[ 3]; new_matrix[ 4] = m[ 0] * other[ 4] + m[ 4] * other[ 5] + m[ 8] * other[ 6] + m[12] * other[ 7]; new_matrix[ 5] = m[ 1] * other[ 4] + m[ 5] * other[ 5] + m[ 9] * other[ 6] + m[13] * other[ 7]; new_matrix[ 6] = m[ 2] * other[ 4] + m[ 6] * other[ 5] + m[10] * other[ 6] + m[14] * other[ 7]; new_matrix[ 7] = m[ 3] * other[ 4] + m[ 7] * other[ 5] + m[11] * other[ 6] + m[15] * other[ 7]; new_matrix[ 8] = m[ 0] * other[ 8] + m[ 4] * other[ 9] + m[ 8] * other[10] + m[12] * other[11]; new_matrix[ 9] = m[ 1] * other[ 8] + m[ 5] * other[ 9] + m[ 9] * other[10] + m[13] * other[11]; new_matrix[10] = m[ 2] * other[ 8] + m[ 6] * other[ 9] + m[10] * other[10] + m[14] * other[11]; new_matrix[11] = m[ 3] * other[ 8] + m[ 7] * other[ 9] + m[11] * other[10] + m[15] * other[11]; new_matrix[12] = m[ 0] * other[12] + m[ 4] * other[13] + m[ 8] * other[14] + m[12] * other[15]; new_matrix[13] = m[ 1] * other[12] + m[ 5] * other[13] + m[ 9] * other[14] + m[13] * other[15]; new_matrix[14] = m[ 2] * other[12] + m[ 6] * other[13] + m[10] * other[14] + m[14] * other[15]; new_matrix[15] = m[ 3] * other[12] + m[ 7] * other[13] + m[11] * other[14] + m[15] * other[15]; return Matrix(new_matrix); } /** * @brief Matrix addition operator. Returns a new matrix * */ Matrix Matrix::operator+(const Matrix &other) const { float new_matrix[16]; for(int i = 0; i < 16; i++) { new_matrix[i] = m[i] + other[i]; } return Matrix(new_matrix); } Matrix Matrix::operator+=(const Matrix &other) { return *this + other; } Matrix Matrix::operator*(const float* &other) const { float new_matrix[16]; new_matrix[ 0] = m[ 0] * other[ 0] + m[ 4] * other[ 1] + m[ 8] * other[ 2] + m[12] * other[ 3]; new_matrix[ 1] = m[ 1] * other[ 0] + m[ 5] * other[ 1] + m[ 9] * other[ 2] + m[13] * other[ 3]; new_matrix[ 2] = m[ 2] * other[ 0] + m[ 6] * other[ 1] + m[10] * other[ 2] + m[14] * other[ 3]; new_matrix[ 3] = m[ 3] * other[ 0] + m[ 7] * other[ 1] + m[11] * other[ 2] + m[15] * other[ 3]; new_matrix[ 4] = m[ 0] * other[ 4] + m[ 4] * other[ 5] + m[ 8] * other[ 6] + m[12] * other[ 7]; new_matrix[ 5] = m[ 1] * other[ 4] + m[ 5] * other[ 5] + m[ 9] * other[ 6] + m[13] * other[ 7]; new_matrix[ 6] = m[ 2] * other[ 4] + m[ 6] * other[ 5] + m[10] * other[ 6] + m[14] * other[ 7]; new_matrix[ 7] = m[ 3] * other[ 4] + m[ 7] * other[ 5] + m[11] * other[ 6] + m[15] * other[ 7]; new_matrix[ 8] = m[ 0] * other[ 8] + m[ 4] * other[ 9] + m[ 8] * other[10] + m[12] * other[11]; new_matrix[ 9] = m[ 1] * other[ 8] + m[ 5] * other[ 9] + m[ 9] * other[10] + m[13] * other[11]; new_matrix[10] = m[ 2] * other[ 8] + m[ 6] * other[ 9] + m[10] * other[10] + m[14] * other[11]; new_matrix[11] = m[ 3] * other[ 8] + m[ 7] * other[ 9] + m[11] * other[10] + m[15] * other[11]; new_matrix[12] = m[ 0] * other[12] + m[ 4] * other[13] + m[ 8] * other[14] + m[12] * other[15]; new_matrix[13] = m[ 1] * other[12] + m[ 5] * other[13] + m[ 9] * other[14] + m[13] * other[15]; new_matrix[14] = m[ 2] * other[12] + m[ 6] * other[13] + m[10] * other[14] + m[14] * other[15]; new_matrix[15] = m[ 3] * other[12] + m[ 7] * other[13] + m[11] * other[14] + m[15] * other[15]; return Matrix(new_matrix); } Vertex Matrix::operator*(const Vertex &v) const { float x = m[ 0] * v.x + m[ 4] * v.y + m[8 ] * v.z; float y = m[ 1] * v.x + m[ 5] * v.y + m[9 ] * v.z; float z = m[ 2] * v.x + m[ 6] * v.y + m[10] * v.z; x = x + m[12]; y = y + m[13]; z = z + m[14]; return Vertex(x, y, z); } /** * @brief Transposes the current matrix */ void Matrix::transpose() { float m_tmp[16]; m_tmp[0] = m[0]; m_tmp[4] = m[1]; m_tmp[8] = m[2]; m_tmp[12] = m[3]; m_tmp[1] = m[4]; m_tmp[5] = m[5]; m_tmp[9] = m[6]; m_tmp[13] = m[7]; m_tmp[2] = m[8]; m_tmp[6] = m[9]; m_tmp[10] = m[10]; m_tmp[14] = m[11]; m_tmp[3] = m[12]; m_tmp[7] = m[13]; m_tmp[11] = m[14]; m_tmp[15] = m[15]; for(int i = 0; i < 16; i++) m[i] = m_tmp[i]; } /** * @brief Computes an Euler representation (x, y, z) plus three * rotation values in rad. Rotations are with respect to * the x, y, z axes. */ void Matrix::toPostionAngle(float pose[6]) { if(pose != 0){ float _trX, _trY; if(m[0] > 0.0) { pose[4] = asin(m[8]); } else { pose[4] = (float)M_PI - asin(m[8]); } // rPosTheta[1] = asin( m[8]); // Calculate Y-axis angle float C = cos( pose[4] ); if ( fabs( C ) > 0.005 ) { // Gimball lock? _trX = m[10] / C; // No, so get X-axis angle _trY = -m[9] / C; pose[3] = atan2( _trY, _trX ); _trX = m[0] / C; // Get Z-axis angle _trY = -m[4] / C; pose[5] = atan2( _trY, _trX ); } else { // Gimball lock has occurred pose[3] = 0.0; // Set X-axis angle to zero _trX = m[5]; //1 // And calculate Z-axis angle _trY = m[1]; //2 pose[5] = atan2( _trY, _trX ); } pose[0] = m[12]; pose[1] = m[13]; pose[2] = m[14]; } } /** * @brief Matrix scaling with self assignment. */ void Matrix::operator*=(const float scale) { *this = *this * scale; } /** * @brief Matrix-Matrix multiplication with self assigment. */ void Matrix::operator*=(const Matrix& other) { *this = *this * other; } /** * @brief Matrix-Matrix multiplication (array based). See \ref{operator*}. */ void Matrix::operator*=(const float* other) { *this = *this * other; } /** * @brief Returns the internal data array. Unsafe. Will probably * removed in one of the next versions. */ float* Matrix::getData(){ return m;}; /** * @brief Indexed element (reading) access. */ float Matrix::operator[](const int index) const { /// TODO: Boundary check return m[index]; } /** * @brief Writeable index access */ float& Matrix::operator[](const int index) { return m[index]; } /** * @brief Returns the matrix's determinant */ float Matrix::det() { float det, result = 0, i = 1.0; float Msub3[9]; int n; for ( n = 0; n < 4; n++, i *= -1.0 ) { submat( Msub3, 0, n ); det = det3( Msub3 ); result += m[n] * det * i; } return( result ); } Matrix Matrix::inv(bool& success) { Matrix Mout; float mdet = det(); if ( fabs( mdet ) < 0.00000000000005 ) { cout << "Error matrix inverting! " << mdet << endl; return Mout; } float mtemp[9]; int i, j, sign; for ( i = 0; i < 4; i++ ) { for ( j = 0; j < 4; j++ ) { sign = 1 - ( (i +j) % 2 ) * 2; submat( mtemp, i, j ); Mout[i+j*4] = ( det3( mtemp ) * sign ) / mdet; } } return Mout; } /** * @brief Returns a sub matrix without row \ref i and column \ref j. */ void Matrix::submat(float* submat, int i, int j) { int di, dj, si, sj; // loop through 3x3 submatrix for( di = 0; di < 3; di ++ ) { for( dj = 0; dj < 3; dj ++ ) { // map 3x3 element (destination) to 4x4 element (source) si = di + ( ( di >= i ) ? 1 : 0 ); sj = dj + ( ( dj >= j ) ? 1 : 0 ); // copy element submat[di * 3 + dj] = m[si * 4 + sj]; } } } /** * @brief Calculates the determinant of a 3x3 matrix * * @param M input 3x3 matrix * @return determinant of input matrix */ float Matrix::det3( const float *M ) { float det; det = (double)( M[0] * ( M[4]*M[8] - M[7]*M[5] ) - M[1] * ( M[3]*M[8] - M[6]*M[5] ) + M[2] * ( M[3]*M[7] - M[6]*M[4] )); return ( det ); } } // namespace cpp2014
[ "themightyoarfish@users.noreply.github.com" ]
themightyoarfish@users.noreply.github.com
98edbff16d5af4310e6ce0018e66c872f22d0e20
cf1911723d07048c4180ace63afbd6ae60727eb0
/nnnUtilLib/wavemusic.cpp
d5a012d1329c22ec463f620504ea8ef825c93c38
[]
no_license
tinyan/SystemNNN
57490606973d95aa1e65d6090957b0e25c5b89f8
07e18ded880a0998bf5560c05c112b5520653e19
refs/heads/master
2023-05-04T17:30:42.406037
2023-04-16T03:38:40
2023-04-16T03:38:40
7,564,789
13
2
null
null
null
null
SHIFT_JIS
C++
false
false
28,717
cpp
// // // #include <windows.h> #include <stdio.h> #include <mmSystem.h> #include <dsound.h> #include "..\nyanLib\include\commonMacro.h" #include "..\nyanLib\include\myFile.h" #include "..\nyanDirectXLib\myDirectSound.h" #include "oggStreamDecoder.h" //#include "oggDecoder.h" #include "mmlControl.h" #include "waveMusic.h" //CWaveMusic* CWaveMusic::m_this = NULL; //HANDLE CWaveMusic::m_hEvent[12]; //BOOL CWaveMusic::m_dataEndFlag = FALSE; //LPSTR CWaveMusic::m_filename = NULL; //COggStreamDecoder* CWaveMusic::m_oggStreamDecoder = NULL; //char CWaveMusic::m_blockBuffer[44100*2*2 *2]; //FILE* CWaveMusic::m_filePointer = NULL; //int CWaveMusic::m_musicLoopCount = 0; //int CWaveMusic::m_nokoriDataSize = 0; //int CWaveMusic::m_waveTime = 0; //int CWaveMusic::m_waveTime0 = 0; //int CWaveMusic::m_playFlag0 = 0; //int CWaveMusic::m_playFlag = 0; #define STARTBGM_COMMAND 3 #define STOPBGM_COMMAND 4 #define THREADEND_COMMAND 5 #define GETMUSICTIME_COMMAND 7 #define PAUSEBGM_COMMAND 8 #define RESUMEBGM_COMMAND 9 #define CHECKPLAYING_COMMAND 10 #define SETVOLUME_COMMAND 11 #define FADEOUT_COMMAND 12 //#define RETURNEVENT_STATUS 13 #define GETFFT_COMMAND 13 #define FADEVOLUME_COMMAND 14 short convBuffer[4096]; short convBuffer2[4096]; // // multiThreadOnly // CWaveMusic::CWaveMusic(LPVOID myDirectSound, int number) { m_myDirectSound = myDirectSound; m_bufferNumber = number; m_directSoundBuffer = NULL; m_directSoundBuffer8 = NULL; m_filePointer = NULL; // m_fileHandle = INVALID_HANDLE_VALUE; m_spectrumCalcuMode = 0; //create second buffer 2sec WAVEFORMATEX pcmwf; ZeroMemory(&pcmwf, sizeof(pcmwf)); pcmwf.cbSize = sizeof(pcmwf); pcmwf.wBitsPerSample = 16; pcmwf.wFormatTag = WAVE_FORMAT_PCM; pcmwf.nChannels = 2; pcmwf.nSamplesPerSec = 44100; pcmwf.nBlockAlign = 4; pcmwf.nAvgBytesPerSec = pcmwf.nSamplesPerSec * pcmwf.nBlockAlign; DSBUFFERDESC dsbdesc; ZeroMemory(&dsbdesc, sizeof(dsbdesc)); dsbdesc.dwSize = sizeof(dsbdesc); dsbdesc.dwFlags = DSBCAPS_CTRLVOLUME | DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS | DSBCAPS_LOCSOFTWARE | DSBCAPS_CTRLPOSITIONNOTIFY; // dsbdesc.dwFlags = DSBCAPS_CTRLVOLUME | DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS | DSBCAPS_LOCDEFER | DSBCAPS_CTRLPOSITIONNOTIFY; dsbdesc.dwBufferBytes = pcmwf.nAvgBytesPerSec * 2; dsbdesc.lpwfxFormat = &pcmwf; LPDIRECTSOUND8 directSound8 = (LPDIRECTSOUND8)m_myDirectSound; LPDIRECTSOUNDBUFFER lp = NULL; if (directSound8) { HRESULT hr = directSound8->CreateSoundBuffer(&dsbdesc, &lp, NULL); m_directSoundBuffer = lp; lp->QueryInterface(IID_IDirectSoundBuffer8, (LPVOID*)&m_directSoundBuffer8); } //refget // if (hr != DS_OK) return FALSE; // if (lp == NULL) return FALSE; m_startVolumeFlag = FALSE; // char m_blockBuffer[44100*2*2 *2]; // char m_fftBuffer[4096]; // char m_fftBuffer0[44100*2*2 ]; // char m_fftBuffer00[44100*2*2 ]; m_blockBuffer = NULL; m_fftBuffer = NULL; m_fftBuffer0 = NULL; m_fftBuffer00 = NULL; m_blockBuffer = new char[44100*2*2 *2]; if (number < 2) { m_fftBuffer = new char[4096]; m_fftBuffer0 = new char[44100*2*2]; m_fftBuffer00 = new char[44100*2*2]; } m_convBuffer = NULL; //#if !defined __USE_XAUDIO2__ m_oggStreamDecoder = NULL; if (CMyDirectSound::m_xAudioFlag == 0) { if (number == 0) { m_oggStreamDecoder = new COggStreamDecoder(convBuffer); } else if (number == 1) { m_oggStreamDecoder = new COggStreamDecoder(convBuffer2); } else { m_convBuffer = new short[4096]; m_oggStreamDecoder = new COggStreamDecoder(m_convBuffer); } } //#endif m_mmlControl = new CMMLControl(); for (int i=0;i<16;i++) { m_hEvent[i] = NULL; m_hReturnEvent[i] = NULL; } //event m_hEvent[0] = CreateEvent(NULL,FALSE,FALSE,NULL); //first point m_hEvent[1] = CreateEvent(NULL,FALSE,FALSE,NULL); //centerpoint m_hEvent[2] = CreateEvent(NULL,FALSE,FALSE,NULL); //end m_hEvent[3] = CreateEvent(NULL,FALSE,FALSE,NULL); //start bgm command m_hEvent[4] = CreateEvent(NULL,FALSE,FALSE,NULL); //stop bgm command m_hEvent[5] = CreateEvent(NULL,FALSE,FALSE,NULL); //thread end command m_hEvent[6] = CreateEvent(NULL,FALSE,FALSE,NULL); //bgm stopped m_hEvent[7] = CreateEvent(NULL,FALSE,FALSE,NULL); //gettime event m_hEvent[8] = CreateEvent(NULL,FALSE,FALSE,NULL); //pause event m_hEvent[9] = CreateEvent(NULL,FALSE,FALSE,NULL); //resume event m_hEvent[10] = CreateEvent(NULL,FALSE,FALSE,NULL); //checkplaying m_hEvent[11] = CreateEvent(NULL,FALSE,FALSE,NULL); //setvolume m_hEvent[12] = CreateEvent(NULL,FALSE,FALSE,NULL); //fadeout //m_hEvent[13] = CreateEvent(NULL,FALSE,FALSE,NULL); //return event m_hEvent[13] = CreateEvent(NULL,FALSE,FALSE,NULL); //getfftbuffer m_hEvent[14] = CreateEvent(NULL,FALSE,FALSE,NULL); //fadeVolume m_hReturnEvent[3] = CreateEvent(NULL,FALSE,FALSE,NULL); //start bgm command m_hReturnEvent[4] = CreateEvent(NULL,FALSE,FALSE,NULL); //stop bgm command m_hReturnEvent[5] = CreateEvent(NULL,FALSE,FALSE,NULL); //thread end command m_hReturnEvent[6] = CreateEvent(NULL,FALSE,FALSE,NULL); //bgm stopped m_hReturnEvent[7] = CreateEvent(NULL,FALSE,FALSE,NULL); //gettime event m_hReturnEvent[8] = CreateEvent(NULL,FALSE,FALSE,NULL); //pause event m_hReturnEvent[9] = CreateEvent(NULL,FALSE,FALSE,NULL); //resume event m_hReturnEvent[10] = CreateEvent(NULL,FALSE,FALSE,NULL); //checkplaying m_hReturnEvent[11] = CreateEvent(NULL,FALSE,FALSE,NULL); //setvolume m_hReturnEvent[12] = CreateEvent(NULL,FALSE,FALSE,NULL); //fadeout m_hReturnEvent[13] = CreateEvent(NULL,FALSE,FALSE,NULL); //getfftbuffer m_hReturnEvent[14] = CreateEvent(NULL,FALSE,FALSE,NULL); //fadeVolume DSBPOSITIONNOTIFY pn[3]; pn[0].dwOffset = 0; pn[0].hEventNotify = m_hEvent[0]; pn[1].dwOffset = 1*(44100*2*2); pn[1].hEventNotify = m_hEvent[1]; pn[2].dwOffset = DSBPN_OFFSETSTOP; pn[2].hEventNotify = m_hEvent[2]; m_directSoundNotify = NULL; if (m_myDirectSound) { LPDIRECTSOUNDNOTIFY pNotify; HRESULT hr2 = lp->QueryInterface(IID_IDirectSoundNotify, (LPVOID*)&pNotify); m_directSoundNotify = lp; HRESULT hr3 = pNotify->SetNotificationPositions(3, pn); } m_fadeInFlag = FALSE; m_fadeOutFlag = FALSE; m_volume = 100; m_fadeInCount = 0; m_fadeOutCount = 0; m_fadeInTime0 = 20; m_fadeInTime = 20; m_fadeOutTime0 = 30; m_fadeOutTime = 30; ZeroMemory(m_fftBuffer,4096); ZeroMemory(m_fftBuffer0,40960); ZeroMemory(m_fftBuffer00,40960); m_fadeTime = 0; m_fadeTime0 = 0; m_fadeCount = 0; m_fadeVolumeStart = 0; m_fadeVolumeEnd = 0; m_fadeVolumeEnd0 = 0; // m_this = this; //thread m_threadHandle = NULL; if (m_myDirectSound) { m_threadHandle = CreateThread(NULL, 0, staticMyThread, (LPVOID)this, 0, &m_threadID); if (m_threadHandle == NULL) { //error } } } CWaveMusic::~CWaveMusic() { End(); } void CWaveMusic::End(void) { //threadが存在すれば停止終了させる if (m_threadHandle != NULL) { SetEvent(m_hEvent[THREADEND_COMMAND]); WaitForSingleObject(m_threadHandle,5*1000); // if (m_hEvent[RETURNEVENT_STATUS] != NULL) // { // WaitForSingleObject(m_hEvent[RETURNEVENT_STATUS],2*1000); // } Sleep(100); CloseHandle(m_threadHandle); m_threadHandle = NULL; } int i = 0; for (i=0;i<16;i++) { if (m_hEvent[i] != NULL) { CloseHandle(m_hEvent[i]); m_hEvent[i] = NULL; } } for (i=0;i<16;i++) { if (m_hReturnEvent[i] != NULL) { CloseHandle(m_hReturnEvent[i]); m_hReturnEvent[i] = NULL; } } if (m_directSoundNotify != NULL) { LPDIRECTSOUNDNOTIFY lp = (LPDIRECTSOUNDNOTIFY)m_directSoundNotify; lp->Release(); m_directSoundNotify = NULL; } //release second buffer if (m_directSoundBuffer8 != NULL) { LPDIRECTSOUNDBUFFER8 lp8 = (LPDIRECTSOUNDBUFFER8)m_directSoundBuffer8; lp8->Release(); m_directSoundBuffer8 = NULL; } if (m_directSoundBuffer != NULL) { LPDIRECTSOUNDBUFFER lp = (LPDIRECTSOUNDBUFFER)m_directSoundBuffer; lp->Release(); m_directSoundBuffer = NULL; } //用心 if (m_filePointer != NULL) { fclose(m_filePointer); m_filePointer = NULL; } // if (m_fileHandle != INVALID_HANDLE_VALUE) // { // CloseHandle(m_fileHandle); // m_fileHandle = INVALID_HANDLE_VALUE; // } // DELETEARRAY(m_convBuffer); DELETEARRAY(m_fftBuffer00); DELETEARRAY(m_fftBuffer0); DELETEARRAY(m_fftBuffer); DELETEARRAY(m_blockBuffer); ENDDELETECLASS(m_mmlControl); ENDDELETECLASS(m_oggStreamDecoder); } BOOL CWaveMusic::PlayBGM(LPSTR filename,int loop,BOOL fadeinFlag,int fadeinTime) { if (m_threadHandle == NULL) return FALSE; //stop in playing StopBGM(); if (m_mmlControl->LoadMML(filename) == FALSE) return FALSE; // m_musicLoopCount0 = loop; m_filename = filename; if (fadeinFlag) { m_fadeInTime0 = fadeinTime; // char mes[256]; // sprintf(mes,"[PlayWithFadeIn %d]",fadeinTime); // OutputDebugString(mes); } else { m_fadeInTime0 = 0; } m_fadeInFlag0 = fadeinFlag; SetEvent(m_hEvent[STARTBGM_COMMAND]); WaitForSingleObject(m_hReturnEvent[STARTBGM_COMMAND],10*1000); ResetEvent(m_hReturnEvent[STARTBGM_COMMAND]); return TRUE; } //PlayVoice pack voice //PlaySound plain wave BOOL CWaveMusic::StopBGM(BOOL fadeOutFlag,int fadeOutTime) { if (m_threadHandle == NULL) return FALSE; if (fadeOutFlag == FALSE) { SetEvent(m_hEvent[STOPBGM_COMMAND]); WaitForSingleObject(m_hReturnEvent[STOPBGM_COMMAND],10*1000); ResetEvent(m_hReturnEvent[STOPBGM_COMMAND]); //if (m_bufferNumber == 1) //{ OutputDebugString("[stopbgm command]"); //} m_fadeInFlag = FALSE; m_fadeFlag = FALSE; } else { if (fadeOutTime > 0) { m_fadeOutTime0 = fadeOutTime; } m_fadeOutFlag0 = fadeOutFlag; SetEvent(m_hEvent[FADEOUT_COMMAND]); WaitForSingleObject(m_hReturnEvent[FADEOUT_COMMAND],10*1000); ResetEvent(m_hReturnEvent[FADEOUT_COMMAND]); OutputDebugString("bgm(FADEOUT) command"); } return TRUE; } void CWaveMusic::SetStartVolume(int vol) { m_startVolume = vol; m_startVolumeFlag = TRUE; } void CWaveMusic::SetVolumeRoutine(int vol) { if (m_directSoundBuffer != NULL) { long vol2 = (vol-100)*20; if (vol == 0) vol2 = -10000; if (vol2>0) vol2 = 0; if (vol2<-10000) vol2 = -10000; LPDIRECTSOUNDBUFFER8 lp = (LPDIRECTSOUNDBUFFER8)m_directSoundBuffer8; lp->SetVolume(vol2); } } DWORD WINAPI CWaveMusic::staticMyThread(LPVOID param) { CWaveMusic* thisObject = (CWaveMusic*)param; int rt = thisObject->MyThread(param); ExitThread(0); return rt; } DWORD WINAPI CWaveMusic::MyThread(LPVOID param) { BOOL bgmPlayingFlag = FALSE; int loopCount = 0; // LPDIRECTSOUND directSound = (LPDIRECTSOUND)m_myDirectSound; LPDIRECTSOUNDBUFFER8 directSoundBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8); // static int debugCount = 0; m_oldTime = timeGetTime(); m_amari = 0; m_bufferTimeAmari = 0; while(TRUE) { DWORD en = WaitForMultipleObjects(15,m_hEvent,FALSE,100); switch (en) { case WAIT_OBJECT_0: //first //OutputDebugString("[F]"); case WAIT_OBJECT_0+1: //center //OutputDebugString("[C]"); //OutputDebugString("[1sec]"); m_waveTime0++; int n; n = 0; if (en == WAIT_OBJECT_0) n = 1; if (m_dataEndFlag) { directSoundBuffer->Stop(); //OutputDebugString("[data end stop]"); m_playFlag0 = FALSE; } else { if (GetBlock(n) == 0) { m_dataEndFlag = TRUE; } } OnWaveTime(); break; case WAIT_OBJECT_0+2: //end dummy break; case WAIT_OBJECT_0+3: //play command m_waveTime0 = 0; LPSTR filename; filename = m_mmlControl->Kaiseki(); if (filename == NULL) { m_mmlControl->RestartMML(); filename = m_mmlControl->Kaiseki(); } #if defined _DEBUG char mes[256]; wsprintf(mes,"PLAY ch=%d 曲【%s】\n",m_bufferNumber,filename); OutputDebugString(mes); #endif OpenNewFile(filename); m_dataEndFlag = FALSE; m_nokoriDataSize = 0; if (m_filePointer != NULL) // if (m_fileHandle != INVALID_HANDLE_VALUE) { if (GetBlock(0) == 0) m_dataEndFlag = TRUE;//??? } directSoundBuffer->SetCurrentPosition(0); m_fadeInFlag = m_fadeInFlag0; m_fadeInCount = 0; m_fadeInTime = m_fadeInTime0; m_fadeOutFlag = FALSE; m_fadeOutCount = 0; m_musicLoopCount = m_musicLoopCount0; if (m_startVolumeFlag) { m_volume = m_startVolume; m_startVolumeFlag = FALSE; } //set start volume if (m_fadeInFlag) { //if (m_bufferNumber == 1) //{ //OutputDebugString("[o]"); //} SetFadeInVolume(); } else { SetNormalVolume(); } // ResetEvent(m_hEvent[0]); // ResetEvent(m_hEvent[1]); int hr; hr = directSoundBuffer->Play(0,0,DSBPLAY_LOOPING); // if FAILED(hr) // { // OutputDebugString("DirectSoundBuffer::Play Error"); // } m_playTime = 0; m_bufferTime = 0; m_playFlag0 = TRUE; m_amari = 0; m_bufferTimeAmari = 0; m_oldTime = timeGetTime(); SetEvent(m_hReturnEvent[STARTBGM_COMMAND]); break; case WAIT_OBJECT_0+4: //stop command directSoundBuffer->Stop(); if (m_filePointer != NULL) { fclose(m_filePointer); m_filePointer = NULL; } // m_oggStreamDecoder->EndDecode(); // if (m_fileHandle != INVALID_HANDLE_VALUE) // { // CloseHandle(m_fileHandle); // m_fileHandle = INVALID_HANDLE_VALUE; // } m_playFlag0 = FALSE; SetEvent(m_hReturnEvent[STOPBGM_COMMAND]); break; case WAIT_OBJECT_0+5: //exit command if (directSoundBuffer != NULL) { directSoundBuffer->Stop(); } // SetEvent(m_hEvent[RETURNEVENT_STATUS]); ExitThread(0); return 0; break; case WAIT_OBJECT_0+7: //getmusictime m_waveTime = m_waveTime0; SetEvent(m_hReturnEvent[GETMUSICTIME_COMMAND]); break; case WAIT_OBJECT_0+8: //pause directSoundBuffer->Stop(); m_playFlag0 = FALSE; SetEvent(m_hReturnEvent[PAUSEBGM_COMMAND]); break; case WAIT_OBJECT_0+9: //resume directSoundBuffer->Play(0,0,DSBPLAY_LOOPING); m_playFlag0 = TRUE; SetEvent(m_hReturnEvent[RESUMEBGM_COMMAND]); break; case WAIT_OBJECT_0+10: //checkplaying m_playFlag = m_playFlag0; SetEvent(m_hReturnEvent[CHECKPLAYING_COMMAND]); break; case WAIT_OBJECT_0+11: //setvolume m_volume = m_volume0; if (m_fadeOutFlag) { SetFadeOutVolume(); } else if (m_fadeInFlag) { SetFadeInVolume(); } else if (m_fadeFlag) { SetFadeVolume(); } else { SetNormalVolume(); } SetEvent(m_hReturnEvent[SETVOLUME_COMMAND]); break; case WAIT_OBJECT_0+12: //fadeout if (m_fadeInFlag) { //けいさん m_fadeOutCount = m_fadeInTime - m_fadeInCount; if (m_fadeOutCount < 0) m_fadeOutCount = 0; if (m_fadeOutCount > m_fadeInTime) m_fadeOutCount = m_fadeInTime; if (m_fadeInTime > 0) { m_fadeOutCount *= m_fadeOutTime; m_fadeOutCount /= m_fadeInTime; } // OutputDebugString("特殊"); } else if (m_fadeOutFlag == FALSE) { m_fadeOutCount = 0; } else { //そのまま? } m_fadeOutFlag = TRUE; m_fadeOutTime = m_fadeOutTime0; //if (m_bufferNumber == 1) //{ //OutputDebugString("[x]"); //} m_fadeInFlag = FALSE; SetEvent(m_hReturnEvent[FADEOUT_COMMAND]); break; case WAIT_OBJECT_0+13: //getfftbuffer OnWaveTime(); if (m_fftBuffer != NULL) { DWORD playPtr; if (directSoundBuffer->GetCurrentPosition(&playPtr,NULL) == DS_OK) { playPtr %= (44100*2*2 * 2); int n2 = playPtr / (44100*2*2); int n3 = playPtr % (44100*2*2); n3 &= ~3; if (n3>4408*39) n3 = 4408*39; if (n2 == 0) { memcpy(m_fftBuffer,m_fftBuffer00+n3,4096); } else { memcpy(m_fftBuffer,m_fftBuffer0+n3,4096); } } else { if (m_bufferBlockNumber == 1) { memcpy(m_fftBuffer,m_fftBuffer00+4408*(m_bufferTime % 40),4096);//4410は4の倍数じゃないのでごまかす } else { memcpy(m_fftBuffer,m_fftBuffer0+4408*(m_bufferTime % 40),4096); } } } // memcpy(m_fftBuffer,m_fftBuffer0+4096*(rand() % 10),4096); SetEvent(m_hReturnEvent[GETFFT_COMMAND]); break; case WAIT_OBJECT_0+14://fadevolume FadeVolumeMain(); SetEvent(m_hReturnEvent[FADEVOLUME_COMMAND]); break; case WAIT_TIMEOUT: OnWaveTime(); break; } } return 0; } void CWaveMusic::OnWaveTime(void) { int newTime; newTime = timeGetTime(); int deltaTime = newTime - m_oldTime + m_amari; int dms; dms = deltaTime / 100; m_amari = deltaTime - dms * 100; int deltaBufferTime = newTime - m_oldTime + m_bufferTimeAmari; int dms2; dms2 = deltaBufferTime / 25; m_bufferTimeAmari = deltaBufferTime - dms2*25; m_oldTime = newTime; if (dms<=0) return; m_playTime += dms; m_bufferTime += dms2; //if (m_bufferNumber == 1) //{ //OutputDebugString("."); //} if (m_fadeInFlag) { //OutputDebugString("+"); if (m_fadeInCount <= m_fadeInTime) { m_fadeInCount += dms; if (dms>0) { // OutputDebugString("+"); } else { // OutputDebugString(","); } if (m_fadeInCount >= m_fadeInTime) { m_fadeInCount = m_fadeInTime; m_fadeInFlag = FALSE; // OutputDebugString("[fadein終了にゃ]"); } //set volume if (m_playFlag0) { SetFadeInVolume(); } } } else if (m_fadeOutFlag) { m_fadeOutCount += dms; if (dms>0) { // OutputDebugString("-"); } else { // OutputDebugString("."); } if (m_fadeOutCount >= m_fadeOutTime) { //stop bgm if (m_playFlag0) { LPDIRECTSOUNDBUFFER8 directSoundBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8); directSoundBuffer->Stop(); // m_oggStreamDecoder->EndDecode(); // if (m_fileHandle != INVALID_HANDLE_VALUE) // { // CloseHandle(m_fileHandle); // m_fileHandle = INVALID_HANDLE_VALUE; // } if (m_filePointer != NULL) { fclose(m_filePointer); m_filePointer = NULL; } } m_playFlag0 = FALSE; m_fadeOutFlag = FALSE; //if (m_bufferNumber == 1) //{ //OutputDebugString("[xx]"); //} m_fadeInFlag = FALSE; } else { //set volume SetFadeOutVolume(); } } else if (m_fadeFlag) { if (m_fadeCount <= m_fadeTime) { m_fadeCount += dms; if (dms>0) { // OutputDebugString("+"); } else { // OutputDebugString(","); } if (m_fadeCount >= m_fadeTime) { m_fadeCount = m_fadeTime; m_fadeFlag = FALSE; // OutputDebugString("[fadein終了にゃ]"); } //set volume if (m_playFlag0) { SetFadeVolume(); } } } } //もどり:有効データサイズ int CWaveMusic::GetBlock(int n) { if (m_filePointer == NULL) // if (m_fileHandle == INVALID_HANDLE_VALUE) { ZeroMemory(m_blockBuffer,44100*2*2); return 0; } BOOL f = TRUE; while(f) { //OutputDebugString("[decode]"); int sz = m_oggStreamDecoder->Decode(); if (sz>0) { if (m_bufferNumber == 0) { memcpy(m_blockBuffer + m_nokoriDataSize,convBuffer,sz); } else { memcpy(m_blockBuffer + m_nokoriDataSize,convBuffer2,sz); } m_nokoriDataSize += sz; if (m_nokoriDataSize >= 44100*2*2) f = FALSE; //char mes[256]; //sprintf(mes,"[decode=%d nokori=%d]",sz,m_nokoriDataSize); //OutputDebugString(mes); } else { //char mes[256]; //sprintf(mes,"[nokori=%d]",m_nokoriDataSize); //OutputDebugString(mes); m_oggStreamDecoder->EndDecode(); BOOL flg = TRUE; if (m_filePointer != NULL) { fclose(m_filePointer); m_filePointer = NULL; } // if (m_fileHandle != INVALID_HANDLE_VALUE) // { // CloseHandle(m_fileHandle); // m_fileHandle = INVALID_HANDLE_VALUE; // } //nextdecode? LPSTR filename; filename = m_mmlControl->Kaiseki(); if (filename == NULL) { if (m_musicLoopCount == 0) { m_mmlControl->RestartMML(); filename = m_mmlControl->Kaiseki(); } else { m_musicLoopCount--; if (m_musicLoopCount > 0) { m_mmlControl->RestartMML(); filename = m_mmlControl->Kaiseki(); } } } if (filename == NULL) { f = FALSE; } else { #if defined _DEBUG OutputDebugString("- 曲【"); OutputDebugString(filename); OutputDebugString("】"); #endif OpenNewFile(filename); } } } int dataSize = m_nokoriDataSize; if (dataSize > 44100*2*2) dataSize = 44100*2*2; #if defined _DEBUG //char mes2[256]; //sprintf(mes2,"[dataSize=%d]",dataSize); //OutputDebugString(mes2); #endif //あきをうめる if (m_nokoriDataSize < 44100*2*2) { ZeroMemory(m_blockBuffer+m_nokoriDataSize,44100*2*2-m_nokoriDataSize); } //転送 LPBYTE lpBlockAdd1; LPBYTE lpBlockAdd2; DWORD blockSize1; DWORD blockSize2; LPDIRECTSOUNDBUFFER8 lpDSBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8); int dsize = (44100*2*2*2)/2; HRESULT hr = lpDSBuffer->Lock(dsize*n,dsize,(LPVOID*)&lpBlockAdd1,&blockSize1,(LPVOID*)&lpBlockAdd2,&blockSize2,0); //error check if (blockSize1>0) { memcpy(lpBlockAdd1,m_blockBuffer,blockSize1); } if (blockSize2>0) { memcpy(lpBlockAdd2,m_blockBuffer+blockSize1,blockSize2); } lpDSBuffer->Unlock(lpBlockAdd1,blockSize1,lpBlockAdd2,blockSize2); if (m_spectrumCalcuMode == 1) { //4096byte to fft buffer if (n == 0) { memcpy(m_fftBuffer00,m_blockBuffer,4408*40); } else { memcpy(m_fftBuffer0,m_blockBuffer,4408*40); } } //のこりをずらす m_nokoriDataSize -= 44100*2*2; if (m_nokoriDataSize < 0) m_nokoriDataSize = 0; if (m_nokoriDataSize > 0) { memmove(m_blockBuffer,m_blockBuffer+44100*2*2,m_nokoriDataSize); } m_bufferBlockNumber = n; return dataSize; } void CWaveMusic::Pause(void) { SetEvent(m_hEvent[PAUSEBGM_COMMAND]); WaitForSingleObject(m_hReturnEvent[PAUSEBGM_COMMAND],10*1000); ResetEvent(m_hReturnEvent[PAUSEBGM_COMMAND]); } void CWaveMusic::Resume(void) { //OutputDebugString("resumeCommand"); SetEvent(m_hEvent[RESUMEBGM_COMMAND]); WaitForSingleObject(m_hReturnEvent[RESUMEBGM_COMMAND],10*1000); ResetEvent(m_hReturnEvent[RESUMEBGM_COMMAND]); } BOOL CWaveMusic::CheckPlaying(void) { SetEvent(m_hEvent[CHECKPLAYING_COMMAND]); WaitForSingleObject(m_hReturnEvent[CHECKPLAYING_COMMAND],10*1000); ResetEvent(m_hReturnEvent[CHECKPLAYING_COMMAND]); return m_playFlag; } int CWaveMusic::GetMusicTime(void) { SetEvent(m_hEvent[GETMUSICTIME_COMMAND]); WaitForSingleObject(m_hReturnEvent[GETMUSICTIME_COMMAND],10*1000); ResetEvent(m_hReturnEvent[GETMUSICTIME_COMMAND]); return m_waveTime; } void CWaveMusic::SetNormalVolume(void) { LPDIRECTSOUNDBUFFER8 directSoundBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8); int vol = m_volume*100; m_nowVolume = m_volume; vol -= 10000; if (directSoundBuffer != nullptr) { directSoundBuffer->SetVolume(vol); } //char mes[256]; //sprintf(mes,"[ch=%d VOL=%d]",m_bufferNumber,m_volume); //OutputDebugString(mes); } void CWaveMusic::SetFadeVolume(void) { LPDIRECTSOUNDBUFFER8 directSoundBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8); int dv = m_fadeTime; if (dv<1) dv = 1; int count = m_fadeCount; if (m_fadeTime == 0) count = 1; if (count>dv) count = dv; int vol = ((m_fadeVolumeEnd - m_fadeVolumeStart)*100 * count) / dv; vol += m_fadeVolumeStart * 100; if (vol < 0) vol = 0; if (vol > 10000) vol = 10000; vol -= 10000; if (directSoundBuffer != nullptr) { directSoundBuffer->SetVolume(vol); } } void CWaveMusic::SetFadeInVolume(void) { LPDIRECTSOUNDBUFFER8 directSoundBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8); int dv = m_fadeInTime; if (dv<1) dv = 1; int count = m_fadeInCount; if (m_fadeInTime == 0) count = 1; if (count>dv) count = dv; if (m_fadeInFlag == FALSE) { count = dv; } m_nowVolume = (m_volume * count) / dv; int vol = (m_volume*100 * count) / dv; //char mes[256]; //sprintf(mes,"[ch=%d FadeInVol=%d]",m_bufferNumber,vol/100); //OutputDebugString(mes); vol -= 10000; if (directSoundBuffer != nullptr) { directSoundBuffer->SetVolume(vol); } } void CWaveMusic::SetFadeOutVolume(void) { LPDIRECTSOUNDBUFFER8 directSoundBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8); int dv = m_fadeOutTime; if (dv<1) dv = 1; int count = m_fadeOutCount; if (m_fadeOutTime == 0) count = 1; if (count>dv) count = dv; m_nowVolume = (m_volume * count) / dv; int vol = (m_volume*100 * (dv-count)) / dv; //char mes[256]; //sprintf(mes,"[ch=%d FadeOutVol=%d]",m_bufferNumber,vol/100); //OutputDebugString(mes); vol -= 10000; if (directSoundBuffer != nullptr) { directSoundBuffer->SetVolume(vol); } } BOOL CWaveMusic::OpenNewFile(LPSTR filename) { char allfilename[256]; wsprintf(allfilename,"wgq\\%s.wgq",filename); // memcpy(allfilename,"wgq\\",4); // int ln = strlen(filename); // memcpy(allfilename+4,filename,ln); // memcpy(allfilename+4+ln,".wgq",5); m_filePointer = CMyFile::Open(allfilename,"rb"); // m_fileHandle = CreateFile(allfilename,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); if (m_filePointer != NULL) // if (m_fileHandle != INVALID_HANDLE_VALUE) { //packtypeでわける char header[64]; DWORD readed = 0; //ReadFile(m_fileHandle,header,64,&readed,NULL); fread(header,sizeof(char),64,m_filePointer); if (header[57] == '2') { char waveheader[20]; // ReadFile(m_fileHandle,waveheader,20,&readed,NULL); fread(waveheader,sizeof(char),20,m_filePointer); int* ptr = (int*)waveheader; ptr += 4; int skp = *ptr; // SetFilePointer(m_fileHandle,skp,NULL,FILE_CURRENT); fpos_t nowPos; fgetpos(m_filePointer,&nowPos); nowPos += skp; fsetpos(m_filePointer,&nowPos); } // SetFilePointer(m_fileHandle,64,NULL,FILE_BEGIN); m_dataEndFlag = FALSE; m_oggStreamDecoder->StartDecode2(m_filePointer); // m_oggStreamDecoder->StartDecode2(m_fileHandle); return TRUE; } return FALSE; } void CWaveMusic::FadeVolume(int vol,int fadeTime) { m_fadeVolumeEnd0 = vol; m_fadeTime0 = fadeTime; SetEvent(m_hEvent[FADEVOLUME_COMMAND]); WaitForSingleObject(m_hReturnEvent[FADEVOLUME_COMMAND],10*1000); ResetEvent(m_hReturnEvent[FADEVOLUME_COMMAND]); } void CWaveMusic::ChangeVolume(int vol) { m_volume0 = vol; // char mes[256]; // sprintf(mes,"[COMMAND SETVOLUME %d]",m_volume); // OutputDebugString(mes); SetEvent(m_hEvent[SETVOLUME_COMMAND]); WaitForSingleObject(m_hReturnEvent[SETVOLUME_COMMAND],10*1000); ResetEvent(m_hReturnEvent[SETVOLUME_COMMAND]); // sprintf(mes,"[RETURN SETVOLUME %d]",m_volume); // OutputDebugString(mes); } BOOL CWaveMusic::GetWaveCut(float* wave,int n,int rightChannel) { if ((m_threadHandle == NULL) || (m_playFlag0 == FALSE) || (m_spectrumCalcuMode == 0)) { for (int i=0;i<n;i++) { *(wave) = 0.0f; } return FALSE; } SetEvent(m_hEvent[GETFFT_COMMAND]); WaitForSingleObject(m_hReturnEvent[GETFFT_COMMAND],10*1000); ResetEvent(m_hReturnEvent[GETFFT_COMMAND]); short* ptr = (short*)m_fftBuffer; ptr += rightChannel; float dv = 1.0f / 32768.0f; for (int i=0;i<n;i++) { *(wave+i) = ((float)(ptr[2*i])) * dv; } return TRUE; } BOOL CWaveMusic::GetWavePlainData(int* wave,int block) { if ((m_threadHandle == NULL) || (m_playFlag0 == FALSE) || (m_spectrumCalcuMode == 0)) { for (int i=0;i<block;i++) { *(wave) = 0; } return FALSE; } SetEvent(m_hEvent[GETFFT_COMMAND]); WaitForSingleObject(m_hReturnEvent[GETFFT_COMMAND],10*1000); ResetEvent(m_hReturnEvent[GETFFT_COMMAND]); short* ptr = (short*)m_fftBuffer; for (int i=0;i<block;i++) { *(wave+i) = (int)(ptr[2*i * (1024/block)]); } return TRUE; } BOOL CWaveMusic::GetFFT(int* fft,int point,int block) { if ((m_threadHandle == NULL) || (m_playFlag0 == FALSE) || (m_spectrumCalcuMode == 0)) { for (int i=0;i<block;i++) { *(fft+i) = 0; } return FALSE; } SetEvent(m_hEvent[GETFFT_COMMAND]); WaitForSingleObject(m_hReturnEvent[GETFFT_COMMAND],10*1000); ResetEvent(m_hReturnEvent[GETFFT_COMMAND]); // int tm = GetMusicTime(); // tm %= 10; //fft計算は最大1024pointまで //volumeも考慮すべきか→FFTに専念 //dummy routine stereo 44 16bit short* ptr = (short*)m_fftBuffer; // ptr += 44100*2*2/2/10*tm; for (int i=0;i<block;i++) { *(fft+i) = (int)(ptr[2*i * (1024/block)]); } // memcpy(buffer,m_fftBuffer,4096); return TRUE; } //handleで同期とらなくてもだいじょうぶかな void CWaveMusic::StartSpectrum(void) { m_spectrumCalcuMode = 1; } void CWaveMusic::StopSpectrum(void) { m_spectrumCalcuMode = 0; } void CWaveMusic::FadeVolumeMain(void) { int vol = m_volume; if (m_fadeInFlag) { vol = m_nowVolume; } else if (m_fadeOutFlag) { vol = m_nowVolume; } else { // } m_fadeVolumeStart = vol; m_fadeVolumeEnd = m_fadeVolumeEnd0; m_fadeInFlag = FALSE; m_fadeOutFlag = FALSE; m_fadeFlag = TRUE; m_fadeTime = m_fadeTime0; m_fadeCount = 0; m_volume = m_fadeVolumeEnd; }
[ "tinyan@mri.biglobe.ne.jp" ]
tinyan@mri.biglobe.ne.jp
79492de6b19f35d48a1d5cffc4c81377d89ac360
c86ef1757d6598225c5162032b41628f221e02e1
/main.cpp
2e0b712d878a15d144ece08b2610a46e451a7d8a
[]
no_license
deknapp/mtg-sim
77f42f83a8fc0569917e6c96a6858c26abdf5230
6cb625e8a279ffd8165d45b74bf10240473180c7
refs/heads/master
2020-04-03T18:29:35.598213
2018-11-09T06:05:56
2018-11-09T06:05:56
155,486,375
0
0
null
null
null
null
UTF-8
C++
false
false
368
cpp
#include "include/run.h" #include <cstdlib> #include <iostream> int main( int argc, char* argv[] ){ if ( argc == 1 or argc > 2 ){ std::cout << argv[0] << " " << argv[1] << std::endl; std::cout << argc << std::endl; std::cout << "Invalid arguments. Requires one text file argument." << std::endl; return 0; } run( argv[1] ); return 1; }
[ "nathaniel.knapp@gmail.com" ]
nathaniel.knapp@gmail.com