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
6d38229c0e5e1e91c67ab75b3e21552526018f45
83b7f3fd6eb4cd4ff3728e9249abdf1ce1fdce33
/LEETCODE/30_DAY_LEETCODE_CHALLENGE MAY/8_CHECK_IF_IT_IS_A_STRAIGHT_LINE.cpp
5ea87db29094f2d81fc431a01e9ef356811604ab
[]
no_license
akash19jain/COMPETITIVE-PROGRAMMING
881ee80c40b1bdb8556f4fd8193896224e126a95
7a0fe1a5aad7d1990838a7b99891e9af1be5c336
refs/heads/master
2021-11-23T01:26:36.780405
2021-09-12T17:05:27
2021-09-12T17:05:27
173,334,187
8
3
null
null
null
null
UTF-8
C++
false
false
460
cpp
class Solution { public: bool checkStraightLine(vector<vector<int>>& coordinates) { if (coordinates.size() <= 2) return true; int x1 = coordinates[0][0]; int y1 = coordinates[0][1]; int x2 = coordinates[1][0]; int y2 = coordinates[1][1]; for (int i = 2; i < coordinates.size(); i++) { int x = coordinates[i][0]; int y = coordinates[i][1]; if ((y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1)) return false; } return true; } };
[ "akash19jain@gmail.com" ]
akash19jain@gmail.com
29159e6876b437b9d6bd73cd9545bd414fa23f83
59760e7e351fa25a9d974f105b9ac323f9115665
/HYJ/boj/Graph/boj13418.cpp
e8a45997e5cd260e8d338a7a86be641931010c48
[]
no_license
grighth12/algorithm
f01ba85b75cded2c717666c68aac82ed66d0a563
21778b86e97acc5ffc80d4933855b94b89e9ffd3
refs/heads/main
2023-07-14T15:59:35.078846
2021-08-21T16:45:47
2021-08-21T16:45:47
375,053,162
0
2
null
2021-08-21T16:45:48
2021-06-08T15:10:58
C++
UHC
C++
false
false
1,972
cpp
#include <iostream> #include <vector> #include <queue> #include <cmath> using namespace std; vector<int> parent; struct Edge { int start; int end; int cost; Edge(int start, int end, int cost) { this->start = start; this->end = end; this->cost = cost; } }; struct compare { bool operator()(Edge a, Edge b) { return a.cost < b.cost; } }; struct compare2 { bool operator()(Edge a, Edge b) { return a.cost > b.cost; } }; int Find(int i) { if (parent[i] == i) return i; else { return parent[i] = Find(parent[i]); } } void Union(int a, int b) { int pa = Find(a); int pb = Find(b); parent[pb] = pa; } int main() { ios::sync_with_stdio(false); cin.tie(0); int N, M; cin >> N >> M; parent = vector<int>(N + 1); priority_queue<Edge, vector<Edge>, compare> pq1; priority_queue<Edge, vector<Edge>, compare2> pq2; for (int i = 0; i <= N; i++) { parent[i] = i; } int entry; for (int i = 0; i <= M; i++) { int a, b, c; cin >> a >> b >> c; if (a == 0 && b == 1) { entry = c; continue; } if (a == 1 && b == 0) { entry = c; continue; } // 계산하기 편하기 (오르막길을)0->1, (내리막길을) 1->0으로 치환하여 넣는다. pq1.push(Edge(a, b, c)); pq2.push(Edge(a, b, c)); } int cnt = 0; int cnt_MIN = 0; if (entry == 0) cnt_MIN++; Union(0, 1); while (!pq1.empty()) { Edge now = pq1.top(); pq1.pop(); if (cnt == N-1) break; if (Find(now.start) != Find(now.end)) { if (now.cost == 0) cnt_MIN++; Union(now.start, now.end); cnt++; } } for (int i = 0; i <= N; i++) { parent[i] = i; } int cnt2 = 0; int cnt_MAX = 0; if (entry == 0) cnt_MAX++; Union(0, 1); while (!pq2.empty()) { Edge now = pq2.top(); pq2.pop(); if (cnt2 == N -1) break; if (Find(now.start) != Find(now.end)) { if (now.cost == 0) cnt_MAX++; Union(now.start, now.end); cnt2++; } } cout << (cnt_MAX * cnt_MAX) - (cnt_MIN * cnt_MIN) << "\n"; return 0; }
[ "abc123472000@naver.com" ]
abc123472000@naver.com
e3c7ecc54bb99b9c9ebc1cee71fd73bb154f28cd
4f8e66ebd1bc845ba011907c9fc7c6400dd7a6be
/SDL_Core/src/components/JSONHandler/src/SDLRPCObjectsImpl/V2/AddCommand_requestMarshaller.cpp
c7bbbe2b8c5260a465228b0c27d3361108c7c41b
[]
no_license
zhanzhengxiang/smartdevicelink
0145c304f28fdcebb67d36138a3a34249723ae28
fbf304e5c3b0b269cf37d3ab22ee14166e7a110b
refs/heads/master
2020-05-18T11:54:10.005784
2014-05-18T09:46:33
2014-05-18T09:46:33
20,008,961
1
0
null
null
null
null
UTF-8
C++
false
false
5,066
cpp
// // Copyright (c) 2013, Ford Motor Company // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following // disclaimer in the documentation and/or other materials provided with the // distribution. // // Neither the name of the Ford Motor Company nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include "../include/JSONHandler/SDLRPCObjects/V2/AddCommand_request.h" #include "ImageMarshaller.h" #include "MenuParamsMarshaller.h" #include "AddCommand_requestMarshaller.h" /* interface Ford Sync RAPI version 2.0O date 2012-11-02 generated at Thu Jan 24 06:36:23 2013 source stamp Thu Jan 24 06:35:41 2013 author RC */ using namespace NsSmartDeviceLinkRPCV2; bool AddCommand_requestMarshaller::checkIntegrity(AddCommand_request& s) { return checkIntegrityConst(s); } bool AddCommand_requestMarshaller::fromString(const std::string& s,AddCommand_request& e) { try { Json::Reader reader; Json::Value json; if(!reader.parse(s,json,false)) return false; if(!fromJSON(json,e)) return false; } catch(...) { return false; } return true; } const std::string AddCommand_requestMarshaller::toString(const AddCommand_request& e) { Json::FastWriter writer; return checkIntegrityConst(e) ? writer.write(toJSON(e)) : ""; } bool AddCommand_requestMarshaller::checkIntegrityConst(const AddCommand_request& s) { if(s.cmdID>2000000000) return false; if(s.menuParams && !MenuParamsMarshaller::checkIntegrityConst(*s.menuParams)) return false; if(s.vrCommands) { unsigned int i=s.vrCommands[0].size(); if(i>100 || i<1) return false; while(i--) { if(s.vrCommands[0][i].length()>99) return false; } } if(s.cmdIcon && !ImageMarshaller::checkIntegrityConst(*s.cmdIcon)) return false; return true; } Json::Value AddCommand_requestMarshaller::toJSON(const AddCommand_request& e) { Json::Value json(Json::objectValue); if(!checkIntegrityConst(e)) return Json::Value(Json::nullValue); json["cmdID"]=Json::Value(e.cmdID); if(e.menuParams) json["menuParams"]=MenuParamsMarshaller::toJSON(*e.menuParams); if(e.vrCommands) { unsigned int sz=e.vrCommands->size(); json["vrCommands"]=Json::Value(Json::arrayValue); json["vrCommands"].resize(sz); for(unsigned int i=0;i<sz;i++) json["vrCommands"][i]=Json::Value(e.vrCommands[0][i]); } if(e.cmdIcon) json["cmdIcon"]=ImageMarshaller::toJSON(*e.cmdIcon); return json; } bool AddCommand_requestMarshaller::fromJSON(const Json::Value& json,AddCommand_request& c) { if(c.menuParams) delete c.menuParams; c.menuParams=0; if(c.vrCommands) delete c.vrCommands; c.vrCommands=0; if(c.cmdIcon) delete c.cmdIcon; c.cmdIcon=0; try { if(!json.isObject()) return false; if(!json.isMember("cmdID")) return false; { const Json::Value& j=json["cmdID"]; if(!j.isInt()) return false; c.cmdID=j.asInt(); } if(json.isMember("menuParams")) { const Json::Value& j=json["menuParams"]; c.menuParams=new MenuParams(); if(!MenuParamsMarshaller::fromJSON(j,c.menuParams[0])) return false; } if(json.isMember("vrCommands")) { const Json::Value& j=json["vrCommands"]; if(!j.isArray()) return false; c.vrCommands=new std::vector<std::string>(); c.vrCommands->resize(j.size()); for(unsigned int i=0;i<j.size();i++) if(!j[i].isString()) return false; else c.vrCommands[0][i]=j[i].asString(); } if(json.isMember("cmdIcon")) { const Json::Value& j=json["cmdIcon"]; c.cmdIcon=new Image(); if(!ImageMarshaller::fromJSON(j,c.cmdIcon[0])) return false; } } catch(...) { return false; } return checkIntegrity(c); }
[ "kburdet1@ford.com" ]
kburdet1@ford.com
4b59fd23126ca25e2d7b0a4f631a2788cd5adfc0
d0fb46aecc3b69983e7f6244331a81dff42d9595
/dms-enterprise/include/alibabacloud/dms-enterprise/model/DisableUserResult.h
5bc13bd0a6133a3a9ed99cb8ac85ebab79f2ff32
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,543
h
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #ifndef ALIBABACLOUD_DMS_ENTERPRISE_MODEL_DISABLEUSERRESULT_H_ #define ALIBABACLOUD_DMS_ENTERPRISE_MODEL_DISABLEUSERRESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/dms-enterprise/Dms_enterpriseExport.h> namespace AlibabaCloud { namespace Dms_enterprise { namespace Model { class ALIBABACLOUD_DMS_ENTERPRISE_EXPORT DisableUserResult : public ServiceResult { public: DisableUserResult(); explicit DisableUserResult(const std::string &payload); ~DisableUserResult(); std::string getErrorCode()const; std::string getErrorMessage()const; bool getSuccess()const; protected: void parse(const std::string &payload); private: std::string errorCode_; std::string errorMessage_; bool success_; }; } } } #endif // !ALIBABACLOUD_DMS_ENTERPRISE_MODEL_DISABLEUSERRESULT_H_
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
43fffce2e1704d52ae23d924f572a37085921411
6240d8c171d182e969ec24b9e5f88a8137cfebce
/ZeroJudge/b082. C. 國家寶藏.cpp
bd4f0da8e532c6950ad08d397262c07bef9df13b
[]
no_license
BillySilver/Online-Judge
04e93d05e054df33c054cdfdd1cb89145815ae8b
2d2ba064b01007f9a1a99f427595ae6f807a3d5e
refs/heads/master
2021-07-12T22:21:10.389235
2017-10-14T21:48:38
2017-10-14T21:53:47
106,046,686
0
0
null
null
null
null
UTF-8
C++
false
false
440
cpp
#include <iostream> int n, m, a, b, start; char c, g, s[257], i; struct linked { int l; char w; } st[257]; int main() { for (scanf("%d",&n); n--; ) { scanf("%d%d%c%c%c%d",&m,&a,&g,&c,&g,&b); start = a; st[a].l = b; st[a].w = c; for (i=1; i<m; i++) { scanf("%d%c%c%c%d",&a,&g,&c,&g,&b); st[a].l = b; st[a].w = c; } for(i=0; i<m; i++) { s[i] = st[start].w; start = st[start].l; } s[m] = 0; puts(s); } }
[ "BillySilver@users.noreply.github.com" ]
BillySilver@users.noreply.github.com
6723cdc30d8943e1df89760b2e5ab069e559c146
3dd2b1f5bab48660cf76be0378dbd7334cce9245
/4.1-10.cpp
a59321cc707b2e3aefa29661c9a90eec9b6d2173
[]
no_license
arduino731/ITSE-1307-Intro-to-C-
e682f09f6230b4350f84cf0b9b629a7150efd3dc
330585806942fcc94ec3968448f559f5933a7de6
refs/heads/master
2021-01-19T22:33:49.132070
2017-08-24T04:44:56
2017-08-24T04:44:56
101,254,516
0
0
null
null
null
null
MacCentralEurope
C++
false
false
841
cpp
// This program tests whether or not an initialized value // is equal to a value input by the user // Brian van Vlymen #include <iostream> using namespace std; int main() { int num1, // num1 is not initialized num2 = 5; // num2 has been initialized to 5 cout << "Please enter an integer" << endl; cin >> num1; cout << "num1 = " << num1 << " and num2 = " << num2 << endl; if (num1 == num2) { cout << "The values are the same." << endl; cout << "Hey, thatís a coincidence!" << endl; } else { cout << "The values are not the same" << endl; } system("PAUSE"); return 0; } // -10 missing: Exercise 2: Modify the program so that the user inputs both values to be tested for equality. Make sure you have a prompt for each input. Test the program with pairs of values that are the same and that are different.
[ "arduino731@gmail.com" ]
arduino731@gmail.com
5dd6a979640b9b59993bbc5c5d11b4d6dbf658b0
38c10c01007624cd2056884f25e0d6ab85442194
/content/browser/appcache/appcache_response.cc
014ecfe40736ec16931b19e389166b713934bdfa
[ "BSD-3-Clause" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
14,550
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/appcache/appcache_response.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/compiler_specific.h" #include "base/location.h" #include "base/logging.h" #include "base/numerics/safe_math.h" #include "base/pickle.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_util.h" #include "base/thread_task_runner_handle.h" #include "content/browser/appcache/appcache_storage.h" #include "net/base/completion_callback.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" namespace content { namespace { // Disk cache entry data indices. enum { kResponseInfoIndex, kResponseContentIndex, kResponseMetadataIndex }; // An IOBuffer that wraps a pickle's data. Ownership of the // pickle is transfered to the WrappedPickleIOBuffer object. class WrappedPickleIOBuffer : public net::WrappedIOBuffer { public: explicit WrappedPickleIOBuffer(const base::Pickle* pickle) : net::WrappedIOBuffer(reinterpret_cast<const char*>(pickle->data())), pickle_(pickle) { DCHECK(pickle->data()); } private: ~WrappedPickleIOBuffer() override {} scoped_ptr<const base::Pickle> pickle_; }; } // anon namespace // AppCacheResponseInfo ---------------------------------------------- AppCacheResponseInfo::AppCacheResponseInfo( AppCacheStorage* storage, const GURL& manifest_url, int64 response_id, net::HttpResponseInfo* http_info, int64 response_data_size) : manifest_url_(manifest_url), response_id_(response_id), http_response_info_(http_info), response_data_size_(response_data_size), storage_(storage) { DCHECK(http_info); DCHECK(response_id != kAppCacheNoResponseId); storage_->working_set()->AddResponseInfo(this); } AppCacheResponseInfo::~AppCacheResponseInfo() { storage_->working_set()->RemoveResponseInfo(this); } // HttpResponseInfoIOBuffer ------------------------------------------ HttpResponseInfoIOBuffer::HttpResponseInfoIOBuffer() : response_data_size(kUnkownResponseDataSize) {} HttpResponseInfoIOBuffer::HttpResponseInfoIOBuffer(net::HttpResponseInfo* info) : http_info(info), response_data_size(kUnkownResponseDataSize) {} HttpResponseInfoIOBuffer::~HttpResponseInfoIOBuffer() {} // AppCacheResponseIO ---------------------------------------------- AppCacheResponseIO::AppCacheResponseIO( int64 response_id, int64 group_id, AppCacheDiskCacheInterface* disk_cache) : response_id_(response_id), group_id_(group_id), disk_cache_(disk_cache), entry_(NULL), buffer_len_(0), weak_factory_(this) { } AppCacheResponseIO::~AppCacheResponseIO() { if (entry_) entry_->Close(); } void AppCacheResponseIO::ScheduleIOCompletionCallback(int result) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&AppCacheResponseIO::OnIOComplete, weak_factory_.GetWeakPtr(), result)); } void AppCacheResponseIO::InvokeUserCompletionCallback(int result) { // Clear the user callback and buffers prior to invoking the callback // so the caller can schedule additional operations in the callback. buffer_ = NULL; info_buffer_ = NULL; net::CompletionCallback cb = callback_; callback_.Reset(); cb.Run(result); } void AppCacheResponseIO::ReadRaw(int index, int offset, net::IOBuffer* buf, int buf_len) { DCHECK(entry_); int rv = entry_->Read( index, offset, buf, buf_len, base::Bind(&AppCacheResponseIO::OnRawIOComplete, weak_factory_.GetWeakPtr())); if (rv != net::ERR_IO_PENDING) ScheduleIOCompletionCallback(rv); } void AppCacheResponseIO::WriteRaw(int index, int offset, net::IOBuffer* buf, int buf_len) { DCHECK(entry_); int rv = entry_->Write( index, offset, buf, buf_len, base::Bind(&AppCacheResponseIO::OnRawIOComplete, weak_factory_.GetWeakPtr())); if (rv != net::ERR_IO_PENDING) ScheduleIOCompletionCallback(rv); } void AppCacheResponseIO::OnRawIOComplete(int result) { DCHECK_NE(net::ERR_IO_PENDING, result); OnIOComplete(result); } void AppCacheResponseIO::OpenEntryIfNeeded() { int rv; AppCacheDiskCacheInterface::Entry** entry_ptr = NULL; if (entry_) { rv = net::OK; } else if (!disk_cache_) { rv = net::ERR_FAILED; } else { entry_ptr = new AppCacheDiskCacheInterface::Entry*; open_callback_ = base::Bind(&AppCacheResponseIO::OpenEntryCallback, weak_factory_.GetWeakPtr(), base::Owned(entry_ptr)); rv = disk_cache_->OpenEntry(response_id_, entry_ptr, open_callback_); } if (rv != net::ERR_IO_PENDING) OpenEntryCallback(entry_ptr, rv); } void AppCacheResponseIO::OpenEntryCallback( AppCacheDiskCacheInterface::Entry** entry, int rv) { DCHECK(info_buffer_.get() || buffer_.get()); if (!open_callback_.is_null()) { if (rv == net::OK) { DCHECK(entry); entry_ = *entry; } open_callback_.Reset(); } OnOpenEntryComplete(); } // AppCacheResponseReader ---------------------------------------------- AppCacheResponseReader::AppCacheResponseReader( int64 response_id, int64 group_id, AppCacheDiskCacheInterface* disk_cache) : AppCacheResponseIO(response_id, group_id, disk_cache), range_offset_(0), range_length_(kint32max), read_position_(0), reading_metadata_size_(0), weak_factory_(this) { } AppCacheResponseReader::~AppCacheResponseReader() { } void AppCacheResponseReader::ReadInfo(HttpResponseInfoIOBuffer* info_buf, const net::CompletionCallback& callback) { DCHECK(!callback.is_null()); DCHECK(!IsReadPending()); DCHECK(info_buf); DCHECK(!info_buf->http_info.get()); DCHECK(!buffer_.get()); DCHECK(!info_buffer_.get()); info_buffer_ = info_buf; callback_ = callback; // cleared on completion OpenEntryIfNeeded(); } void AppCacheResponseReader::ContinueReadInfo() { int size = entry_->GetSize(kResponseInfoIndex); if (size <= 0) { ScheduleIOCompletionCallback(net::ERR_CACHE_MISS); return; } buffer_ = new net::IOBuffer(size); ReadRaw(kResponseInfoIndex, 0, buffer_.get(), size); } void AppCacheResponseReader::ReadData(net::IOBuffer* buf, int buf_len, const net::CompletionCallback& callback) { DCHECK(!callback.is_null()); DCHECK(!IsReadPending()); DCHECK(buf); DCHECK(buf_len >= 0); DCHECK(!buffer_.get()); DCHECK(!info_buffer_.get()); buffer_ = buf; buffer_len_ = buf_len; callback_ = callback; // cleared on completion OpenEntryIfNeeded(); } void AppCacheResponseReader::ContinueReadData() { if (read_position_ + buffer_len_ > range_length_) { // TODO(michaeln): What about integer overflows? DCHECK(range_length_ >= read_position_); buffer_len_ = range_length_ - read_position_; } ReadRaw(kResponseContentIndex, range_offset_ + read_position_, buffer_.get(), buffer_len_); } void AppCacheResponseReader::SetReadRange(int offset, int length) { DCHECK(!IsReadPending() && !read_position_); range_offset_ = offset; range_length_ = length; } void AppCacheResponseReader::OnIOComplete(int result) { if (result >= 0) { if (reading_metadata_size_) { DCHECK(reading_metadata_size_ == result); DCHECK(info_buffer_->http_info->metadata); reading_metadata_size_ = 0; } else if (info_buffer_.get()) { // Deserialize the http info structure, ensuring we got headers. base::Pickle pickle(buffer_->data(), result); scoped_ptr<net::HttpResponseInfo> info(new net::HttpResponseInfo); bool response_truncated = false; if (!info->InitFromPickle(pickle, &response_truncated) || !info->headers.get()) { InvokeUserCompletionCallback(net::ERR_FAILED); return; } DCHECK(!response_truncated); info_buffer_->http_info.reset(info.release()); // Also return the size of the response body DCHECK(entry_); info_buffer_->response_data_size = entry_->GetSize(kResponseContentIndex); int64 metadata_size = entry_->GetSize(kResponseMetadataIndex); if (metadata_size > 0) { reading_metadata_size_ = metadata_size; info_buffer_->http_info->metadata = new net::IOBufferWithSize( base::CheckedNumeric<size_t>(metadata_size).ValueOrDie()); ReadRaw(kResponseMetadataIndex, 0, info_buffer_->http_info->metadata.get(), metadata_size); return; } } else { read_position_ += result; } } InvokeUserCompletionCallback(result); } void AppCacheResponseReader::OnOpenEntryComplete() { if (!entry_) { ScheduleIOCompletionCallback(net::ERR_CACHE_MISS); return; } if (info_buffer_.get()) ContinueReadInfo(); else ContinueReadData(); } // AppCacheResponseWriter ---------------------------------------------- AppCacheResponseWriter::AppCacheResponseWriter( int64 response_id, int64 group_id, AppCacheDiskCacheInterface* disk_cache) : AppCacheResponseIO(response_id, group_id, disk_cache), info_size_(0), write_position_(0), write_amount_(0), creation_phase_(INITIAL_ATTEMPT), weak_factory_(this) { } AppCacheResponseWriter::~AppCacheResponseWriter() { } void AppCacheResponseWriter::WriteInfo( HttpResponseInfoIOBuffer* info_buf, const net::CompletionCallback& callback) { DCHECK(!callback.is_null()); DCHECK(!IsWritePending()); DCHECK(info_buf); DCHECK(info_buf->http_info.get()); DCHECK(!buffer_.get()); DCHECK(!info_buffer_.get()); DCHECK(info_buf->http_info->headers.get()); info_buffer_ = info_buf; callback_ = callback; // cleared on completion CreateEntryIfNeededAndContinue(); } void AppCacheResponseWriter::ContinueWriteInfo() { if (!entry_) { ScheduleIOCompletionCallback(net::ERR_FAILED); return; } const bool kSkipTransientHeaders = true; const bool kTruncated = false; base::Pickle* pickle = new base::Pickle; info_buffer_->http_info->Persist(pickle, kSkipTransientHeaders, kTruncated); write_amount_ = static_cast<int>(pickle->size()); buffer_ = new WrappedPickleIOBuffer(pickle); // takes ownership of pickle WriteRaw(kResponseInfoIndex, 0, buffer_.get(), write_amount_); } void AppCacheResponseWriter::WriteData( net::IOBuffer* buf, int buf_len, const net::CompletionCallback& callback) { DCHECK(!callback.is_null()); DCHECK(!IsWritePending()); DCHECK(buf); DCHECK(buf_len >= 0); DCHECK(!buffer_.get()); DCHECK(!info_buffer_.get()); buffer_ = buf; write_amount_ = buf_len; callback_ = callback; // cleared on completion CreateEntryIfNeededAndContinue(); } void AppCacheResponseWriter::ContinueWriteData() { if (!entry_) { ScheduleIOCompletionCallback(net::ERR_FAILED); return; } WriteRaw( kResponseContentIndex, write_position_, buffer_.get(), write_amount_); } void AppCacheResponseWriter::OnIOComplete(int result) { if (result >= 0) { DCHECK(write_amount_ == result); if (!info_buffer_.get()) write_position_ += result; else info_size_ = result; } InvokeUserCompletionCallback(result); } void AppCacheResponseWriter::CreateEntryIfNeededAndContinue() { int rv; AppCacheDiskCacheInterface::Entry** entry_ptr = NULL; if (entry_) { creation_phase_ = NO_ATTEMPT; rv = net::OK; } else if (!disk_cache_) { creation_phase_ = NO_ATTEMPT; rv = net::ERR_FAILED; } else { creation_phase_ = INITIAL_ATTEMPT; entry_ptr = new AppCacheDiskCacheInterface::Entry*; create_callback_ = base::Bind(&AppCacheResponseWriter::OnCreateEntryComplete, weak_factory_.GetWeakPtr(), base::Owned(entry_ptr)); rv = disk_cache_->CreateEntry(response_id_, entry_ptr, create_callback_); } if (rv != net::ERR_IO_PENDING) OnCreateEntryComplete(entry_ptr, rv); } void AppCacheResponseWriter::OnCreateEntryComplete( AppCacheDiskCacheInterface::Entry** entry, int rv) { DCHECK(info_buffer_.get() || buffer_.get()); if (creation_phase_ == INITIAL_ATTEMPT) { if (rv != net::OK) { // We may try to overwrite existing entries. creation_phase_ = DOOM_EXISTING; rv = disk_cache_->DoomEntry(response_id_, create_callback_); if (rv != net::ERR_IO_PENDING) OnCreateEntryComplete(NULL, rv); return; } } else if (creation_phase_ == DOOM_EXISTING) { creation_phase_ = SECOND_ATTEMPT; AppCacheDiskCacheInterface::Entry** entry_ptr = new AppCacheDiskCacheInterface::Entry*; create_callback_ = base::Bind(&AppCacheResponseWriter::OnCreateEntryComplete, weak_factory_.GetWeakPtr(), base::Owned(entry_ptr)); rv = disk_cache_->CreateEntry(response_id_, entry_ptr, create_callback_); if (rv != net::ERR_IO_PENDING) OnCreateEntryComplete(entry_ptr, rv); return; } if (!create_callback_.is_null()) { if (rv == net::OK) entry_ = *entry; create_callback_.Reset(); } if (info_buffer_.get()) ContinueWriteInfo(); else ContinueWriteData(); } // AppCacheResponseMetadataWriter ---------------------------------------------- AppCacheResponseMetadataWriter::AppCacheResponseMetadataWriter( int64 response_id, int64 group_id, AppCacheDiskCacheInterface* disk_cache) : AppCacheResponseIO(response_id, group_id, disk_cache), write_amount_(0), weak_factory_(this) { } AppCacheResponseMetadataWriter::~AppCacheResponseMetadataWriter() { } void AppCacheResponseMetadataWriter::WriteMetadata( net::IOBuffer* buf, int buf_len, const net::CompletionCallback& callback) { DCHECK(!callback.is_null()); DCHECK(!IsIOPending()); DCHECK(buf); DCHECK(buf_len >= 0); DCHECK(!buffer_.get()); buffer_ = buf; write_amount_ = buf_len; callback_ = callback; // cleared on completion OpenEntryIfNeeded(); } void AppCacheResponseMetadataWriter::OnOpenEntryComplete() { if (!entry_) { ScheduleIOCompletionCallback(net::ERR_FAILED); return; } WriteRaw(kResponseMetadataIndex, 0, buffer_.get(), write_amount_); } void AppCacheResponseMetadataWriter::OnIOComplete(int result) { DCHECK(result < 0 || write_amount_ == result); InvokeUserCompletionCallback(result); } } // namespace content
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
a7c16379d3ef8ed8d9302c4550adb58e6ad88d7a
5a3371745de16ae56fb25a1864548f48c3e8f76c
/include/script/engine.h
170cf1ceb055927fca0e285f6ee654485384b955
[ "MIT" ]
permissive
lineCode/libscript
019af52943604278ec9b64a198344ec18d8eed26
d52d673c694d7315fcbccb60a9478bb23ca1d7ed
refs/heads/master
2020-09-30T18:43:43.195467
2019-07-14T10:56:48
2019-07-14T10:56:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,161
h
// Copyright (C) 2018 Vincent Chambrin // This file is part of the libscript library // For conditions of distribution and use, see copyright notice in LICENSE #ifndef LIBSCRIPT_ENGINE_H #define LIBSCRIPT_ENGINE_H #include <map> #include <typeindex> #include <vector> #include "script/exception.h" #include "script/scope.h" #include "script/string.h" #include "script/types.h" #include "script/value.h" #include "script/thisobject.h" #include "script/modulecallbacks.h" namespace script { class Array; class Class; class ClassTemplate; class ClosureType; class Context; class Conversion; class EngineImpl; class Enum; class FunctionBuilder; class FunctionType; class Namespace; class Prototype; class Script; class SourceFile; class TemplateArgumentDeduction; class TemplateParameter; class TypeSystem; namespace compiler { class Compiler; } // namespace compiler namespace interpreter { class Interpreter; } // namespace interpreter namespace program { class Expression; } // namespace program // base class for all engine exception class EngineError : public Exception { public: ErrorCode code_; EngineError(ErrorCode c) : code_(c) {} ErrorCode code() const override { return code_; } }; // errors returned by Engine::construct struct ConstructionError : EngineError { using EngineError::EngineError; }; struct NoMatchingConstructor : ConstructionError { NoMatchingConstructor() : ConstructionError(ErrorCode::E_NoMatchingConstructor) {} }; struct ConstructorIsDeleted : ConstructionError { ConstructorIsDeleted() : ConstructionError(ErrorCode::E_ConstructorIsDeleted) {} }; struct TooManyArgumentInInitialization : ConstructionError { TooManyArgumentInInitialization() : ConstructionError(ErrorCode::E_TooManyArgumentInInitialization) {} }; struct TooFewArgumentInInitialization : ConstructionError { TooFewArgumentInInitialization() : ConstructionError(ErrorCode::E_TooFewArgumentInInitialization) {} }; // error returned by Engine::copy struct CopyError : EngineError { CopyError() : EngineError(ErrorCode::E_CopyError) {} }; // error returned by Engine::cast struct ConversionError : EngineError { ConversionError() : EngineError(ErrorCode::E_ConversionError) {} }; // error returned by Engine::typeId struct UnknownTypeError : EngineError { UnknownTypeError() : EngineError(ErrorCode::E_UnknownTypeError) {} }; // error returned by Engine::eval struct EvaluationError : EngineError { std::string message; EvaluationError(const std::string & mssg) : EngineError(ErrorCode::E_EvaluationError), message(mssg) {} }; class LIBSCRIPT_API Engine { public: Engine(); ~Engine(); Engine(const Engine & other) = delete; void setup(); TypeSystem* typeSystem() const; Value newBool(bool bval); Value newChar(char cval); Value newInt(int ival); Value newFloat(float fval); Value newDouble(double dval); Value newString(const String & sval); struct ArrayType { Type type; }; struct ElementType { Type type; }; struct fail_if_not_instantiated_t {}; static const fail_if_not_instantiated_t FailIfNotInstantiated; Array newArray(ArrayType t); Array newArray(ElementType t); Array newArray(ElementType t, fail_if_not_instantiated_t); Value construct(Type t, const std::vector<Value> & args); /// TODO: remove (depecated) template<typename InitFunc> Value construct(Type t, InitFunc && f) { Value ret = allocate(t); f(ret); return ret; } template<typename T, typename...Args> Value construct(Args&& ... args) { Value ret = allocate(Type::make<T>()); ThisObject self{ ret }; self.init<T>(std::forward<Args>(args)...); return ret; } void destroy(Value val); template<typename T> void destroy(Value val) { ThisObject self{ val }; self.destroy<T>(); free(val); } void manage(Value val); void garbageCollect(); Value allocate(const Type & t); void free(Value & v); bool canCopy(const Type & t); Value copy(const Value & val); bool canConvert(const Type & srcType, const Type & destType) const; Value convert(const Value & val, const Type & type); Namespace rootNamespace() const; Script newScript(const SourceFile & source); bool compile(Script s); void destroy(Script s); Module newModule(const std::string & name); Module newModule(const std::string & name, ModuleLoadFunction load, ModuleCleanupFunction cleanup); Module newModule(const std::string & name, const SourceFile & src); const std::vector<Module> & modules() const; Module getModule(const std::string & name); Type typeId(const std::string & typeName, Scope scope = Scope()) const; Context newContext(); Context currentContext() const; void setContext(Context con); Value eval(const std::string & command); compiler::Compiler* compiler() const; interpreter::Interpreter* interpreter() const; const std::map<std::type_index, Template>& templateMap() const; const std::vector<Script> & scripts() const; EngineImpl * implementation() const; Engine & operator=(const Engine & other) = delete; protected: std::unique_ptr<EngineImpl> d; }; } // namespace script #endif // LIBSCRIPT_ENGINE_H
[ "vincent.chambrin@gmail.com" ]
vincent.chambrin@gmail.com
fea5c2ddb3a2b31a4fbe2c68dbc6415fbe5a5e96
332dea92d05126785186397351c5724469a2e406
/HLS/project_mlp/solution1/syn/systemc/MLP_hiddenlayer1.h
56e3935671d47dac82e0b1d3dcff4e40591c933c
[]
no_license
alexconejo/VivadoProject
962fe3fd3ecfe36515594fab8a3c5344887f25b5
09382812050f8f4deeb22166572d46b4f0861604
refs/heads/main
2023-06-29T12:00:57.924098
2021-08-06T12:58:32
2021-08-06T12:58:32
393,376,090
0
0
null
null
null
null
UTF-8
C++
false
false
2,561
h
// ============================================================== // File generated on Thu Dec 17 22:11:27 +0100 2020 // Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC v2018.3 (64-bit) // SW Build 2405991 on Thu Dec 6 23:38:27 MST 2018 // IP Build 2404404 on Fri Dec 7 01:43:56 MST 2018 // Copyright 1986-2018 Xilinx, Inc. All Rights Reserved. // ============================================================== #ifndef __MLP_hiddenlayer1_H__ #define __MLP_hiddenlayer1_H__ #include <systemc> using namespace sc_core; using namespace sc_dt; #include <iostream> #include <fstream> struct MLP_hiddenlayer1_ram : public sc_core::sc_module { static const unsigned DataWidth = 32; static const unsigned AddressRange = 64; static const unsigned AddressWidth = 6; //latency = 1 //input_reg = 1 //output_reg = 0 sc_core::sc_in <sc_lv<AddressWidth> > address0; sc_core::sc_in <sc_logic> ce0; sc_core::sc_out <sc_lv<DataWidth> > q0; sc_core::sc_in<sc_logic> we0; sc_core::sc_in<sc_lv<DataWidth> > d0; sc_core::sc_in<sc_logic> reset; sc_core::sc_in<bool> clk; sc_lv<DataWidth> ram[AddressRange]; SC_CTOR(MLP_hiddenlayer1_ram) { SC_METHOD(prc_write_0); sensitive<<clk.pos(); } void prc_write_0() { if (ce0.read() == sc_dt::Log_1) { if (we0.read() == sc_dt::Log_1) { if(address0.read().is_01() && address0.read().to_uint()<AddressRange) { ram[address0.read().to_uint()] = d0.read(); q0 = d0.read(); } else q0 = sc_lv<DataWidth>(); } else { if(address0.read().is_01() && address0.read().to_uint()<AddressRange) q0 = ram[address0.read().to_uint()]; else q0 = sc_lv<DataWidth>(); } } } }; //endmodule SC_MODULE(MLP_hiddenlayer1) { static const unsigned DataWidth = 32; static const unsigned AddressRange = 64; static const unsigned AddressWidth = 6; sc_core::sc_in <sc_lv<AddressWidth> > address0; sc_core::sc_in<sc_logic> ce0; sc_core::sc_out <sc_lv<DataWidth> > q0; sc_core::sc_in<sc_logic> we0; sc_core::sc_in<sc_lv<DataWidth> > d0; sc_core::sc_in<sc_logic> reset; sc_core::sc_in<bool> clk; MLP_hiddenlayer1_ram* meminst; SC_CTOR(MLP_hiddenlayer1) { meminst = new MLP_hiddenlayer1_ram("MLP_hiddenlayer1_ram"); meminst->address0(address0); meminst->ce0(ce0); meminst->q0(q0); meminst->we0(we0); meminst->d0(d0); meminst->reset(reset); meminst->clk(clk); } ~MLP_hiddenlayer1() { delete meminst; } };//endmodule #endif
[ "alex.conejo@alu.uclm.es" ]
alex.conejo@alu.uclm.es
0ab53c204727cd2f8fe2f1c3738f1b3c997e6ca6
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_log_1055.cpp
8798944a1e3f3cef14d56e26db9589e8ce7426dd
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
90
cpp
archive_set_error(f->archive, ENOMEM, "Can't allocate data for compression buffer");
[ "993273596@qq.com" ]
993273596@qq.com
ab4ff13f2c083ca1f44ed80aa0d704a2403f1427
14acabf7a6594f054978c95b75cfc4249f7f5651
/image-version/polynomial.h
211d8513be760287ddfa37a52fe02189577bcaf2
[]
no_license
yanyangxiao/VoroApprox
a975b6ede6b27062ffe40ec171f35984d44b990f
5e564e89122be3624cd8d5fd3bddf3ba4517c4f5
refs/heads/master
2023-06-21T21:22:58.167524
2023-06-12T04:24:35
2023-06-12T04:24:35
267,139,048
1
1
null
null
null
null
UTF-8
C++
false
false
8,860
h
/** * author: Yanyang Xiao * email : yanyangxiaoxyy@gmail.com */ #ifndef POLYNOMIAL_H #define POLYNOMIAL_H #include <vector> #include <math.h> #include <Eigen/Eigen> #include "pixelset.h" namespace xyy { template <typename Real> class Polynomial { int tab[3] = { 1, 3, 6 }; private: int _degree; std::vector<Real> _coeff; public: Polynomial(int d = 1) : _degree(d) { } Polynomial(const Polynomial &rhs) { _degree = rhs._degree; _coeff = rhs._coeff; } Polynomial& operator= (const Polynomial &rhs) { _degree = rhs._degree; _coeff = rhs._coeff; return *this; } int degree() const { return _degree; } std::vector<Real>& coefficients() const { return _coeff; } void compute_factors( const unsigned char *image, int width, int height, int channel, const PixelSet* pixels); Real evaluate(int c, Real x, Real y) const; Real evaluate(int c, const Real* p) const { return evaluate(c, p[0], p[1]); } Real compute_energy( const unsigned char *image, int width, int height, int channel, const PixelSet* pixels, int Lp = 2) const; protected: void compute_constant_factors( const unsigned char *image, int width, int height, int channel, const PixelSet* pixels); void compute_linear_factors( const unsigned char *image, int width, int height, int channel, const PixelSet* pixels); void compute_quadratic_factors( const unsigned char *image, int width, int height, int channel, const PixelSet* pixels); }; template <typename Real> void Polynomial<Real>::compute_factors( const unsigned char *image, int width, int height, int channel, const PixelSet* pixels) { if (!image || !pixels) return; switch (_degree) { case 1: compute_linear_factors(image, width, height, channel, pixels); break; case 2: compute_quadratic_factors(image, width, height, channel, pixels); break; default: compute_constant_factors(image, width, height, channel, pixels); break; } } template <typename Real> void Polynomial<Real>::compute_constant_factors( const unsigned char *image, int width, int height, int channel, const PixelSet* pixels) { _coeff.clear(); _coeff.resize(channel, Real(0.0)); int count = 0; for (int j = pixels->ymin; j <= pixels->ymax; ++j) { int lineStart = j * width; int loc = j - pixels->ymin; for (int i = pixels->left[loc]; i <= pixels->right[loc]; ++i) { int pixID = lineStart + i; const unsigned char* pixColor = &image[channel * pixID]; for (int c = 0; c < channel; ++c) { _coeff[c] += pixColor[c]; } ++count; } } if (count > 0) { for (int c = 0; c < channel; ++c) { _coeff[c] /= count; } } } template <typename Real> void Polynomial<Real>::compute_linear_factors( const unsigned char *image, int width, int height, int channel, const PixelSet* pixels) { _coeff.clear(); _coeff.resize(channel * 3); Real ratio = Real(height) / width; Real pixWidth = Real(2.0) / width; Real pixArea = pixWidth * pixWidth; std::vector<Eigen::Matrix3d> matA(channel); std::vector<Eigen::Vector3d> vecB(channel); for (int c = 0; c < channel; ++c) { matA[c].setZero(); vecB[c].setZero(); } Real temp[3]; for (int j = pixels->ymin; j <= pixels->ymax; ++j) { Real y = pixWidth * (j + Real(0.5)) - ratio; int lineStart = j * width; int loc = j - pixels->ymin; for (int i = pixels->left[loc]; i <= pixels->right[loc]; ++i) { Real x = pixWidth * (i + Real(0.5)) - Real(1.0); int pixID = lineStart + i; const unsigned char* pixColor = &image[channel * pixID]; temp[2] = pixArea; temp[0] = x * temp[2]; temp[1] = y * temp[2]; for (int c = 0; c < channel; ++c) { for (int k = 0; k < 3; ++k) { vecB[c](k) += pixColor[c] * temp[k]; matA[c](0, k) += x * temp[k]; matA[c](1, k) += y * temp[k]; matA[c](2, k) += temp[k]; } } } } for (int c = 0; c < channel; ++c) { if (matA[c].determinant() != Real(0.0)) { Eigen::Vector3d vecX = matA[c].colPivHouseholderQr().solve(vecB[c]); _coeff[c * 3] = vecX(0); _coeff[c * 3 + 1] = vecX(1); _coeff[c * 3 + 2] = vecX(2); } else { // back to constant _coeff[c * 3] = Real(0.0); _coeff[c * 3 + 1] = Real(0.0); _coeff[c * 3 + 2] = Real(0.0); if (matA[c](2, 2) != Real(0.0)) { _coeff[c * 3 + 2] = vecB[c](2) / matA[c](2, 2); } } } } template <typename Real> void Polynomial<Real>::compute_quadratic_factors( const unsigned char *image, int width, int height, int channel, const PixelSet* pixels) { _coeff.clear(); _coeff.resize(channel * 6); Real ratio = Real(height) / width; Real pixWidth = Real(2.0) / width; Real pixArea = pixWidth * pixWidth; Eigen::MatrixXd matA[3]; Eigen::VectorXd vecB[3]; for (int c = 0; c < channel; c++) { matA[c] = Eigen::MatrixXd::Zero(6, 6); vecB[c] = Eigen::VectorXd::Zero(6); } Real temp[6]; for (int j = pixels->ymin; j <= pixels->ymax; ++j) { Real y = pixWidth * (j + Real(0.5)) - ratio; int lineStart = j * width; int loc = j - pixels->ymin; for (int i = pixels->left[loc]; i <= pixels->right[loc]; ++i) { Real x = pixWidth * (i + Real(0.5)) - Real(1.0); int pixID = lineStart + i; const unsigned char* pixColor = &image[channel * pixID]; temp[5] = pixArea; temp[0] = x * x * temp[5]; temp[1] = x * y * temp[5]; temp[2] = y * y * temp[5]; temp[3] = x * temp[5]; temp[4] = y * temp[5]; for (int c = 0; c < channel; ++c) { for (int k = 0; k < 6; ++k) { vecB[c](k) += pixColor[c] * temp[k]; matA[c](0, k) += x * x * temp[k]; matA[c](1, k) += x * y * temp[k]; matA[c](2, k) += y * y * temp[k]; matA[c](3, k) += x * temp[k]; matA[c](4, k) += y * temp[k]; matA[c](5, k) += temp[k]; } } } } for (int c = 0; c < channel; ++c) { if (matA[c].determinant() != Real(0.0)) { Eigen::VectorXd vecX = matA[c].colPivHouseholderQr().solve(vecB[c]); for (int k = 0; k < 6; ++k) { _coeff[c * 6 + k] = vecX(k); } } else { // back to linear _coeff[c * 6] = Real(0.0); _coeff[c * 6 + 1] = Real(0.0); _coeff[c * 6 + 2] = Real(0.0); Eigen::Matrix3d matAN; matAN(0, 0) = matA[c](0, 5); matAN(0, 1) = matA[c](1, 5); matAN(0, 2) = matA[c](3, 5); matAN(1, 1) = matA[c](2, 5); matAN(0, 2) = matA[c](4, 5); matAN(2, 2) = matA[c](5, 5); matAN(1, 0) = matAN(0, 1); matAN(2, 0) = matAN(0, 2); matAN(2, 1) = matAN(1, 2); if (matAN.determinant() != Real(0.0)) { Eigen::Vector3d vecBN, vecXN; for (int k = 0; k < 3; ++k) vecBN(k) = vecB[c](k + 3); vecXN = matAN.colPivHouseholderQr().solve(vecBN); for (int k = 0; k < 3; ++k) _coeff[c * 6 + k + 3] = vecXN(k); } else { // back to constant _coeff[c * 6 + 3] = Real(0.0); _coeff[c * 6 + 4] = Real(0.0); _coeff[c * 6 + 5] = Real(0.0); if (matA[c](5, 5) != Real(0.0)) { _coeff[c * 6 + 5] = vecB[c](5) / matA[c](5, 5); } } } } } template <typename Real> Real Polynomial<Real>::evaluate(int c, Real x, Real y) const { Real result = Real(0.0); switch (_degree) { case 0: result = _coeff[c]; break; case 1: result = _coeff[c * 3] * x + _coeff[c * 3 + 1] * y + _coeff[c * 3 + 2]; break; case 2: result = _coeff[c * 6] * x * x + _coeff[c * 6 + 1] * x * y + _coeff[c * 6 + 2] * y * y + _coeff[c * 6 + 3] * x + _coeff[c * 6 + 4] * y + _coeff[c * 6 + 5]; break; } return result; } template <typename Real> Real Polynomial<Real>::compute_energy( const unsigned char *image, int width, int height, int channel, const PixelSet* pixels, int Lp = 2) const { if (!image || !pixels) return Real(0.0); Real ratio = Real(height) / width; Real pixWidth = Real(2.0) / width; Real pixArea = pixWidth * pixWidth; Real result = Real(0.0); for (int j = pixels->ymin; j <= pixels->ymax; ++j) { Real y = pixWidth * (j + Real(0.5)) - ratio; int lineStart = j * width; int loc = j - pixels->ymin; for (int i = pixels->left[loc]; i <= pixels->right[loc]; ++i) { Real x = pixWidth * (i + Real(0.5)) - Real(1.0); int pixID = lineStart + i; const unsigned char* pixColor = &image[channel * pixID]; Real tempEnergy = 0.0; for (int c = 0; c < channel; ++c) { Real approxVal = evaluate(c, x, y); Real pixVal = (Real)pixColor[c]; Real absError = abs(pixVal - approxVal); tempEnergy += std::pow(absError, Lp); } result += tempEnergy * pixArea; } } return result; } } #endif
[ "yanyangxiaoxyy@gmail.com" ]
yanyangxiaoxyy@gmail.com
f84fed42c380b1155664851863d6b0b9ab116f11
a472ef5e4096fbb0684776f17c92c3f9b116c71c
/c++/mpa_ext2/mpa/mpa.cpp
21c3bd79a118ee58bece20e6e61a15dc0078e936
[]
no_license
alishbakanwal/cern_git
d1d53ae0b5355d6123908d4d96076cf8a329c75f
a30d00dbcd8594fcdb7b4ecbf67d279b2073f0b6
refs/heads/master
2020-04-15T13:36:04.857055
2016-11-12T11:16:21
2016-11-12T11:16:21
57,893,770
2
1
null
null
null
null
UTF-8
C++
false
false
16,838
cpp
#include<stdio.h> #include<fstream> #include<iostream> using namespace std; int main() { ifstream dtcinput("dtc.prn", ios::in | ios::binary | ios::ate); ofstream dtcproc("dtcproc.txt"); char *memblock; // int size = 16889; int size = 18522; // stripping away header and extracting first 263 samples // all stub information available in 263 samples by observation if (dtcinput.is_open()) { memblock = new char[size]; dtcinput.seekg(122, ios::beg); dtcinput.read(memblock, size); dtcproc.write(memblock, size); dtcinput.close(); dtcproc.close(); } // processing dtcproc to file stub information according to chip ID ofstream mpa0_f("mpa0_int.txt"); ofstream mpa1_f("mpa1_int.txt"); ofstream mpa2_f("mpa2_int.txt"); ofstream mpa3_f("mpa3_int.txt"); ofstream mpa4_f("mpa4_int.txt"); ofstream mpa5_f("mpa5_int.txt"); ofstream mpa6_f("mpa6_int.txt"); ofstream mpa7_f("mpa7_int.txt"); ifstream dtcproc_o("dtcproc.txt", ios::in | ios::ate | ios::binary); char * chipID; char * douta_0; char * douta_1; char * douta_2; char * douta_3; char * douta_4; char * douta_5; char * douta_6; char * douta_7; int i; int jump_douta = 68; int jump_chipID; if (dtcproc_o.is_open()) { douta_0 = new char[6]; douta_1 = new char[6]; douta_2 = new char[6]; douta_3 = new char[6]; douta_4 = new char[6]; douta_5 = new char[6]; douta_6 = new char[6]; douta_7 = new char[6]; // // for i 0 - 9 // for (i = 0; i < 10; i++) { jump_douta = 68; jump_chipID = 68; //-----chip0 // read dtcproc_o.seekg(9 + i*jump_douta, ios::beg); dtcproc_o.read(douta_0, 6); //write mpa0_f.write(douta_0, 6); mpa0_f << "\n"; //-----chip1 // read dtcproc_o.seekg(16 + i*jump_douta, ios::beg); dtcproc_o.read(douta_1, 6); //write mpa1_f.write(douta_1, 6); mpa1_f << "\n"; //-----chip2 // read dtcproc_o.seekg(23 + i*jump_douta, ios::beg); dtcproc_o.read(douta_2, 6); //write mpa2_f.write(douta_2, 6); mpa2_f << "\n"; //-----chip3 // read dtcproc_o.seekg(30 + i*jump_douta, ios::beg); dtcproc_o.read(douta_3, 6); //write mpa3_f.write(douta_3, 6); mpa3_f << "\n"; //-----chip4 // read dtcproc_o.seekg(37 + i*jump_douta, ios::beg); dtcproc_o.read(douta_4, 6); //write mpa4_f.write(douta_4, 6); mpa4_f << "\n"; //-----chip5 // read dtcproc_o.seekg(44 + i*jump_douta, ios::beg); dtcproc_o.read(douta_5, 6); //write mpa5_f.write(douta_5, 6); mpa5_f << "\n"; //-----chip6 // read dtcproc_o.seekg(51 + i*jump_douta, ios::beg); dtcproc_o.read(douta_6, 6); //write mpa6_f.write(douta_6, 6); mpa6_f << "\n"; //-----chip7 // read dtcproc_o.seekg(58 + i*jump_douta, ios::beg); dtcproc_o.read(douta_7, 6); //write mpa7_f.write(douta_7, 6); mpa7_f << "\n"; } // // for i 10 - 99 // for (i = 0; i < 90; i++) { jump_douta = 70; jump_chipID = 70; //-----chip0 // read dtcproc_o.seekg(691 + i*jump_douta, ios::beg); dtcproc_o.read(douta_0, 6); //write mpa0_f.write(douta_0, 6); mpa0_f << "\n"; //-----chip1 // read dtcproc_o.seekg(698 + i*jump_douta, ios::beg); dtcproc_o.read(douta_1, 6); //write mpa1_f.write(douta_1, 6); mpa1_f << "\n"; //-----chip2 // read dtcproc_o.seekg(705 + i*jump_douta, ios::beg); dtcproc_o.read(douta_2, 6); //write mpa2_f.write(douta_2, 6); mpa2_f << "\n"; //-----chip3 // read dtcproc_o.seekg(712 + i*jump_douta, ios::beg); dtcproc_o.read(douta_3, 6); //write mpa3_f.write(douta_3, 6); mpa3_f << "\n"; //-----chip4 // read dtcproc_o.seekg(719 + i*jump_douta, ios::beg); dtcproc_o.read(douta_4, 6); //write mpa4_f.write(douta_4, 6); mpa4_f << "\n"; //-----chip5 // read dtcproc_o.seekg(726 + i*jump_douta, ios::beg); dtcproc_o.read(douta_5, 6); //write mpa5_f.write(douta_5, 6); mpa5_f << "\n"; //-----chip6 // read dtcproc_o.seekg(733 + i*jump_douta, ios::beg); dtcproc_o.read(douta_6, 6); //write mpa6_f.write(douta_6, 6); mpa6_f << "\n"; //-----chip7 // read dtcproc_o.seekg(740 + i*jump_douta, ios::beg); dtcproc_o.read(douta_7, 6); //write mpa7_f.write(douta_7, 6); mpa7_f << "\n"; } // // for i 100 - 240 // for (i = 0; i < 163; i++) { jump_douta = 72; jump_chipID = 72; //-----chip0 // read dtcproc_o.seekg(6993 + i*jump_douta, ios::beg); dtcproc_o.read(douta_0, 6); //write mpa0_f.write(douta_0, 6); mpa0_f << "\n"; //-----chip1 // read dtcproc_o.seekg(7000 + i*jump_douta, ios::beg); dtcproc_o.read(douta_1, 6); //write mpa1_f.write(douta_1, 6); mpa1_f << "\n"; //-----chip2 // read dtcproc_o.seekg(7007 + i*jump_douta, ios::beg); dtcproc_o.read(douta_2, 6); //write mpa2_f.write(douta_2, 6); mpa2_f << "\n"; //-----chip3 // read dtcproc_o.seekg(7014 + i*jump_douta, ios::beg); dtcproc_o.read(douta_3, 6); //write mpa3_f.write(douta_3, 6); mpa3_f << "\n"; //-----chip4 // read dtcproc_o.seekg(7021 + i*jump_douta, ios::beg); dtcproc_o.read(douta_4, 6); //write mpa4_f.write(douta_4, 6); mpa4_f << "\n"; //-----chip5 // read dtcproc_o.seekg(7028 + i*jump_douta, ios::beg); dtcproc_o.read(douta_5, 6); //write mpa5_f.write(douta_5, 6); mpa5_f << "\n"; //-----chip6 // read dtcproc_o.seekg(7035 + i*jump_douta, ios::beg); dtcproc_o.read(douta_6, 6); //write mpa6_f.write(douta_6, 6); mpa6_f << "\n"; //-----chip7 // read dtcproc_o.seekg(7042 + i*jump_douta, ios::beg); dtcproc_o.read(douta_7, 6); //write mpa7_f.write(douta_7, 6); mpa7_f << "\n"; } dtcproc_o.close(); mpa0_f.close(); mpa1_f.close(); mpa2_f.close(); mpa3_f.close(); mpa4_f.close(); mpa5_f.close(); mpa6_f.close(); mpa7_f.close(); } // // extracting unique stubs // assumption: every stub info corresponding to a chipID is unique // ifstream m0("mpa0_int.txt", ios::in | ios::ate | ios::binary); ifstream m1("mpa1_int.txt", ios::in | ios::ate | ios::binary); ifstream m2("mpa2_int.txt", ios::in | ios::ate | ios::binary); ifstream m3("mpa3_int.txt", ios::in | ios::ate | ios::binary); ifstream m4("mpa4_int.txt", ios::in | ios::ate | ios::binary); ifstream m5("mpa5_int.txt", ios::in | ios::ate | ios::binary); ifstream m6("mpa6_int.txt", ios::in | ios::ate | ios::binary); ifstream m7("mpa7_int.txt", ios::in | ios::ate | ios::binary); ofstream mpa0_fo("mpa0_int2.txt"); ofstream mpa1_fo("mpa1_int2.txt"); ofstream mpa2_fo("mpa2_int2.txt"); ofstream mpa3_fo("mpa3_int2.txt"); ofstream mpa4_fo("mpa4_int2.txt"); ofstream mpa5_fo("mpa5_int2.txt"); ofstream mpa6_fo("mpa6_int2.txt"); ofstream mpa7_fo("mpa7_int2.txt"); char * mem, *mem2; int cond; int j; // //---mpa0--- // if (m0.is_open()) { mem = new char[6]; mem2 = new char[6]; for (j = 0; j < 264; j++) { m0.seekg(0 + j * 8, ios::beg); m0.read(mem2, 6); cond = strcmp(mem, mem2); if (cond == 1 || cond == -1) { mpa0_fo.write(mem2, 6); mpa0_fo << "\n"; } strcpy(mem, mem2); /* cout << mem2 << endl; cout << mem << endl; cout << cond << endl << endl; */ } m0.close(); } // //---mpa0--- // if (m1.is_open()) { mem = new char[6]; mem2 = new char[6]; for (j = 0; j < 264; j++) { m1.seekg(0 + j * 8, ios::beg); m1.read(mem2, 6); cond = strcmp(mem, mem2); if (cond == 1 || cond == -1) { mpa1_fo.write(mem2, 6); mpa1_fo << "\n"; } strcpy(mem, mem2); /* cout << mem2 << endl; cout << mem << endl; cout << cond << endl << endl; */ } m1.close(); } // //---mpa2--- // if (m2.is_open()) { mem = new char[6]; mem2 = new char[6]; for (j = 0; j < 264; j++) { m2.seekg(0 + j * 8, ios::beg); m2.read(mem2, 6); cond = strcmp(mem, mem2); if (cond == 1 || cond == -1) { mpa2_fo.write(mem2, 6); mpa2_fo << "\n"; } strcpy(mem, mem2); /* cout << mem2 << endl; cout << mem << endl; cout << cond << endl << endl; */ } m2.close(); } // //---mpa3--- // if (m3.is_open()) { mem = new char[6]; mem2 = new char[6]; for (j = 0; j < 264; j++) { m3.seekg(0 + j * 8, ios::beg); m3.read(mem2, 6); cond = strcmp(mem, mem2); if (cond == 1 || cond == -1) { mpa3_fo.write(mem2, 6); mpa3_fo << "\n"; } strcpy(mem, mem2); /* cout << mem2 << endl; cout << mem << endl; cout << cond << endl << endl; */ } m3.close(); } // //---mpa4--- // if (m4.is_open()) { mem = new char[6]; mem2 = new char[6]; for (j = 0; j < 264; j++) { m4.seekg(0 + j * 8, ios::beg); m4.read(mem2, 6); cond = strcmp(mem, mem2); if (cond == 1 || cond == -1) { mpa4_fo.write(mem2, 6); mpa4_fo << "\n"; } strcpy(mem, mem2); /* cout << mem2 << endl; cout << mem << endl; cout << cond << endl << endl; */ } m4.close(); } // //---mpa5--- // if (m5.is_open()) { mem = new char[6]; mem2 = new char[6]; for (j = 0; j < 264; j++) { m5.seekg(0 + j * 8, ios::beg); m5.read(mem2, 6); cond = strcmp(mem, mem2); if (cond == 1 || cond == -1) { mpa5_fo.write(mem2, 6); mpa5_fo << "\n"; } strcpy(mem, mem2); /* cout << mem2 << endl; cout << mem << endl; cout << cond << endl << endl; */ } m5.close(); } // //---mpa6--- // if (m6.is_open()) { mem = new char[6]; mem2 = new char[6]; for (j = 0; j < 264; j++) { m6.seekg(0 + j * 8, ios::beg); m6.read(mem2, 6); cond = strcmp(mem, mem2); if (cond == 1 || cond == -1) { mpa6_fo.write(mem2, 6); mpa6_fo << "\n"; } strcpy(mem, mem2); /* cout << mem2 << endl; cout << mem << endl; cout << cond << endl << endl; */ } m6.close(); } // //---mpa7--- // if (m7.is_open()) { mem = new char[6]; mem2 = new char[6]; for (j = 0; j < 264; j++) { m7.seekg(0 + j * 8, ios::beg); m7.read(mem2, 6); cond = strcmp(mem, mem2); if (cond == 1 || cond == -1) { mpa7_fo.write(mem2, 6); mpa7_fo << "\n"; } strcpy(mem, mem2); /* cout << mem2 << endl; cout << mem << endl; cout << cond << endl << endl; */ } m7.close(); } mpa0_fo.close(); mpa1_fo.close(); mpa2_fo.close(); mpa3_fo.close(); mpa4_fo.close(); mpa5_fo.close(); mpa6_fo.close(); mpa7_fo.close(); // // checking for redundant stubs // check applied on first and last stub of every mpa file // ifstream mpa0_of1("mpa0_int2.txt", ios::in | ios::binary | ios::ate); ifstream mpa1_of1("mpa1_int2.txt", ios::in | ios::binary | ios::ate); ifstream mpa2_of1("mpa2_int2.txt", ios::in | ios::binary | ios::ate); ifstream mpa3_of1("mpa3_int2.txt", ios::in | ios::binary | ios::ate); ifstream mpa4_of1("mpa4_int2.txt", ios::in | ios::binary | ios::ate); ifstream mpa5_of1("mpa5_int2.txt", ios::in | ios::binary | ios::ate); ifstream mpa6_of1("mpa6_int2.txt", ios::in | ios::binary | ios::ate); ifstream mpa7_of1("mpa7_int2.txt", ios::in | ios::binary | ios::ate); // final mpa outputs ofstream mpa0_o("mpa0.txt"); ofstream mpa1_o("mpa1.txt"); ofstream mpa2_o("mpa2.txt"); ofstream mpa3_o("mpa3.txt"); ofstream mpa4_o("mpa4.txt"); ofstream mpa5_o("mpa5.txt"); ofstream mpa6_o("mpa6.txt"); ofstream mpa7_o("mpa7.txt"); streampos sizen; char * memX; char * memY; char * memf; char * memff; // //--- mpa0 --- // if (mpa0_of1.is_open()) { sizen = mpa0_of1.tellg(); memX = new char[6]; memY = new char[6]; memf = new char[sizen]; memff = new char[int(sizen) - 6]; mpa0_of1.seekg(0, ios::beg); mpa0_of1.read(memX, 6); mpa0_of1.seekg(int(sizen) - 8, ios::beg); mpa0_of1.read(memY, 6); cond = strcmp(memX, memY); if (*memX != *memY) // don't match { mpa0_of1.seekg(0, ios::beg); mpa0_of1.read(memf, int(sizen)); mpa0_o.write(memf, int(sizen)); } else { mpa0_of1.seekg(0, ios::beg); mpa0_of1.read(memff, int(sizen) -8); mpa0_o.write(memff, int(sizen) - 8); } cout << memX << endl << memY << endl << (*memX != *memY) << endl; mpa0_of1.close(); } // //--- mpa1 --- // if (mpa1_of1.is_open()) { sizen = mpa1_of1.tellg(); memX = new char[6]; memY = new char[6]; memf = new char[sizen]; memff = new char[int(sizen) - 6]; mpa1_of1.seekg(0, ios::beg); mpa1_of1.read(memX, 6); mpa1_of1.seekg(int(sizen) - 8, ios::beg); mpa1_of1.read(memY, 6); cond = strcmp(memX, memY); if (*memX != *memY) // match { mpa1_of1.seekg(0, ios::beg); mpa1_of1.read(memf, int(sizen)); mpa1_o.write(memf, int(sizen)); } else { mpa1_of1.seekg(0, ios::beg); mpa1_of1.read(memf, int(sizen) -8); mpa1_o.write(memf, int(sizen) - 8); } mpa1_of1.close(); } // //--- mpa2 --- // if (mpa2_of1.is_open()) { sizen = mpa2_of1.tellg(); memX = new char[6]; memY = new char[6]; memf = new char[sizen]; memff = new char[int(sizen) - 6]; mpa2_of1.seekg(0, ios::beg); mpa2_of1.read(memX, 6); mpa2_of1.seekg(int(sizen) - 8, ios::beg); mpa2_of1.read(memY, 6); cond = strcmp(memX, memY); if (*memX != *memY) // match { mpa2_of1.seekg(0, ios::beg); mpa2_of1.read(memf, int(sizen)); mpa2_o.write(memf, int(sizen)); } else { mpa2_of1.seekg(0, ios::beg); mpa2_of1.read(memf, int(sizen) - 8); mpa2_o.write(memf, int(sizen) - 8); } mpa2_of1.close(); } // //--- mpa3 --- // if (mpa3_of1.is_open()) { sizen = mpa3_of1.tellg(); memX = new char[6]; memY = new char[6]; memf = new char[sizen]; memff = new char[int(sizen) - 6]; mpa3_of1.seekg(0, ios::beg); mpa3_of1.read(memX, 6); mpa3_of1.seekg(int(sizen) - 8, ios::beg); mpa3_of1.read(memY, 6); cond = strcmp(memX, memY); if (*memX != *memY) // match { mpa3_of1.seekg(0, ios::beg); mpa3_of1.read(memf, int(sizen)); mpa3_o.write(memf, int(sizen)); } else { mpa3_of1.seekg(0, ios::beg); mpa3_of1.read(memf, int(sizen) - 8); mpa3_o.write(memf, int(sizen) - 8); } mpa3_of1.close(); } // //--- mpa4 --- // if (mpa4_of1.is_open()) { sizen = mpa4_of1.tellg(); memX = new char[6]; memY = new char[6]; memf = new char[sizen]; memff = new char[int(sizen) - 6]; mpa4_of1.seekg(0, ios::beg); mpa4_of1.read(memX, 6); mpa4_of1.seekg(int(sizen) - 8, ios::beg); mpa4_of1.read(memY, 6); cond = strcmp(memX, memY); if (*memX != *memY) // match { mpa4_of1.seekg(0, ios::beg); mpa4_of1.read(memf, int(sizen)); mpa4_o.write(memf, int(sizen)); } else { mpa4_of1.seekg(0, ios::beg); mpa4_of1.read(memf, int(sizen) - 8); mpa4_o.write(memf, int(sizen) - 8); } mpa4_of1.close(); } // //--- mpa5 --- // if (mpa5_of1.is_open()) { sizen = mpa5_of1.tellg(); memX = new char[6]; memY = new char[6]; memf = new char[sizen]; memff = new char[int(sizen) - 8]; mpa5_of1.seekg(0, ios::beg); mpa5_of1.read(memX, 6); mpa5_of1.seekg(int(sizen) - 8, ios::beg); mpa5_of1.read(memY, 6); cond = strcmp(memX, memY); if (*memX != *memY) // match { mpa5_of1.seekg(0, ios::beg); mpa5_of1.read(memf, int(sizen)); mpa5_o.write(memf, int(sizen)); } else { mpa5_of1.seekg(0, ios::beg); mpa5_of1.read(memf, int(sizen) - 8); mpa5_o.write(memf, int(sizen) - 8); } mpa5_of1.close(); } // //--- mpa6 --- // if (mpa6_of1.is_open()) { sizen = mpa6_of1.tellg(); memX = new char[6]; memY = new char[6]; memf = new char[sizen]; memff = new char[int(sizen) - 6]; mpa6_of1.seekg(0, ios::beg); mpa6_of1.read(memX, 6); mpa6_of1.seekg(int(sizen) - 8, ios::beg); mpa6_of1.read(memY, 6); cond = strcmp(memX, memY); if (*memX != *memY) // match { mpa6_of1.seekg(0, ios::beg); mpa6_of1.read(memf, int(sizen)); mpa6_o.write(memf, int(sizen)); } else { mpa6_of1.seekg(0, ios::beg); mpa6_of1.read(memf, int(sizen) - 8); mpa6_o.write(memf, int(sizen) - 8); } mpa6_of1.close(); } // //--- mpa7 --- // if (mpa7_of1.is_open()) { sizen = mpa7_of1.tellg(); memX = new char[6]; memY = new char[6]; memf = new char[sizen]; memff = new char[int(sizen) - 6]; mpa7_of1.seekg(0, ios::beg); mpa7_of1.read(memX, 6); mpa7_of1.seekg(int(sizen) - 8, ios::beg); mpa7_of1.read(memY, 6); cond = strcmp(memX, memY); if (*memX != *memY) // match { mpa7_of1.seekg(0, ios::beg); mpa7_of1.read(memf, int(sizen)); mpa7_o.write(memf, int(sizen)); } else { mpa7_of1.seekg(0, ios::beg); mpa7_of1.read(memf, int(sizen) - 8); mpa7_o.write(memf, int(sizen) - 8); } mpa7_of1.close(); } return 0; }
[ "14mseeakanwal@seecs.edu.pk" ]
14mseeakanwal@seecs.edu.pk
5f6a670a4073befe85ddb4f1edf8f5f698ebfacb
9dd079b34e3471676c15e2696aa8b06f1f934a01
/parrGpu/test/mpiCartTest.cpp
fae0442fff9e3dce05299c2a49f14d26b9ea1d49
[]
no_license
rmasti/FEM
536621ecfc3652cb4d9be54fdb54f47a3af2fb5c
ce7142d4cc47442ee3f50461f311c35adb732699
refs/heads/master
2021-06-26T11:42:18.081654
2019-05-14T19:31:55
2019-05-14T19:31:55
145,762,203
0
0
null
null
null
null
UTF-8
C++
false
false
1,696
cpp
# include "mhdRT.hpp" int main(int argc, char * argv[]) { //printf("Run with 12 processors for the example to work\n"); MPI_Init(& argc, &argv); int rank; int size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); double exp=double(log(size))/double(log(2)); int ni, nj; int cnt=size; int n=0; /* * YANG WAY * */ while(cnt >=2) { cnt = cnt/2; n++; } ni = pow(2, (n/2)); nj = pow(2, (n/2) + n%2); printf("nj = %d, ni = %d, n = %d \n", nj, ni, n); /* if (exp == ceil(exp)) { if (int(exp) % 2 == 0) { nj = sqrt(size); ni = sqrt(size); printf("its even and right: %d\n", int(exp)); printf("nj = %d, ni = %d\n", nj, ni); } else { printf("its odd and right: %d\n", int(exp)); nj = sqrt(size/2); ni = 2*sqrt(size/2); printf("nj = %d, ni = %d\n", nj, ni); } } else { printf("its not right\n"); } */ MPI_Barrier(MPI_COMM_WORLD); MPI_Comm com2d; int dim[2] = {nj, ni}; int reorder; int period[2], coord[2]; int id; int u, d, l, r; period[0] = TRUE;//TRUE; period[1] = FALSE;//TRUE; reorder = FALSE; MPI_Cart_create(MPI_COMM_WORLD, 2, dim, period, reorder, &com2d); // create 2d comm //if(rank==size/2){ //printf("\n 0 1 2\n 3 4 5\n 6 7 8\n 9 10 11\n\n"); MPI_Cart_coords(com2d, rank, 2, coord); printf("My rank is %d: My coordinates are %d, %d\n", rank, coord[0], coord[1]); MPI_Cart_shift(com2d, 0, 1, &u, &d); MPI_Cart_shift(com2d, 1, 1, &l, &r); printf("My neighbors are left:%d right:%d up:%d down:%d\n", l, r, u ,d); //} MPI_Finalize(); return 0; }
[ "rlm7819@vt.edu" ]
rlm7819@vt.edu
cd08c7b9f84977f29795ee4ed4f25ad3c1823850
e019ee42ca6c0be65ff3b23d394028b87d9fa13d
/sketches/OpenROV2x/CDeadManSwitch.h
a3a31ab72f1f626b1cce8f28f0918c299d10060b
[ "MIT" ]
permissive
eyoz/openrov-software-arduino
886756d96b34310173645bcbf5fec5a16f9a196a
66291d147a070d94a8ed9ccb06916b828dc24ff9
refs/heads/master
2020-06-02T22:54:34.451463
2019-06-11T09:11:32
2019-06-12T11:37:52
191,334,988
0
0
MIT
2019-06-11T09:09:29
2019-06-11T09:09:28
null
UTF-8
C++
false
false
178
h
#pragma once // Includes #include "CModule.h" class CDeadManSwitch : public CModule { public: virtual void Initialize(); virtual void Update( CCommand& commandIn ); };
[ "charles@openrov.com" ]
charles@openrov.com
ab17bb434ad13536bc7f7ceb138c289d689c9d3c
0876d1a78b7c74df9a3f81668ff69fae6761a577
/OpenGL/Main.cpp
3b8164ff75bbf53dae63b95ee22866bcd095bd8d
[]
no_license
alicetemp/OpenGL_shaders
4f1dcfaca7e0a1e226ef016d162fb0df20359d07
483968b01d617fda2ec4607e9dcb536895a14758
refs/heads/master
2022-04-14T03:47:54.853989
2020-04-13T11:18:31
2020-04-13T11:18:31
255,304,384
0
0
null
null
null
null
UTF-8
C++
false
false
6,379
cpp
#include "glad.h" #include <glfw3.h> #include <iostream> #include "shader_m.h" #include <glm.hpp> #include <gtc/matrix_transform.hpp> #include <gtc/type_ptr.hpp> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow *window); const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); const GLuint WIDTH = 800, HEIGHT = 600; int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", NULL, NULL); glfwMakeContextCurrent(window); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize OpenGL context" << std::endl; return -1; } glEnable(GL_DEPTH_TEST); Shader ourShader("coordinate_system.vs", "coordinate_system.fs"); float vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; // world space positions of our cubes glm::vec3 cubePositions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // texture coord attribute glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); unsigned int texture1, texture2; glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); int width, height, nrChannels; stbi_set_flip_vertically_on_load(true); unsigned char *data = stbi_load("text1.jpg", &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); unsigned char *data2 = stbi_load("text2.jpg", &width, &height, &nrChannels, 0); ourShader.use(); glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), 0); ourShader.setInt("texture2", 1); while (!glfwWindowShouldClose(window)) { processInput(window); glClearColor(0.3f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); ourShader.use(); glm::mat4 view(1.0f); glm::mat4 projection; projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f)); ourShader.setMat4("projection", projection); ourShader.setMat4("view", view); glBindVertexArray(VAO); for (unsigned int i = 0; i < 10; i++) { glm::mat4 model = glm::translate(glm::mat4(1.0f), cubePositions[i]); float angle = 20.0f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } glfwSwapBuffers(window); glfwPollEvents(); } glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glfwTerminate(); return 0; } void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); }
[ "aliceberbeniuk@gmail.com" ]
aliceberbeniuk@gmail.com
7c846f71150b842518af0a6959a0805eeb3afad5
a9ca33f6cb1f373d5e378ce2d26059978fe88832
/src/lib_common/response.hpp
5867224514a093b85b9cb2c321b0cde582d888bb
[]
no_license
gigamantra/asio_perf
31ed51f3b79a005753c614e881f3c8d3e7039d07
a762452c9b71c98c6982d2ad60a089d0514cc90e
refs/heads/master
2021-03-12T20:40:41.242205
2014-05-02T23:55:36
2014-05-02T23:55:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,231
hpp
#ifndef __REST_RESPONSE__ #define __REST_RESPONSE__ #include "message.hpp" #include <boost/asio.hpp> namespace rest { namespace common { /* Represents a HTTP response. It derives most of it's functionality from the message class */ class response : public message { public: // The status of the reply. We will only support a small // subset of http response codes enum status_type { ok, bad_request, unauthorized, internal_server_error, not_implemented }; response(status_type status): _status(status){} public: // Serialize this response to a vector of buffers void to_buffer(vector<boost::asio::const_buffer>& buffer) const; public: // Accessor status_type get_status() { return _status;} // Mutator void set_status(status_type status) {_status = status;} private: // The status of the request status_type _status; }; } // common } // rest #endif //__REST_RESPONSE__
[ "quixver@gmail.com" ]
quixver@gmail.com
ec6791935b5e6722f8978feba1b559ddf90b7440
9e5079222f318f8c4d15cda275e21af0d73fb390
/include/PBR.h
b64005e64f3898e82d40710178f0491a59eb7299
[]
no_license
TomMasdin/PBREngineTEM
936a21308dd99fef55cc4ca51a314dccdbab5d41
7085124089b0757ebf7ac5e21950a6f3d5e85d7c
refs/heads/master
2020-05-30T19:53:02.962637
2019-06-03T04:23:14
2019-06-03T04:23:14
189,933,873
0
0
null
null
null
null
UTF-8
C++
false
false
1,257
h
#pragma once #include <glad/glad.h> #include <GLFW/glfw3.h> #include <STB_IMAGE/stb_image.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <Shader.h> //!< Simple Storage class that holds all the texture information of a PBR object class PBR { private: unsigned int m_albedoMap; // ID for the Albedo texture unsigned int m_normalMap; // ID for the normal texture unsigned int m_metallicMap; // ID for the Metallic Texture unsigned int m_roughnessMap; // ID for the roughness Texture unsigned int m_ambientOccMap; // ID for the ambient occlusion texture unsigned int loadTextures(const char* p_path); // Basic Texture Loader public: PBR(); void bindTextureUnits(); //!< Binds the pbr textures to units 3-7 (must correspond with the information bound to the shader) // Getters and Setters for each texture (Usable at runtime with slight delay) void setAlbedo(const char* p_path); void setNormal(const char* p_path); void setMetallic(const char* p_path); void setRoughness(const char* p_path); void setAmbientOcc(const char* p_path); unsigned int getAlbedo(); unsigned int getNormal(); unsigned int getMetallic(); unsigned int getRoughness(); unsigned int getAmbientOcc(); };
[ "ThomasMasdin@DESKTOP-PIEUFI7" ]
ThomasMasdin@DESKTOP-PIEUFI7
b9c6bbdbe74efd42fc57b07a136aa97b88418b31
fada123fff2570d3cf4c59337e81fa034adb36fc
/src/model/word.h
e15530905bff382792908dd14761eadf3af187cf
[]
no_license
sergburn/firu.qt
db5b52129fd60da00848d1ed58a533ef076576ec
5269933688b62a7366d186a164c8d184532cfcfa
refs/heads/master
2021-01-10T19:10:07.373183
2014-08-09T22:03:51
2014-08-09T22:03:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,418
h
#ifndef WORD_H #define WORD_H #include <QList> #include <QMap> #include <QString> #include <QSharedPointer> #include "model.h" #include "itembase.h" #include "translation.h" class WordQueryAdapter; class Word : public ItemBase { public: typedef QSharedPointer<Word> Ptr; typedef QList<Ptr> List; public: Word( const QString& text, Lang lang ); static Ptr find( qint64 id, Lang src ); static List find( const QString& pattern, Lang lang, TextMatch match = StartsWith, int limit = 0 ); static bool exists( const QString& pattern, Lang lang ); static List filter( const List& list, const QString& pattern, TextMatch match = StartsWith ); static int count( const QString& pattern, Lang lang ); public: void setText( const QString& text ); bool match( const QString& pattern, TextMatch match ); Translation::List translations( Lang trg ); bool addTranslation( const Translation& trans ); bool addTranslation( const QString& text, Lang trg ); private: Word(); Word( Lang lang ); Q_DISABLE_COPY( Word ) virtual bool doInsert(); virtual bool doUpdate(); virtual bool doDelete(); virtual bool doSaveAssociates(); virtual bool doDeleteAssociates(); private slots: void handleTransactionFinish( bool success ); private: QMap<Lang, Translation::List> m_translations; friend class WordQueryAdapter; }; #endif // WORD_H
[ "sergburn@497590ae-b53e-4291-bb47-07b2b5baf046" ]
sergburn@497590ae-b53e-4291-bb47-07b2b5baf046
efebe4200b6fbc444bd7adcb59828ea3d91a2684
c90a56e7d7752b041fc5eb38257c5573cef346c6
/src-macOS/IntStart.cpp
9de50c6cfbb908fe50250c34b0ad6be73f9ab2f2
[]
no_license
random-builder/design_cadquery_ocp
a4c572a72699bad52ca5f43f30bb7c15d89072ff
2af799a9f1b2d81fd39e519b2f73e12b34a14c0a
refs/heads/master
2021-05-21T23:10:23.833461
2020-03-29T15:34:46
2020-03-29T15:34:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,509
cpp
// std lib related includes #include <tuple> // pybind 11 related includes #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace py = pybind11; // Standard Handle #include <Standard_Handle.hxx> // includes to resolve forward declarations #include <gp_Pnt2d.hxx> // module includes #include <IntStart_SITopolTool.hxx> // template related includes // user-defined pre #include "OCP_specific.inc" // user-defined inclusion per module // Module definiiton void register_IntStart(py::module &main_module) { py::module m = static_cast<py::module>(main_module.attr("IntStart")); //Python trampoline classes class Py_IntStart_SITopolTool : public IntStart_SITopolTool{ public: using IntStart_SITopolTool::IntStart_SITopolTool; // public pure virtual TopAbs_State Classify(const gp_Pnt2d & P,const Standard_Real Tol) override { PYBIND11_OVERLOAD_PURE(TopAbs_State,IntStart_SITopolTool,Classify,P,Tol) }; // protected pure virtual // private pure virtual }; // classes static_cast<py::class_<IntStart_SITopolTool ,opencascade::handle<IntStart_SITopolTool>,Py_IntStart_SITopolTool , Standard_Transient>>(m.attr("IntStart_SITopolTool")) // constructors // custom constructors // methods .def("Classify", (TopAbs_State (IntStart_SITopolTool::*)( const gp_Pnt2d & , const Standard_Real ) ) static_cast<TopAbs_State (IntStart_SITopolTool::*)( const gp_Pnt2d & , const Standard_Real ) >(&IntStart_SITopolTool::Classify), R"#(None)#" , py::arg("P"), py::arg("Tol")) .def("DynamicType", (const opencascade::handle<Standard_Type> & (IntStart_SITopolTool::*)() const) static_cast<const opencascade::handle<Standard_Type> & (IntStart_SITopolTool::*)() const>(&IntStart_SITopolTool::DynamicType), R"#(None)#" ) // methods using call by reference i.s.o. return // static methods .def_static("get_type_name_s", (const char * (*)() ) static_cast<const char * (*)() >(&IntStart_SITopolTool::get_type_name), R"#(None)#" ) // static methods using call by reference i.s.o. return // operators // additional methods and static methods ; // functions // ./opencascade/IntStart_SITopolTool.hxx // Additional functions // operators // register typdefs // exceptions // user-defined post-inclusion per module in the body }; // user-defined post-inclusion per module // user-defined post
[ "adam.jan.urbanczyk@gmail.com" ]
adam.jan.urbanczyk@gmail.com
d0f77e0995bacb573fa0fe651d3fe793200a69ff
bd2ce60ab8c4b05158d234637a5212be15d7cf6d
/MainWindow.h
c770fb0a4c20d5dd152426054929f583c4acee0b
[]
no_license
Quentista/editor
fbc7c9f30ff0838b89b0ec6caa470c15c53c064a
8b36c9822880d307ecf56f2cf0c9537296025648
refs/heads/master
2021-01-01T05:50:28.464259
2013-04-25T20:03:28
2013-04-25T20:03:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
656
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QWidget> #include <QDir> class GridWidget; class GridData; class QSignalMapper; class QStringList; class QPushButton; class QLineEdit; class MainWindow : public QWidget { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void createNew(); void trySave(); void tryLoad(); private: QDir m_pixDir; QSignalMapper* m_mapper; QStringList m_pixList; GridData* m_gData; GridWidget* m_gWidget; QPushButton* m_createButton; QPushButton* m_saveButton; QPushButton* m_loadButton; QLineEdit* m_newWidth; QLineEdit* m_newHeight; }; #endif // MAINWINDOW_H
[ "sebastian@devmachine.(none)" ]
sebastian@devmachine.(none)
1d0b49b8f0808723f983c419a8abd26bb4b1d970
b329b74a734175a4efc66b5cec540347193a2d33
/problem_solving/vjudge/25_03_2018_218399/A.cpp
23a59512bf6574525b2eda35fdef2f2b7b2ecba5
[ "MIT" ]
permissive
sazid/codes
c2b9569979fc3461ab51f07212be9ed5b94772e0
6dc5d8967334a132ff9eb7e87f58fe9b11d8abd2
refs/heads/master
2021-01-23T01:01:11.269644
2019-03-16T15:24:44
2019-03-16T15:24:44
85,860,119
0
2
null
null
null
null
UTF-8
C++
false
false
1,195
cpp
#include <bits/stdc++.h> #define rep(T, i, a, b) for (T (i)=(a); (i) < (b); (i)++) #define repe(T, i, a, b) for (T (i)=(a); (i) <= (b); (i)++) #define MOD(n, M) ((((n) % (M)) + (M)) % (M)) #define PB push_back #define F first #define S second #define PI acos(-1) #define PRNT(arr) for (auto i : (arr)) cout << i << " "; cout << endl; #define eps 1e-11 #define len(x) x.size() #define FIN freopen("input.txt", "r", stdin); #define FOUT freopen("output.txt", "w", stdout); #define NL "\n" using namespace std; typedef long long ll; typedef unsigned long ul; typedef unsigned long long ull; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<ii> vii; // double max = numer_limits<double>::max() // double INFINITY = numeric_limits<double>::infinity(); bool game(ull n, ull p) { if (p >= n) return true; if (game(n, p*2) or game(n, p*3) or game(n, p*4) or game(n, p*5) or game(n, p*6) or game(n, p*6) or game(n, p*7) or game(n, p*8) or game(n, p*9)) { return true; } return false; } int main() { ios::sync_with_stdio(0); cin.tie(0); ull n; cin >> n; if (game(n, 1)) { cout << "Stan wins.\n"; } else { cout << "Ollie wins.\n"; } return 0; }
[ "sazidozon@gmail.com" ]
sazidozon@gmail.com
56efae23afbfabe1e76183ade2787de1294753dd
2732338546c64e79ec99e5e1f3a764435ed5bc3f
/backup/Headers/Functionalities.hpp
c868fd6ba0fa3f7bb4bb42a39bc29f3245c15a23
[]
no_license
NightCruiser/NetworkSimTest
b1c7e557e35d7c28f02bf1bccc5006bab262cc88
53f0c638d792ba0f33021ca6c7e338e22d1970b3
refs/heads/main
2023-01-18T23:59:39.090406
2020-11-24T13:03:33
2020-11-24T13:03:33
309,975,537
0
0
null
null
null
null
UTF-8
C++
false
false
188
hpp
#ifndef FUNCTIONALITIES_HPP #define FUNCTIONALITIES_HPP #include "Node.hpp" //class Node; //forward decl new class Functionalities : public Node { }; #endif //FUNCTIONALITIES_HPP
[ "valentin.kriukov@aalto.fi" ]
valentin.kriukov@aalto.fi
3628b4a68b10f134f2f4a1edcb6eb2ba5e7a2fe0
70ffc53a7a906d6da6d635d131fb525618245083
/src/libks/libks/stereo/sparse/sparseconstraints.cpp
ff54762af44f2c3e9f55ba8a9b9cc94b4721c798
[]
no_license
sundsunds/catkin_backup
529c9892655bd0f5035f1b02f0dc0fe945e0080c
04ebec48e26fdf89e13ea0f6086c76ce8119f4ea
refs/heads/master
2021-01-18T23:13:52.830285
2017-04-03T16:38:15
2017-04-03T16:38:15
87,096,984
1
0
null
null
null
null
UTF-8
C++
false
false
2,258
cpp
#include "libks/stereo/sparse/sparseconstraints.h" #include <climits> namespace ks { using namespace cv; using namespace std; /*void SparseConstraints::leftRightConsistency(const vector<Point2f>& leftFeatures, SparseCostCube<short>* costCube) { Mat_<short> costs; int currentRow = -1; int leftIndex = 0; for(int l = 0; l < (int)leftFeatures.size(); l++) { if(int(leftFeatures[l].y) != currentRow) { currentRow = (int)leftFeatures[l].y; costs = costCube->getCosts(currentRow); leftIndex = 0; } short minCost = SHRT_MAX; int leftMin = 0; int r = costCube->getRightMinimumCostIndex(l); for(int l2=0; l2<costs.rows; l2++) if(costs(l2,r) < minCost) { minCost = costs(l2, r); leftMin = l2; } if(leftMin != leftIndex) costCube->invalidateMatch(l); leftIndex++; } } void SparseConstraints::uniquenessConstraint(SparseCostCube<short>* costCube, float uniqueness) { for(int row=0; row<costCube->getRows(); row++) { Mat_<short> costs = costCube->getCosts(row); for(int l=0; l<costs.rows; l++) { int lowestRight = -1; short lowestCost = SHRT_MAX, secondLowestCost = SHRT_MAX; for(int r=0; r<costs.cols; r++) { if(costs(l, r) < lowestCost) { //if(r != lowestRight+1) // We ignore direct neighbors // secondLowestCost = lowestCost; lowestCost = costs(l,r); lowestRight = r; } } if((float)lowestCost / secondLowestCost > uniqueness) costCube->invalidateMatch(row, l); } } }*/ void SparseConstraints::combindedConsistencyUniqueness(SparseCostCube<short>* costCube, float uniqueness) { Mat_<short> costs; int currentRow = -1; for(int l = 0; l < costCube->getLeftFeaturesCount(); l++) { if(costCube->getLeftFeatureRow(l) != currentRow) { currentRow = costCube->getLeftFeatureRow(l); costs = costCube->getCosts(currentRow); } int r = costCube->getRightMinimumCostIndex(l); short minCost = costCube->getCost(l, r); int l1 = costCube->getLeftFeatureIndexInRow(l); for(int l2=0; l2<costs.rows; l2++) { if(l2 == l1) continue; if(costs(l2,r) < minCost/uniqueness) { costCube->invalidateMatch(l); break; } } } } }
[ "sunds1986@139.com" ]
sunds1986@139.com
362cb389e2a4b5dc8413760b83ed5603e3955d75
6877be2c476362205c0c6e507034718d347fb309
/YouTubeDLer/fileentry.h
23dcdbf5533d82bd339b7546e62b1c7e63bdefd4
[]
no_license
AndrewShultz/Lynx
e606ff2bd6a3bcb5b7d6af0dbb4ce1a2f81b7822
15bf40aa769457eb9b922d3b5f627edc555f2098
refs/heads/master
2020-03-27T05:31:18.016114
2020-03-03T20:00:14
2020-03-03T20:00:14
146,028,022
0
0
null
null
null
null
UTF-8
C++
false
false
1,227
h
#ifndef FILEENTRY_H #define FILEENTRY_H #include <stdio.h> #include <math.h> #include <string.h> #include <stdio.h> #include <dirent.h> #include <sys/types.h> #include <QLineEdit> #include "translator.h" #include "downloader.h" #include "titleHolder.h" #define MIN(x,y) ((x) < (y) ? (x) : (y)) using namespace std; class FileEntry: public QObject { Q_OBJECT public: Translator* translator; Downloader* downloader; string flink; string fname; bool fdownloaded; bool fstarted; int id; bool debug; QLineEdit *statustext; QProgressBar *progressBar; TitleHolder *songtext; explicit FileEntry(string outdir, QTableWidget *parent, string link, int inid); ~FileEntry(); bool doesItExist(const std::string& name); void run(); void checkExistingFiles(); double getLDist(const char *s, const char *t); //int ComputeLevenshteinDistance(string source, string target); private slots: void updateName(const TitleHolder *tname); void setName(const char* song); void downloadupdate(const char* percent, const int &id); void downloadsuccessupdate(); void downloadingStatus(); signals: void startDownload(); private: string foutdir; }; #endif
[ "andjshultz@gmail.com" ]
andjshultz@gmail.com
7fa2f8acee78b96b9c941f04153591c1fcf3a38b
be8810995af19a5a336c095462e3714d6458c1c9
/operations.hpp
6b23a7b4bbed39f3de8593877d7e3ce3f25800ce
[]
no_license
zvladn7/derivation
c53ae367d3cb208eea95a1ce1de2c694ba02eed1
df5d06c34fa2b20a479f46d44b57a865a6a8ed8e
refs/heads/master
2020-09-24T09:34:23.076324
2019-12-27T13:37:32
2019-12-27T13:37:32
225,729,892
0
0
null
null
null
null
UTF-8
C++
false
false
1,274
hpp
#ifndef OPERATIONS_HPP #define OPERATIONS_HPP #include <type_traits> #include "basefunctions.hpp" template <class F1, class F2> Add<F1, F2> operator+(const F1& f1, const F2& f2) { return Add<F1, F2>(f1, f2); } template <class F> typename std::enable_if<!std::is_arithmetic<F>::value, Add<F, Const>>::type operator+(double value, const F& f) { return Add<F, Const>(f, Const(value)); } template <class F> typename std::enable_if<!std::is_arithmetic<F>::value, Add<F, Const>>::type operator+(const F& f, double value) { return Add<F, Const>(f, Const(value)); } template <class F1, class F2> Multiply<F1, F2> operator*(const F1& f1, const F2& f2) { return Multiply<F1, F2>(f1, f2); } template <class F> typename std::enable_if<!std::is_arithmetic<F>::value, Multiply<F, Const>>::type operator*(const F& f, double value) { return Multiply<F, Const>(f, Const(value)); } template <class F> typename std::enable_if<!std::is_arithmetic<F>::value, Multiply<F, Const>>::type operator*(double value, const F& f) { return Multiply<F, Const>(f, Const(value)); } template <class F, class Numeric> Power<F> Pow(const F& f, Numeric n) { return Power<F>(f, n); } inline double Pow(double x, double y) { return pow(x, y); } extern Simple X; #endif // OPERATIONS_HPP
[ "zybkin11@gmail.com" ]
zybkin11@gmail.com
e0034e549725989d85ee2c11c25a0d67d820c064
fb6b653d2f1676b40ab75443edc2a3187cf00606
/Chapter18/exercises/18.08/ex_1808.cpp
d8167200d300680036c0ffdab28032b86504d2c3
[]
no_license
wenjing219/Cpp-How-To-Program-9E
4cd923de658a90f3d3bfd0e4c0b3e8505d3a8472
8a6e2d1bc84e94fc598e258b9b151aa40895b21e
refs/heads/master
2021-01-22T22:16:24.824817
2017-03-14T22:14:40
2017-03-14T22:14:40
85,525,193
2
0
null
2017-03-20T02:04:41
2017-03-20T02:04:41
null
UTF-8
C++
false
false
794
cpp
/* * ===================================================================================== * * Filename: ex_1808.cpp * * Description: Exercise 18.08 - Using string Iterators * * Version: 1.0 * Created: 10/02/17 16:23:07 * Revision: none * Compiler: g++ * * Author: Siidney Watson - siidney.watson.work@gmail.com * Organization: LolaDog Studio * * ===================================================================================== */ #include <iostream> #include <string> int main(int argc, const char* argv[]){ std::string str = "now step live..."; std::string::reverse_iterator rit = str.rbegin(); while(rit != str.rend()){ std::cout << *(rit++); } std::cout << std::endl; return 0; }
[ "siidney.watson.work@gmail.com" ]
siidney.watson.work@gmail.com
29ef2c8f9d834dc4f5780655c2f8ec33fa8d9992
c0f22345988a92d9c8837e9c0ce065c2683d78d3
/lib/evaluate.h
9cfbdb7f6c612892259a987c1551b8990210c478
[]
no_license
toneill818/CD_hw2
b9c8de96a67481468f618e6eb582bc241d71f932
999ab5bb777161049e296cb91edd733d011ab28a
refs/heads/master
2021-01-10T02:42:21.689440
2015-10-27T18:44:43
2015-10-27T18:44:43
44,938,754
0
0
null
null
null
null
UTF-8
C++
false
false
4,501
h
// // Created by Thomas O'Neill on 10/6/15. // #ifndef CALC_EVALUATE_H #define CALC_EVALUATE_H #include "ast.cpp" #include "parser.cpp" #include <iostream> // Visitor pattern that will evaluate the expression depending on its most derived class. // It will recurse down until it hits an Integer by calling accept on each expression for // the binary operators. The evaluated value is store in value. struct Eval:Visitor{ // Hold the value of the expression being evaluated Eval():value(0){} // Base case where it returns the integer value by setting value to the integer. void visit(Integer const *e) { value = e->n; } // Add grabs the value from both of its expressions and saves them in arg1 and arg2 // then adds the two together to get the new current value. void visit(Add const *e){ e->e1->accept(*this); int arg1 = value; e->e2->accept(*this); int arg2 = value; value = arg1 + arg2; } // Multiply grabs the value from both of its expressions and saves them in arg1 and arg2 // then multiplies the two to get the new current value. void visit(Multiply const *e){ e->e1->accept(*this); int arg1 = value; e->e2->accept(*this); int arg2 = value; value = (arg2 * arg1); } // Divide grabs the value from both of its expressions and saves them in arg1 and arg2 // then divides the two to get the new current value. void visit(Divide const *e){ e->e1->accept(*this); int arg1 = value; e->e2->accept(*this); int arg2 = value; if(arg2 == 0){ std::cout <<"Error divide by 0\n"; exit(-5); } value = arg1 / arg2; } // Subtract grabs the value from both of its expressions and saves them in arg1 and arg2 // then subtracts the two together to get the new current value. void visit(Subtract const *e){ e->e1->accept(*this); int arg1 = value; e->e2->accept(*this); int arg2 = value; value = arg1 - arg2; } // Mod grabs the value from both of its expressions and saves them in arg1 and arg2 // then takes the modulus of the two to get the new current value. void visit(Mod const *e){ e->e1->accept(*this); int arg1 = value; e->e2->accept(*this); int arg2 = value; value = arg1 % arg2; } void visit(And const *e){ e->e1->accept(*this); bool arg1 = result; // Short circuit if(!arg1) result = arg1; else e->e2->accept(*this); result = arg1 && result; } void visit(Or const *e){ e->e1->accept(*this); bool arg1 = result; e->e2->accept(*this); result = arg1 || result; } //void visit(Not const *e){ //} void visit(Equal const *e){ if (e->e1->type == getIntType()){ e->e1->accept(*this); int arg1 = value; e->e2->accept(*this); result = arg1 == result; }else{ e->e1->accept(*this); bool arg1 = result; e->e2->accept(*this); result = arg1 == result; } } void visit(NotEqual const *e){ if (e->e1->type == getIntType()){ e->e1->accept(*this); int arg1 = value; e->e2->accept(*this); result = arg1 != result; }else{ e->e1->accept(*this); bool arg1 = result; e->e2->accept(*this); result = arg1 != result; } } void visit(LessThan const *e){ e->e1->accept(*this); int arg1 = value; e->e2->accept(*this); result = arg1 < value; } void visit(LessThanEqual const *e){ e->e1->accept(*this); int arg1 = value; e->e2->accept(*this); result = arg1 <= value; } void visit(GreaterThan const *e){ e->e1->accept(*this); int arg1 = value; e->e2->accept(*this); result = arg1 > value; } void visit(GreaterThanEqual const *e){ e->e1->accept(*this); int arg1 = value; e->e2->accept(*this); result = arg1 >= value; } void visit(Boolean const* e){ result = e->value; } int getInt(){return value;} int getBool(){return result;}; private: int value; bool result; }; #endif //CALC_EVALUATE_H
[ "toneill818@gmail.com" ]
toneill818@gmail.com
ec535464d8f81c80c7332cec7ddcaf38fe25a7ad
c8c85850beee91f71cfd2905f5de82ce3c52f34b
/lib/itk/xregITKBackgroundImageWriter.h
bcb993a076f187cd0bcb7f7b87c937d730deaaa5
[ "MIT" ]
permissive
oneorthomedical/xreg
1477c045cafbcbe97d417e22bf54273a4b629272
c06440d7995f8a441420e311bb7b6524452843d3
refs/heads/master
2023-08-25T14:43:14.555069
2021-09-20T04:18:01
2021-09-20T04:18:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,713
h
/* * MIT License * * Copyright (c) 2020 Robert Grupp * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef XREGITKBACKGROUNDIMAGEWRITER_H_ #define XREGITKBACKGROUNDIMAGEWRITER_H_ #include <vector> #include <queue> #include <memory> #include <thread> #include <mutex> #include "xregITKIOUtils.h" namespace xreg { /// \brief Utility class for writing images to disk in the background /// /// Useful when writing out large compressed images, so that processing on other /// image may continue while waiting from previously processed image to be /// written. template <class tImage> class ITKBackgroundImageWriter { public: using ImageType = tImage; using ImagePointer = typename ImageType::Pointer; using size_type = std::size_t; /// \brief Constructor - starts up the image writing threads /// /// If the number of writer threads passed is 0, then the number of threads /// is determined by the number of virtual cores. explicit ITKBackgroundImageWriter(const size_type num_writer_threads = 0) { num_threads_to_use_ = num_writer_threads; if (!num_writer_threads) { num_threads_to_use_ = std::thread::hardware_concurrency(); if (!num_threads_to_use_) { num_threads_to_use_ = 1; } } running_ = true; ThreadObjFn tmp_thread_obj_fn_init = { &running_, &queue_mutex_, &imgs_to_write_, &cur_num_bytes_, &num_imgs_writing_ }; writer_threads_.resize(num_threads_to_use_); for (size_type thread_idx = 0; thread_idx < num_threads_to_use_; ++thread_idx) { writer_threads_[thread_idx].reset(new std::thread(tmp_thread_obj_fn_init)); } } /// \brief Destructor - waits for all images to be written and stops threads ~ITKBackgroundImageWriter() { // wait for all images to be written wait(); // signal the threads to exit running_ = false; // wait for the threads to exit for (size_type thread_idx = 0; thread_idx < num_threads_to_use_; ++thread_idx) { writer_threads_[thread_idx]->join(); } } // no copying ITKBackgroundImageWriter(const ITKBackgroundImageWriter&) = delete; ITKBackgroundImageWriter& operator=(const ITKBackgroundImageWriter&) = delete; /// \brief Adds an image to the queue void add(ImagePointer img, const std::string& path, const bool force_no_compression = false) { ImagePathPair img_path_pair = { img, path, force_no_compression }; const size_type cur_img_num_bytes = GetImageNumBytes(img.GetPointer()); if (max_num_bytes_) { // we're enforcing the maximum amount of memory to queue, we'll need to block // and keep checking until the image is added. while (true) { { std::lock_guard<std::mutex> lock(queue_mutex_); // we can add this image if the queue is empty and no image is currently // being written (we always need to be able to add a single image, // otherwise no work will be done) or adding the current image does not // violate the memory limit. if ((imgs_to_write_.empty() && !num_imgs_writing_) || ((cur_num_bytes_ + cur_img_num_bytes) <= max_num_bytes_)) { imgs_to_write_.push(img_path_pair); cur_num_bytes_ += cur_img_num_bytes; break; } } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } else { // we're not enforcing the maximum amount of memory to queue, this case is // simpler. { std::lock_guard<std::mutex> lock(queue_mutex_); imgs_to_write_.push(img_path_pair); cur_num_bytes_ += cur_img_num_bytes; } } } /// \brief Blocks until the queue is empty - e.g. all images written. void wait() { bool queue_is_empty = false; while (!queue_is_empty || num_imgs_writing_) { { std::lock_guard<std::mutex> lock(queue_mutex_); queue_is_empty = imgs_to_write_.empty(); } if (!queue_is_empty || num_imgs_writing_) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } } /// \brief The maximum number of bytes of raw image buffers to queue for writing /// /// When this limit is reached, calls to add become blocking until enough images /// are written to disk and their memory reclaimed. This should be used to ensure /// that system memory is not exhausted. 0 -> no limit. void set_memory_limit(const size_type max_num_bytes) { max_num_bytes_ = max_num_bytes; } private: struct ImagePathPair { ImagePointer img; std::string path; bool force_no_compression; }; using ImageQueue = std::queue<ImagePathPair>; struct ThreadObjFn { bool* running; std::mutex* queue_mutex; ImageQueue* img_queue; size_type* cur_num_bytes_in_queue; size_type* num_imgs_writing; void operator()() { ImagePathPair cur_img_path_pair; while (*running) { { // get lock on queue, get an image to write if there is one std::lock_guard<std::mutex> lock(*queue_mutex); if (!img_queue->empty()) { cur_img_path_pair = img_queue->front(); img_queue->pop(); ++*num_imgs_writing; } } if (cur_img_path_pair.img && !cur_img_path_pair.path.empty()) { // a valid image and path was removed from the queue, write it! WriteITKImageToDisk(cur_img_path_pair.img.GetPointer(), cur_img_path_pair.path, cur_img_path_pair.force_no_compression); { std::lock_guard<std::mutex> lock(*queue_mutex); *cur_num_bytes_in_queue -= GetImageNumBytes(cur_img_path_pair.img.GetPointer()); --*num_imgs_writing; } // reset cur_img_path_pair.img = 0; cur_img_path_pair.path.clear(); } else { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } } }; static size_type GetImageNumBytes(ImageType* img) { return sizeof(typename ImageType::PixelType) * img->GetPixelContainer()->Capacity(); } std::mutex queue_mutex_; ImageQueue imgs_to_write_; // TODO: I think this may be changed to std::vector<std::thread> due to // move ctors in c++11 std::vector<std::shared_ptr<std::thread>> writer_threads_; size_type num_threads_to_use_ = 0; bool running_ = false; size_type cur_num_bytes_ = 0; size_type max_num_bytes_ = 0; size_type num_imgs_writing_ = 0; }; } // xreg #endif
[ "robert.grupp@gmail.com" ]
robert.grupp@gmail.com
770ac452fd946111ce7d4734504278214c9a66f1
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5634697451274240_1/C++/hugeh0ge/b-large.cpp
a1eae80a13e7f2327324731326a7cf0ccf5ffaf8
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
797
cpp
#include <cstdio> #include <cstring> #include <queue> #include <algorithm> using namespace std; #define INF 0x3fffffff int T; int n; char S[1000]; int main() { scanf("%d", &T); for (int Case=1; Case<=T; Case++) { int val = 0; scanf("%s", S); n = strlen(S); vector<int> segs; char prev = -1; for (int i=n-1; i>=0; i--) { if (S[i] != prev) { if (prev != -1) segs.push_back(prev); } prev = S[i]; } segs.push_back(prev); int ans = 0; while (1) { if (segs.size() == 1 && segs[0] == '+') break; if (segs.empty()) break; segs.pop_back(); ++ans; } printf("Case #%d: %d\n", Case, ans); } }
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
4be09cca22b6cab6067200b4f1c4226d411749f4
927eff7f52e98ec4f5f00c16751981bbdf33489c
/DEU3D_OSG/src/osg/Matrixf.cpp
6279ae7af3052007bc19278053276b0f531bfa54
[]
no_license
Armida220/MyEarth
cafa24cfb6f0eda6b3e68948e60af54a2242eaad
6e8826fbcedff45e119009e49d11179df7c0ec3f
refs/heads/master
2020-03-18T08:52:49.390253
2018-05-22T14:11:27
2018-05-22T14:11:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,330
cpp
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/Matrixf> #include <osg/Matrixd> // specialise Matrix_implementaiton to be Matrixf #define Matrix_implementation Matrixf #ifdef X64 cmm::MemPool osg::RefMatrixf::ms_MemPool(176u, 32u * 1024u, false, "PoolFor[RefMatrixf]"); #else cmm::MemPool osg::RefMatrixf::ms_MemPool(128u, 32u * 1024u, false, "PoolFor[RefMatrixf]"); #endif osg::Matrixf::Matrixf( const osg::Matrixd& mat ) { set(mat.ptr()); } osg::Matrixf& osg::Matrixf::operator = (const osg::Matrixd& rhs) { set(rhs.ptr()); return *this; } void osg::Matrixf::set(const osg::Matrixd& rhs) { set(rhs.ptr()); } // now compile up Matrix via Matrix_implementation #include "Matrix_implementation.cpp"
[ "2415630511@qq.com" ]
2415630511@qq.com
66781bc8b33df3580b0297db4372295f95b9b50e
17d766a296cc6c72499bba01b82d58f7df747b64
/GameWithMinutes.cpp
a6f8e453f6244738d220567b5a696c6f6cb1e230
[]
no_license
Kullsno2/C-Cpp-Programs
1dd7a57cf7e4c70831c5b36566605dc35abdeb67
2b81ddc67f22ada291e85bfc377e59e6833e48fb
refs/heads/master
2021-01-22T21:45:41.214882
2015-11-15T11:15:46
2015-11-15T11:15:46
85,473,174
0
1
null
2017-03-19T12:12:00
2017-03-19T12:11:59
null
UTF-8
C++
false
false
338
cpp
#include<iostream> using namespace std; int main(){ int h1=0,min1=0,h2=0,min2=0 ; cin>>h1>>min1>>h2>>min2 ; int hr, min ; if(h2 > h1) hr = h2-h1; else hr = (24 - h1) + h2; if(min2 < min1){ hr--; min = 60 - (min1 - min2); } else{ min = min2-min1; } cout<<"O JOGO DUROU "<<hr<<" HORA(S) E "<<min<<" MINUTO(S)\n"; }
[ "nanduvinodan2@gmail.com" ]
nanduvinodan2@gmail.com
8c7634f38b96ed110cdf477690784d56d6185ce7
8a51722273549c6ce246b898928ad2f75b81cfab
/ch10/braking.cc
962295c66d9469f279efd136b1f358a94e95e774
[]
no_license
bliutwo/cpp_crash_course
7c19642d8dd333e8efbb51e52f0f4ebd84c7c5ad
d772272304b160e73538cd77fba3133c6e427f0b
refs/heads/master
2022-07-10T13:43:23.227172
2020-05-20T09:29:42
2020-05-20T09:29:42
258,393,615
0
0
null
null
null
null
UTF-8
C++
false
false
358
cc
#include "braking.h" int main() { ServiceBus bus; AutoBrake auto_brake{ [&bus] (const auto& cmd) { bus.publish(cmd); } }; while (true) { // Service bus's event loop auto_brake.observe(SpeedUpdate{ 10L }); auto_brake.observe(CarDetected{ 250L, 25L }); } return 0; }
[ "bliutwo@cs.stanford.edu" ]
bliutwo@cs.stanford.edu
a3f1831f31b61a1aaab442593610b4346f5f8baf
d7d6441be63dfce06bf015cb4cb598fc48a07507
/ch12/ex12_7.cpp
ad106b1ee3b733bd38f86323c921570f23f646dc
[]
no_license
DestinyOMGwz/Cpp-Primer
5bcf2483be0fdce33cd6044aa311f1ee4e64a882
20a57900f5c26d003e758383c2bd303784b66477
refs/heads/master
2020-03-31T00:36:31.949535
2015-03-30T14:44:13
2015-03-30T14:44:13
32,645,515
0
0
null
null
null
null
UTF-8
C++
false
false
787
cpp
// // ex12_7.cpp // Exercise 12.7 // // Created by DestinyOMGwz on 3/23/15 // Copyright (c) 2015 DestinyOMGwz. All rights reserved. // // Redo the previous exercise, this time using shared_ptr. #include <memory> #include <vector> #include <iostream> std::shared_ptr<std::vector<int>> dynamicVector(const std::initializer_list<int> &il); void print(const std::shared_ptr<std::vector<int>> &p); int main() { std::shared_ptr<std::vector<int>> p = dynamicVector(std::initializer_list<int>{ 1, 2, 3, 4, 5, 6, 7 }); print(p); return 0; } std::shared_ptr<std::vector<int>> dynamicVector(const std::initializer_list<int> &il) { return std::make_shared<std::vector<int>>(il); } void print(const std::shared_ptr<std::vector<int>> &p) { for (int i : *p) std::cout << i << std::endl; }
[ "destinyomgwz@gmail.com" ]
destinyomgwz@gmail.com
708a927efd0328316d13de2f67e288353a5e972c
65e3391b6afbef10ec9429ca4b43a26b5cf480af
/HLT/createGRP/lib/AliHLTCreateGRP.h
e2c090ad05168a77a243a7fa6267d6c3129c798a
[ "GPL-1.0-or-later" ]
permissive
alisw/AliRoot
c0976f7105ae1e3d107dfe93578f819473b2b83f
d3f86386afbaac9f8b8658da6710eed2bdee977f
refs/heads/master
2023-08-03T11:15:54.211198
2023-07-28T12:39:57
2023-07-28T12:39:57
53,312,169
61
299
BSD-3-Clause
2023-07-28T13:19:50
2016-03-07T09:20:12
C++
UTF-8
C++
false
false
1,763
h
#ifndef ALI_HLT_CREATE_GRP_H #define ALI_HLT_CREATE_GRP_H // ************************************************************************** // This file is property of and copyright by the ALICE HLT Project * // ALICE Experiment at CERN, All rights reserved. * // * // Primary Authors: David Rohr <drohr@kip.uni-heidelberg.de> * // for The ALICE HLT Project. * // * // Permission to use, copy, modify and distribute this software and its * // documentation strictly for non-commercial purposes is hereby granted * // without fee, provided that the above copyright notice appears in all * // copies and that both the copyright notice and this permission notice * // appear in the supporting documentation. The authors make no claims * // about the suitability of this software for any purpose. It is * // provided "as is" without express or implied warranty. * // * //*************************************************************************** #include <TObject.h> class AliDCSSensor; class AliHLTCreateGRP : public TObject { public: int CreateGRP(Int_t runNumber, TString detectorList, TString beamType, TString runType, UInt_t startShift, UInt_t endShift, Int_t defaults); private: UInt_t createDetectorMask(TObjArray* listOfDetectors); template <typename T> AliDCSSensor* CreateSensor(const char* id, T value, UInt_t starttime, UInt_t endtime); ClassDef(AliHLTCreateGRP, 0); }; #endif
[ "drohr@cern.ch" ]
drohr@cern.ch
0afcdfa6c3c0a40d21d6dc2e3d36ee908b8d1422
824e587893084b194d7f1b167cc8f462c894f616
/src/water.cpp
1794cb173897f01e64a53f04de90fd93f2cae51d
[]
no_license
natsuset/World-of-Balls
79afe7bbf230fd841058158db1079e319f992ad7
e3fa3709c70cd9cb8c39ab974430320d49d81f1f
refs/heads/master
2021-06-04T05:28:56.413978
2021-01-29T11:29:09
2021-01-29T11:29:09
148,488,065
0
0
null
null
null
null
UTF-8
C++
false
false
2,605
cpp
#include "water.h" #include "main.h" #include "ball.h" #define PI 3.1415926535898 Water::Water(float x, float y, color_t color) { this->position = glm::vec3(x, y, 0); this->rotation = 0; speed = 0; allDown = 0; allLeft = 0; allRight = 0; allTop = 0; this->speed_x = 0.05; GLfloat g_vertex_buffer_data[3240] = {};//color_t color_vertex_buffer_data[3240] = {}; double angle = PI; int i,j=0; for(i=0;i<3240;i+=9){ g_vertex_buffer_data[i] = cos(angle) * 1; g_vertex_buffer_data[i + 1] = sin(angle) * 1; g_vertex_buffer_data[i + 2] = 0; g_vertex_buffer_data[i + 3] = cos(angle + PI /180) * 1; g_vertex_buffer_data[i + 4] = sin(angle + PI / 180) * 1; g_vertex_buffer_data[i + 5] = 0; g_vertex_buffer_data[i + 6] = 0; g_vertex_buffer_data[i + 7] = 0; g_vertex_buffer_data[i + 8] = 0; //color_vertex_buffer_data[j++] = COLOR_RED; /* color_vertex_buffer_data[i + 1] = ; color_vertex_buffer_data[i + 2] = ;*/ // color_vertex_buffer_data[i + 3] = ; // color_vertex_buffer_data[i + 4] = ; // color_vertex_buffer_data[i + 5] = ; // color_vertex_buffer_data[i + 6] = ; // color_vertex_buffer_data[i + 7] = ; // color_vertex_buffer_data[i + 8] = ; angle = PI / 180 +angle; } // static const GLfloat vertex_buffer_data[] = { // -0.2, -0.2, 0, // vertex 1 // 0.2, -0.2, 0, // vertex 2 // 0.2, 0.2, 0, // vertex 3 // 0.2, 0.2, 0, // vertex 3 // -0.2, 0.2, 0, // vertex 4 // -0.2, -0.2, 0 // vertex 1 // }; this->object = create3DObject(GL_TRIANGLES, 540, g_vertex_buffer_data, COLOR_BLUE, GL_FILL); } void Water::draw(glm::mat4 VP) { Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 1)); rotate = rotate * glm::translate(glm::vec3(0, 0, 0)); Matrices.model *= (translate * rotate); glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->object); } void Water::set_position(float x, float y) { this->position = glm::vec3(x, y, 0); } void Water::tick() { // this->position.x -= speed; //this->position.y -= speed; //ball1.speed = 0.1; } bounding_box_t Water::bounding_box() { float x = this->position.x, y = this->position.y; bounding_box_t bbox = { x, y, 0.5, 0.5 }; return bbox; }
[ "sowrya1682@gmail.com" ]
sowrya1682@gmail.com
721adf2eca1486cf55d591be0f075056ac55c09f
dd1a4ca7020ba5cac93d90829798a3a6f80d33a1
/others/water/luogu1441.cpp
6a3bb7b413778af97ce0b132392fc250cefd9a7b
[]
no_license
Exbilar/Source
a0f85b8b47840a4212fd4a9f713f978cab13e9a3
b8bc0dc52e51f6c4986bd0f37de61b13d98e6e8c
refs/heads/master
2022-05-03T22:35:57.300520
2022-03-14T09:03:03
2022-03-14T09:03:03
97,890,246
2
1
null
null
null
null
UTF-8
C++
false
false
738
cpp
#include <cstdio> #include <cstring> #include <algorithm> using std :: max; using std :: min; static const int maxm = 1e4 + 10; int A[maxm],f[maxm],vis[maxm]; int n,m,cnt,ans,M; void calc(){ int res = 0; for(int i = 0;i <= M;i++) f[i] = 0; f[0] = 1; for(int i = 1;i <= n;i++){ if(vis[i]) continue; for(int v = M;v >= A[i];v--){ f[v] += f[v - A[i]]; } } for(int i = 1;i <= M;i++) if(f[i]) res++; ans = max(res,ans); } void dfs(int pos,int rmn){ if(!rmn) return calc(),void(); for(int i = pos;i <= n - rmn + 1;i++){ vis[i] = 1; dfs(i + 1,rmn - 1); vis[i] = 0; } } int main(){ scanf("%d%d",&n,&m); for(int i = 1;i <= n;i++) scanf("%d",&A[i]),M += A[i]; dfs(1,m); printf("%d\n",ans); return 0; }
[ "exbilar@gmail.com" ]
exbilar@gmail.com
1623c72537e894d50da1491c75282baeb76b2d00
e9f6461fea7045bb07fc2be09ae1a9ec609b50f0
/光电所/include/Utility/SmartHandle.hpp
0911250055560ab3947eebd52f6cceafe7d8d5ac
[]
no_license
cash2one/important-files
bd1a88ea30e3ff16b4fbba6b4939ab6b13f5a6c8
12aebeae6322fafb89869ab15eac588420cbb004
refs/heads/master
2021-01-15T23:20:54.484632
2012-09-19T04:21:08
2012-09-19T04:21:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,513
hpp
#ifndef __SMART_POINTER_SMART_HANDLE_HPP #define __SMART_POINTER_SMART_HANDLE_HPP #include <Windows.h> #include <Winsvc.h> #include <type_traits> #include <memory> #include <cassert> namespace utility { // Release algorithms (release policies) template<typename T, typename PointedBy> struct CCloseHandle { void operator()(T handle) { ::CloseHandle(handle); } ~CCloseHandle() { } }; template<typename T, typename PointedBy> struct CCloseRegKey { void operator()(T handle) { ::RegCloseKey(handle); } ~CCloseRegKey() { } }; template<typename T, typename PointedBy> struct CCloseLibrary { void operator()(T handle) { ::FreeLibrary(handle); } ~CCloseLibrary() { } }; template<typename T, typename PointedBy> struct CCloseViewOfFile { void operator()(T handle) { ::UnmapViewOfFile(handle); } ~CCloseViewOfFile() { } }; template<typename T, typename PointedBy> struct CCloseService { void operator()(T handle) { ::CloseServiceHandle(handle); } ~CCloseService() { } }; template<typename T, typename PointedBy> struct CCloseFindFile { void operator()(T handle) { ::FindClose(handle); } }; template<typename T, typename PointedBy> struct CCloseIcon { void operator()(T handle) { ::DestroyIcon(handle); } }; // Empty class used as default CAutoHandle template parameter. class CEmptyClass { }; // Class CSmartHandle which implements release policy. // Second template parameter is ReleaseAlgorithm which is template itself. template< typename HandleT, template<typename, typename> class ReleaseAlgorithm, typename PointedBy = CEmptyClass, // used for smart pointers HandleT NULL_VALUE = NULL > class CSmartHandle : private ReleaseAlgorithm<HandleT, PointedBy> { public: typedef HandleT Type; typedef typename std::tr1::remove_pointer<Type>::type RealType; Type m_Handle; public: CSmartHandle() : m_Handle(NULL_VALUE) { } CSmartHandle(const Type &h) : m_Handle(h) { } CSmartHandle(const CSmartHandle &h) { CleanUp(); m_Handle = h.m_Handle; } ~CSmartHandle() { CleanUp(); } CSmartHandle &operator=(const CSmartHandle &rhs) { if( &rhs != this ) { CleanUp(); m_Handle = rhs.m_Handle; } return(*this); } Type &operator=(const Type &hande) { if( hande != m_Handle ) { CleanUp(); m_Handle = hande; } return m_Handle; } operator Type() { return m_Handle; } operator const Type() const { return m_Handle; } Type Get() { return m_Handle; } const Type Get() const { return m_Handle; } PointedBy* operator->() // for using as smart pointer { // NOTE: adding this operator allows to use CAutoHandle object as pointer. // However, if PointedBy is CHandlePlaceHolder (used for handles), // this is not compiled because CHandlePlaceHolder has no functions. // This is exactly what I need. return m_Handle; } bool IsValid() { return m_Handle != NULL_VALUE; } Type Detach() { Type hHandle = m_Handle; m_Handle = NULL_VALUE; return hHandle; } void CleanUp() { if ( m_Handle != NULL_VALUE ) { operator()(m_Handle); m_Handle = NULL_VALUE; } } }; // Client code (definitions of standard Windows handles). typedef CSmartHandle<HANDLE, CCloseHandle> CAutoHandle; typedef CSmartHandle<HKEY, CCloseRegKey> CAutoRegKey; typedef CSmartHandle<PVOID, CCloseViewOfFile> CAutoViewOfFile; typedef CSmartHandle<HMODULE, CCloseLibrary> CAutoLibrary; typedef CSmartHandle<HANDLE, CCloseHandle, CEmptyClass, INVALID_HANDLE_VALUE> CAutoFile; CAutoFile; typedef CSmartHandle<SC_HANDLE, CCloseService> CAutoService; typedef CSmartHandle<HANDLE, CCloseFindFile, CEmptyClass, INVALID_HANDLE_VALUE> CAutoFindFile; typedef CSmartHandle<HICON, CCloseIcon> CAutoIcon; namespace detail { struct IconTag { typedef HICON Type; typedef BOOL (__stdcall *DeletorFunc)(Type); static DeletorFunc GetDeletor() { return &::DestroyIcon; } }; struct BitmapTag { typedef HBITMAP Type; typedef BOOL (__stdcall *DeletorFunc)(HGDIOBJ ); static DeletorFunc GetDeletor() { return &::DeleteObject; } }; struct HandleTag { typedef HANDLE Type; typedef BOOL (__stdcall *DeletorFunc)(Type); static DeletorFunc GetDeletor() { return &::CloseHandle; } }; } template < typename ResourceT > struct DeclareType { typedef ResourceT ResourceType; typedef typename ResourceType::Type Type; typedef std::tr1::shared_ptr<void> ResType; ResType res_; DeclareType() {} DeclareType(const Type &res) : res_(res, ResourceType::GetDeletor()) {} DeclareType(const DeclareType &rhs) : res_(rhs.res_) {} DeclareType &operator=(const Type &res) { if( res_.get() != res ) res_.reset(res, ResourceType::GetDeletor()); return *this; } DeclareType &operator=(const DeclareType &rhs) { if( this != &rhs ) res_ = rhs.res_; return *this; } operator ResType() { return res_; } operator const ResType() const { return res_; } operator Type() { return static_cast<Type>(res_.get()); } operator const Type() const { return static_cast<Type>(res_.get()); } }; template < typename T > bool operator==(const DeclareType<T> &lhs, const DeclareType<T> &rhs) { return lhs.res_ == rhs.res_; } template < typename T > bool operator!=(const DeclareType<T> &lhs, const DeclareType<T> &rhs) { return !(lhs.res_ == rhs.res_); } template < typename T > bool operator==(const DeclareType<T> &lhs, size_t val) { assert(val == 0); return lhs.res_.get() == 0; } template < typename T > bool operator!=(const DeclareType<T> &lhs, size_t val) { assert(val == 0); return !(lhs.res_ == 0); } typedef DeclareType<detail::IconTag> ICONPtr; typedef DeclareType<detail::HandleTag> HANDLEPtr; typedef DeclareType<detail::BitmapTag> BITMAPPtr; } #endif
[ "chenyu2202863@gmail.com@38044a6e-7afd-79ad-2151-d0cf963d283a" ]
chenyu2202863@gmail.com@38044a6e-7afd-79ad-2151-d0cf963d283a
d4fe026a95d531562d1761cea7a670f8cb09a1e1
b94bfc13c1e593bf7393ed6adbcd630cc6692b7a
/wfmaxplugins/max2lev/main.cc
4468fbca9b7ce3b75b33d0e5b4103b7a766c4143
[]
no_license
WorldFoundry/WorldFoundry
341cd45695ab112a92cefd4ade692734e55695b4
5c507edddb84d2b27b7c248fb8aa79c2fdc7ce22
refs/heads/master
2021-01-25T07:27:49.731410
2010-05-06T19:14:28
2010-05-06T19:14:28
641,648
6
0
null
null
null
null
UTF-8
C++
false
false
4,351
cc
/////////////////////////////////////////////////////////////////////////////// // // // main.cc World Foundry // // /////////////////////////////////////////////////////////////////////////////// #include "global.hpp" #include "max2lev.hpp" // C++ header file #include "max2lev.h" // Resource header file #include "../lib/registry.h" // registry reader #include <oas/oad.h> //#include <iffwrite/iffwrite.h> #include "box.h" static LVLExportClassDesc LVLExportCD; // static instance of the export class descriptor HINSTANCE hInstance; // this DLL's instance handle (some Windows thing) Interface* gMaxInterface; // Global pointer to MAX interface class /////////////////////////////////////////////////////////////////////////////// // Functions called by MAX when our DLL is loaded BOOL WINAPI DllMain( HINSTANCE hinstDLL, ULONG fdwReason, LPVOID lpvReserved ) { if ( !hInstance ) { hInstance = hinstDLL; InitCustomControls( hInstance ); InitCommonControls(); } return TRUE; } __declspec( dllexport ) int LibNumberClasses() { return 1; } __declspec( dllexport ) ClassDesc* LibClassDesc( int i ) { assert( i == 0 ); return &LVLExportCD; } __declspec( dllexport ) const TCHAR* LibDescription() { return _T( "World Foundry IFF Level Exporter v" LEVELCON_VER ); } __declspec( dllexport ) ULONG LibVersion() { return VERSION_3DSMAX; } /////////////////////////////////////////////////////////////////////////////// // Miscelaneous support functions (GUI crap, etc.) TCHAR* GetString( int id ) { static TCHAR buf[256]; if ( hInstance ) return LoadString(hInstance, id, buf, sizeof(buf)) ? buf : NULL; return NULL; } static void MessageBox(int s1, int s2) { TSTR str1( GetString( s1 ) ); TSTR str2( GetString( s2 ) ); MessageBox( GetActiveWindow(), str1.data(), str2.data(), MB_OK ); } static int MessageBox(int s1, int s2, int option = MB_OK) { TSTR str1(GetString(s1)); TSTR str2(GetString(s2)); return MessageBox(GetActiveWindow(), str1, str2, option); } static int Alert(int s1, int s2 /*= IDS_LVLEXP*/, int option = MB_OK) { return (int)MessageBox(s1, s2, option); } /////////////////////////////////////////////////////////////////////////////// // Actual methods of the LVLExport class LVLExport::LVLExport() { } LVLExport::~LVLExport() { } int LVLExport::ExtCount() { return 1; } const TCHAR* LVLExport::Ext(int n) // Extensions supported for import/export modules { switch ( n ) { case 0: return _T("lev"); case 1: return _T("iffbin"); default: assert( 0 ); } return _T( "" ); // to shut up compiler } const TCHAR* LVLExport::LongDesc() // Long ASCII description (i.e. "Targa 2.0 Image File") { return ShortDesc(); } const TCHAR* LVLExport::ShortDesc() // Short ASCII description (i.e. "Targa") { return _T("World Foundry Level IFF File"); } const TCHAR* LVLExport::AuthorName() // ASCII Author name { return _T("William B. Norris IV"); } const TCHAR* LVLExport::CopyrightMessage() // ASCII Copyright message { return _T("Copyright 1997-2000 World Foundry Group. All Rights Reserved."); } const TCHAR* LVLExport::OtherMessage1() // Other message #1 { return _T("OtherMessage1"); } const TCHAR* LVLExport::OtherMessage2() // Other message #2 { return _T("OtherMessage2"); } unsigned int LVLExport::Version() // Version number * 100 (i.e. v3.01 = 301) { return VERSION_3DSMAX; } void AboutBox( HWND hDlg ); void LVLExport::ShowAbout( HWND hWnd ) { assert( hWnd ); AboutBox( hWnd ); } extern "C" bool max2ifflvl_Query( ostream& s, SceneEnumProc* theSceneEnum ); int #if MAX_RELEASE < 2000 LVLExport::DoExport( const TCHAR* name, ExpInterface* ei, Interface* gi ) #else LVLExport::DoExport( const TCHAR* name, ExpInterface* ei, Interface* gi, int ) #endif { assert( gi ); gMaxInterface = gi; // Ask the scene to enumerate all of its nodes so we can determine if there are any we can use SceneEnumProc myScene( ei->theScene, gi->GetTime(), gi ); try { ofstream fp( name, ios::out | ios::binary ); max2ifflvl_Query( fp, &myScene ); } catch ( LVLExporterException theException ) { return 0; // Return to MAX with failure } return 1; // Return to MAX with success } //==============================================================================
[ "wbnorris@gmail.com" ]
wbnorris@gmail.com
a00289785c021692ac0fa42c74a6b0e03d8be3b8
aecd7ea7fecd3da5f940c38f15f85c3eb87e7ae3
/src/PageManager.cpp
12416f462684078105e4bf0a42e75c7023601123
[]
no_license
ExecutionHY/Qverwatch
5bc8f304213244c17524b5dd94a839d9abac2f79
51ed34426a45b378fe9e2a7ef033ca660df4de2e
refs/heads/master
2021-06-13T01:27:49.547988
2017-01-09T21:11:58
2017-01-09T21:11:58
76,510,813
0
1
null
null
null
null
UTF-8
C++
false
false
12,363
cpp
// // PageManager.cpp // OpenGL // // Created by Execution on 06/01/2017. // Copyright © 2017 Execution. All rights reserved. // #include "PageManager.hpp" GLFWwindow* window; // 1920 x 1080 int windowWidth = 800; int windowHeight = 600; GLuint DepthTexture; GLuint DepthFrameBuffer; GLuint quad_vertexbuffer; GLuint UIID; GLuint VertexArrayID; GLuint QuadProgramID; GLuint QuadTextureID; GLuint DepthProgramID; GLuint DepthMVPMatrixID; GLuint DepthBiasID; GLuint ShadowMapID; GLuint DepthMVPID; GLuint programID; GLuint MVPMatrixID; GLuint ViewMatrixID; GLuint ModelMatrixID; GLuint ModelView3x3MatrixID; GLuint DiffuseTextureID; GLuint NormalTextureID; GLuint SpecularTextureID; GLuint SurfaceID; GLuint TextureID; GLuint LightID; GLuint LightInvDirID; GLuint HomePageTexture; GLuint DiffuseTexture[1000]; GLuint NormalTexture[1000]; GLuint SpecularTexture[1000]; // particles GLuint ParticleProgramID; GLuint ParticleTextureID; // Vertex shader GLuint CameraRight_worldspace_ID; GLuint CameraUp_worldspace_ID; GLuint ViewProjMatrixID; GLuint ParticleTexture; GLuint UITexture; void initGL() { // Initialise GLFW if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); getchar(); exit(-1); } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Open a window and create its OpenGL context window = glfwCreateWindow( windowWidth, windowHeight, "Qverwatch", NULL, NULL); if( window == NULL ){ fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" ); getchar(); glfwTerminate(); exit(-1); } glfwMakeContextCurrent(window); printf("%d %d\n", windowWidth, windowHeight); glfwGetFramebufferSize(window, &windowWidth, &windowHeight); printf("%d %d\n", windowWidth, windowHeight); // Initialize GLEW glewExperimental = true; // Needed for core profile if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); getchar(); glfwTerminate(); exit(-1); } // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); // Hide the mouse and enable unlimited mouvement glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Set the mouse at the center of the screen glfwPollEvents(); glfwSetCursorPos(window, windowWidth/2, windowHeight/2); // Dark blue background glClearColor(0.0f, 0.0f, 0.1f, 0.0f); glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); glEnable(GL_CULL_FACE); // ***************** For shadow ***************** // the depth program for shader DepthProgramID = LoadShaders("DepthRTT.vertexshader", "DepthRTT.fragmentshader"); DepthMVPMatrixID = glGetUniformLocation(DepthProgramID, "depthMVP"); // Create a depth texture glGenTextures(1, &DepthTexture); glBindTexture(GL_TEXTURE_2D, DepthTexture); // Allocate storage for the texture data glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, DEPTH_TEXTURE_SIZE, DEPTH_TEXTURE_SIZE, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); // Set the default filtering modes glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Set up depth comparison mode glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); // Set up wrapping modes glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); DepthFrameBuffer = 0; // Create FBO to reader depth into glGenFramebuffers(1, &DepthFrameBuffer); glBindFramebuffer(GL_FRAMEBUFFER, DepthFrameBuffer); // Attach the depth texure to it; glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, DepthTexture, 0); // Disable color rendering as there are no color attachments glDrawBuffer(GL_NONE); // Always check that our framebuffer is ok if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) exit(-2); // The quad's FBO. Used only for visualizing the shadowmap. static const GLfloat g_quad_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; glGenBuffers(1, &quad_vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW); // Create and compile our GLSL program from the shaders programID = LoadShaders( "Passthrough.vertexshader", "SimpleTexture.fragmentshader" ); // Create and compile our GLSL program from the shaders QuadProgramID = LoadShaders( "Passthrough.vertexshader", "SimpleTexture.fragmentshader" ); QuadTextureID = glGetUniformLocation(QuadProgramID, "quadTexture"); // Get a handle for uniform TextureID = glGetUniformLocation(QuadProgramID, "myTextureSampler"); UIID = glGetUniformLocation(QuadProgramID, "UI"); // Create and compile our GLSL program from the shaders //programID = LoadShaders( "ShadowMapping.vertexshader", "ShadowMapping.fragmentshader" ); programID = LoadShaders( "MainAdvanced.vertexshader", "MainAdvanced.fragmentshader" ); // Get a handle for our "myTextureSampler" uniform DiffuseTextureID = glGetUniformLocation(programID, "DiffuseTextureSampler"); NormalTextureID = glGetUniformLocation(programID, "NormalTextureSampler"); SpecularTextureID = glGetUniformLocation(programID, "SpecularTextureSampler"); // Get a handle for our "MVP" uniform MVPMatrixID = glGetUniformLocation(programID, "MVP"); ViewMatrixID = glGetUniformLocation(programID, "V"); ModelMatrixID = glGetUniformLocation(programID, "M"); ModelView3x3MatrixID = glGetUniformLocation(programID, "MV3x3"); DepthBiasID = glGetUniformLocation(programID, "DepthBiasMVP"); ShadowMapID = glGetUniformLocation(programID, "shadowMap"); SurfaceID = glGetUniformLocation(programID, "Surface"); DepthMVPID = glGetUniformLocation(programID, "DepthMVP"); // Get a handle for our "LightPosition" uniform --- for spot light LightID = glGetUniformLocation(programID, "LightPosition_worldspace"); // for directional light LightInvDirID = glGetUniformLocation(programID, "LightInvDirection_worldspace"); ParticleProgramID = LoadShaders( "Particle.vertexshader", "Particle.fragmentshader" ); ParticleTextureID = glGetUniformLocation(ParticleProgramID, "myTextureSampler"); // Vertex shader CameraRight_worldspace_ID = glGetUniformLocation(ParticleProgramID, "CameraRight_worldspace"); CameraUp_worldspace_ID = glGetUniformLocation(ParticleProgramID, "CameraUp_worldspace"); ViewProjMatrixID = glGetUniformLocation(ParticleProgramID, "VP"); // ???? init the obj ??? memset(DiffuseTexture, 0, sizeof(DiffuseTexture)); memset(NormalTexture, 0, sizeof(NormalTexture)); memset(SpecularTexture, 0, sizeof(SpecularTexture)); } void loadingPage() { // ***** Loading Page glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render to the screen glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0,0,windowWidth,windowHeight); // Use our shader glUseProgram(QuadProgramID); glUniform1i(UIID, 0); // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, HomePageTexture); // Set our "renderedTexture" sampler to user Texture Unit 0 glUniform1i(TextureID, 0); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Draw the triangle ! // You have to disable GL_COMPARE_R_TO_TEXTURE above in order to see anything ! glDrawArrays(GL_TRIANGLES, 0, 6); // 2*3 indices starting at 0 -> 2 triangles glDisableVertexAttribArray(0); char loading[64] = "LOADING FILES..."; printText2D(loading, windowWidth/2*0.2, windowHeight/2*0.1, 30); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } void selectingPage() { // ***** Selecting Page int pos = 0; bool downReleased = true, upReleased = true; do { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render to the screen glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0,0,windowWidth,windowHeight); // Use our shader glUseProgram(QuadProgramID); glUniform1i(UIID, 0); // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, HomePageTexture); // Set our "renderedTexture" sampler to user Texture Unit 0 glUniform1i(TextureID, 0); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Draw the triangle ! // You have to disable GL_COMPARE_R_TO_TEXTURE above in order to see anything ! glDrawArrays(GL_TRIANGLES, 0, 6); // 2*3 indices starting at 0 -> 2 triangles glDisableVertexAttribArray(0); // **************************** Text 2D ******************************* char ready[64] = "PRESS ENTER TO START"; printText2D(ready, windowWidth/2*0.2, windowHeight/2*0.1, 25); char text1[64] = "hanamura.wav"; printText2D(text1, windowWidth/2*0.1, windowHeight/2*0.8, 20); char text2[64] = "kkk.wav"; printText2D(text2, windowWidth/2*0.1, windowHeight/2*0.75, 20); char arrow[64] = ">"; printText2D(arrow, windowWidth/2*0.07, windowHeight/2*(0.8 - pos*0.05), 20); if (glfwGetKey( window, GLFW_KEY_DOWN ) == GLFW_RELEASE) downReleased = true; if (glfwGetKey( window, GLFW_KEY_DOWN ) == GLFW_PRESS) { if (downReleased) { pos = (pos + 1) % 2; downReleased = false; } } if (glfwGetKey( window, GLFW_KEY_UP ) == GLFW_RELEASE) upReleased = true; if (glfwGetKey( window, GLFW_KEY_UP ) == GLFW_PRESS) { if (upReleased) { pos = (pos + 1) % 2; upReleased = false; } } // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } while ( glfwGetKey(window, GLFW_KEY_ENTER ) != GLFW_PRESS ); }
[ "executionhy@gmail.com" ]
executionhy@gmail.com
50ddf9804a3dbf97fe4b5b94d3572e5a74ecc467
8ac522d6d19225ee863a71d124451cf437d662b7
/vseros/2018/lvl1/5/simple.cpp
c69d20d6a09572c9366896f5b0a9c163cdeb7d68
[]
no_license
Soberjan/Study
86490ba6fa918e977b9a0514a2604ea055167c3a
35ab609290f65fdf144cf2183752b38527f40f16
refs/heads/master
2020-03-28T17:33:10.175534
2020-01-22T17:06:14
2020-01-22T17:06:14
148,800,521
0
0
null
null
null
null
UTF-8
C++
false
false
1,034
cpp
#include <iostream> using namespace std; string s; int main() { //8freopen("tests/00", "r", stdin); cin >> s; int d[4] = {0}; for (int i = 0, p = 0; i < (int)s.size(); i++) if (s[i] == 'N'){ string s1(s.begin() + p, s.begin() + i); d[0] += stoi(s1); p = i + 1; } else if (s[i] == 'S'){ string s1(s.begin() + p, s.begin() + i); d[1] += stoi(s1); p = i + 1; } else if (s[i] == 'E'){ string s1(s.begin() + p, s.begin() + i); d[2] += stoi(s1); p = i + 1; } else if (s[i] == 'W'){ string s1(s.begin() + p, s.begin() + i); d[3] += stoi(s1); p = i + 1; } if (d[0] != d[1]) cout << ( d[0] - d[1] > 0 ? d[0] - d[1] : d[1] - d[0] ) << ( d[0] - d[1] > 0 ? 'N' : 'S' ); if (d[2] != d[3]) cout << ( d[2] - d[3] > 0 ? d[2] - d[3] : d[3] - d[2] ) << ( d[2] - d[3] > 0 ? 'E' : 'W' ); return 0; }
[ "operations.rannsoknir@gmail.com" ]
operations.rannsoknir@gmail.com
39c341b05bfadcbb550287481098215077def7ec
52507f7928ba44b7266eddf0f1a9bf6fae7322a4
/SDK/BP_LeatherColor32_classes.h
2ef5bb3709ed8f1587ba45f049935121db96a890
[]
no_license
LuaFan2/mordhau-sdk
7268c9c65745b7af511429cfd3bf16aa109bc20c
ab10ad70bc80512e51a0319c2f9b5effddd47249
refs/heads/master
2022-11-30T08:14:30.825803
2020-08-13T16:31:27
2020-08-13T16:31:27
287,329,560
1
0
null
null
null
null
UTF-8
C++
false
false
641
h
#pragma once // Name: Mordhau, Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_LeatherColor32.BP_LeatherColor32_C // 0x0000 (0x0068 - 0x0068) class UBP_LeatherColor32_C : public UMordhauColor { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_LeatherColor32.BP_LeatherColor32_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "51294434+LuaFan2@users.noreply.github.com" ]
51294434+LuaFan2@users.noreply.github.com
357481774726713e8537c07b9a186e3568dc6fbf
25796199906079f453a557a5cf73056eef5f9f84
/algoritma_pemrograman_2/contoh2.cpp
8c52cfdbbe7b1a3f12bcc5ea43047c1c07addf47
[]
no_license
cessyzulma/learning_programming_c
78ca7588c17194c41cf02a8e5d545ed39ec07e5b
aa3a6cccabeaf972722a214c148b7d390a04be76
refs/heads/master
2021-05-21T00:39:08.489037
2021-04-13T06:44:37
2021-04-13T06:44:37
252,472,090
0
0
null
null
null
null
UTF-8
C++
false
false
141
cpp
#include <stdio.h> int main () { int i,j; int*p; p=&i; j=i; printf ("Nurul Cessy \n"); printf ( "%d %d %d \n" , i,j,*p ); }
[ "nshinhyezulma@gmail.com" ]
nshinhyezulma@gmail.com
9633e07a58eea79a7f5503ae2501050bdf11b1dd
8c53f6783056563d0070c830b1facfa69d565d3c
/src/helper.h
2249e992d7334d48131a3e9558934de464246ed0
[]
no_license
Shukla-san1/CarND-Path-Planning-Project
9cef7586109aa1068dd2f478fd43dccf3edf607c
dd6c8a61add96d54dda3fbb6a58f705cf98d5a17
refs/heads/master
2021-07-08T15:34:24.231508
2017-10-08T05:06:22
2017-10-08T05:06:22
104,466,064
0
0
null
2017-09-22T11:14:56
2017-09-22T11:14:56
null
UTF-8
C++
false
false
882
h
#ifndef helper_H #define helper_H #include <iostream> #include <chrono> #include <iostream> #include <thread> #include <vector> #include <fstream> #include <math.h> using namespace std; //using std::vector; class helper { public: double pi(); double deg2rad(double x); double rad2deg(double x); string hasData(string s); double distance(double x1, double y1, double x2, double y2); int ClosestWaypoint(double x, double y, const vector<double> &maps_x, const vector<double> &maps_y); int NextWaypoint(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y); vector<double> getFrenet(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y); vector<double> getXY(double s, double d, const vector<double> &maps_s, const vector<double> &maps_x, const vector<double> &maps_y); }; #endif
[ "sshukla@nvidia.com" ]
sshukla@nvidia.com
4476186cd45cb2a9cf95e81d40d8044ba084f62a
4966b3b6600596681af0d7506a2c0914b296abae
/SceneEngine/ExecuteScene.h
ff2329cdcbf20603a2129490bc8ff909a8e9dba5
[ "MIT" ]
permissive
djewsbury/XLE
4200c797e823e683cebb516958ebee5f45a02bf0
f7f63de2c620ed5d0b1292486eb894016932b74b
refs/heads/master
2023-07-03T14:26:38.517034
2023-06-30T03:22:03
2023-06-30T03:22:03
32,975,591
13
6
null
2015-03-27T08:35:02
2015-03-27T08:35:02
null
UTF-8
C++
false
false
2,236
h
// Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #pragma once #include "IScene.h" #include <memory> namespace RenderCore { namespace Techniques { class IPipelineAcceleratorPool; class ParsingContext; class SequencerConfig; class ProjectionDesc; enum class Batch; struct PreparedResourcesVisibility; struct PreregisteredAttachment; }} namespace RenderCore { namespace LightingEngine { class CompiledLightingTechnique; class SequencePlayback; class LightingEngineApparatus; struct LightSourceOperatorDesc; struct ShadowOperatorDesc; }} namespace RenderCore { class IThreadContext; class FrameBufferProperties; } namespace std { template<typename Type> class future; } namespace SceneEngine { void ExecuteSceneRaw( RenderCore::Techniques::ParsingContext& parserContext, const RenderCore::Techniques::IPipelineAcceleratorPool& pipelineAccelerators, RenderCore::Techniques::SequencerConfig& sequencerConfig, const RenderCore::Techniques::ProjectionDesc& view, RenderCore::Techniques::Batch batch, IScene& scene); RenderCore::LightingEngine::SequencePlayback BeginLightingTechnique( RenderCore::Techniques::ParsingContext& parsingContext, SceneEngine::ILightingStateDelegate& lightingState, RenderCore::LightingEngine::CompiledLightingTechnique& compiledTechnique); std::future<RenderCore::Techniques::PreparedResourcesVisibility> PrepareResources( RenderCore::IThreadContext& threadContext, RenderCore::LightingEngine::CompiledLightingTechnique& compiledTechnique, RenderCore::Techniques::IPipelineAcceleratorPool& pipelineAccelerators, IScene& scene); std::shared_ptr<RenderCore::LightingEngine::CompiledLightingTechnique> CreateAndActualizeLightingTechnique( RenderCore::LightingEngine::LightingEngineApparatus& apparatus, IteratorRange<const RenderCore::LightingEngine::LightSourceOperatorDesc*> resolveOperators, IteratorRange<const RenderCore::LightingEngine::ShadowOperatorDesc*> shadowOperators, const RenderCore::LightingEngine::ChainedOperatorDesc* globalOperators, IteratorRange<const RenderCore::Techniques::PreregisteredAttachment*> preregisteredAttachments); }
[ "djewsbury@gmail.com" ]
djewsbury@gmail.com
5f7383d7fdcfbd95280932afaa4fb99d9395a505
74727f5b184e5c6cffcdffa0aede031158d4b6d5
/myArrayExample/src/main.cpp
8b6e1bb9285fcfdac2cbaba46091239dda927270
[]
no_license
ofZach/risdCode
96e0263394dd5da5458c7056db33361a2ce0bed9
f2c94d619aff3964bc7733fcdb8eaa1e75edcf8b
refs/heads/master
2021-01-19T23:47:21.366555
2017-04-22T17:50:44
2017-04-22T17:50:44
89,027,511
2
1
null
null
null
null
UTF-8
C++
false
false
341
cpp
#include "ofMain.h" #include "ofApp.h" //======================================================================== int main( ){ ofSetupOpenGL(1000,100,OF_WINDOW); // <-------- setup the GL context // this kicks off the running of my app // can be OF_WINDOW or OF_FULLSCREEN // pass in width and height too: ofRunApp(new ofApp()); }
[ "zach@yesyesno.com" ]
zach@yesyesno.com
dc5b32aa1c622664fd235576a2657279187eab79
123fc737f01a88e58c6eb3ca7ad0e51e867ff434
/beyondWhittle/inst/testfiles/cube_from_NumericVector/cube_from_NumericVector_DeepState_TestHarness.cpp
8ced879c48eb1f11383a74a75e1fa645a875a4f0
[]
no_license
akhikolla/ClusterTests
e12e5486fc1a80609a956fcb7f432b47e8174b0f
1c7702ba4035511ffe7d4dd27e9021b6962718fe
refs/heads/master
2022-12-10T13:00:09.654663
2020-09-14T19:12:37
2020-09-14T19:12:37
295,513,576
2
0
null
null
null
null
UTF-8
C++
false
false
786
cpp
#include <fstream> #include <RInside.h> #include <iostream> #include <RcppDeepState.h> #include <DeepState.hpp> arma::cube cube_from_NumericVector(NumericVector x); TEST(beyondWhittle_deepstate_test,cube_from_NumericVector_test){ std::ofstream x_stream; RInside(); std::cout << "input starts" << std::endl; NumericVector x = RcppDeepState_NumericVector(); x_stream.open("/home/akolla/R/x86_64-pc-linux-gnu-library/3.6/RcppDeepState/extdata/compileAttributes/beyondWhittle/inst/testfiles/cube_from_NumericVector/inputs/x"); x_stream << x; std::cout << "x values: "<< x << std::endl; x_stream.close(); std::cout << "input ends" << std::endl; try{ cube_from_NumericVector(x); } catch(Rcpp::exception& e){ std::cout<<"Exception Handled"<<std::endl; } }
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
a5a5132ef7cdbcf580cb1b8b089cd835bb5af023
0d066fcbadcdca1aaf5fa14f44b98d835a92a2b8
/src/tests/compiler_tests/EXT_clip_cull_distance_test.cpp
2bb992e875337f5be0f74aae606abb204bbffe88
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
pkucherov/angle
0dedae8a924913410f003d69bc699e88ffdfeb60
ac05066a00a9c7fecbe3c0fe4bf71c3994c8c200
refs/heads/master
2022-10-25T19:21:11.160354
2021-01-11T07:02:16
2021-01-11T08:57:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,285
cpp
// // Copyright 2020 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // EXT_clip_cull_distance_test.cpp: // Test for EXT_clip_cull_distance // #include "tests/test_utils/ShaderExtensionTest.h" namespace { const char EXTPragma[] = "#extension GL_EXT_clip_cull_distance : require\n"; // Shader using gl_ClipDistance and gl_CullDistance const char VertexShaderCompileSucceeds1[] = R"( uniform vec4 uPlane; in vec4 aPosition; void main() { gl_Position = aPosition; gl_ClipDistance[1] = dot(aPosition, uPlane); gl_CullDistance[1] = dot(aPosition, uPlane); })"; // Shader redeclares gl_ClipDistance and gl_CullDistance const char VertexShaderCompileSucceeds2[] = R"( uniform vec4 uPlane; in vec4 aPosition; out highp float gl_ClipDistance[4]; out highp float gl_CullDistance[4]; void main() { gl_Position = aPosition; gl_ClipDistance[gl_MaxClipDistances - 6 + 1] = dot(aPosition, uPlane); gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)] = dot(aPosition, uPlane); gl_CullDistance[gl_MaxCullDistances - 6 + 1] = dot(aPosition, uPlane); gl_CullDistance[gl_MaxCullDistances - int(aPosition.x)] = dot(aPosition, uPlane); })"; // Shader using gl_ClipDistance and gl_CullDistance // But, the sum of the sizes is greater than gl_MaxCombinedClipAndCullDistances const char VertexShaderCompileFails1[] = R"( uniform vec4 uPlane; in vec4 aPosition; void main() { gl_Position = aPosition; gl_ClipDistance[5] = dot(aPosition, uPlane); gl_CullDistance[4] = dot(aPosition, uPlane); })"; // Shader redeclares gl_ClipDistance and gl_CullDistance // But, the sum of the sizes is greater than gl_MaxCombinedClipAndCullDistances const char VertexShaderCompileFails2[] = R"( uniform vec4 uPlane; in vec4 aPosition; out highp float gl_ClipDistance[5]; out highp float gl_CullDistance[4]; void main() { gl_Position = aPosition; gl_ClipDistance[gl_MaxClipDistances - 6 + 1] = dot(aPosition, uPlane); gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)] = dot(aPosition, uPlane); gl_CullDistance[gl_MaxCullDistances - 6 + 1] = dot(aPosition, uPlane); gl_CullDistance[gl_MaxCullDistances - int(aPosition.x)] = dot(aPosition, uPlane); })"; // Shader redeclares gl_ClipDistance // But, the array size is greater than gl_MaxClipDistances const char VertexShaderCompileFails3[] = R"( uniform vec4 uPlane; in vec4 aPosition; out highp float gl_ClipDistance[gl_MaxClipDistances + 1]; void main() { gl_Position = aPosition; gl_ClipDistance[gl_MaxClipDistances - 6 + 1] = dot(aPosition, uPlane); gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)] = dot(aPosition, uPlane); })"; // Access gl_CullDistance with integral constant index // But, the index is greater than gl_MaxCullDistances const char VertexShaderCompileFails4[] = R"( uniform vec4 uPlane; in vec4 aPosition; void main() { gl_Position = aPosition; gl_CullDistance[gl_MaxCullDistances] = dot(aPosition, uPlane); })"; // Shader using gl_ClipDistance and gl_CullDistance const char FragmentShaderCompileSucceeds1[] = R"( out highp vec4 fragColor; void main() { fragColor = vec4(gl_ClipDistance[0], gl_CullDistance[0], 0, 1); })"; // Shader redeclares gl_ClipDistance and gl_CullDistance const char FragmentShaderCompileSucceeds2[] = R"( in highp float gl_ClipDistance[4]; in highp float gl_CullDistance[4]; in highp vec4 aPosition; out highp vec4 fragColor; void main() { fragColor.x = gl_ClipDistance[gl_MaxClipDistances - 6 + 1]; fragColor.y = gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)]; fragColor.z = gl_CullDistance[gl_MaxCullDistances - 6 + 1]; fragColor.w = gl_CullDistance[gl_MaxCullDistances - int(aPosition.x)]; })"; // Shader using gl_ClipDistance and gl_CullDistance // But, the sum of the sizes is greater than gl_MaxCombinedClipAndCullDistances const char FragmentShaderCompileFails1[] = R"( out highp vec4 fragColor; void main() { fragColor = vec4(gl_ClipDistance[4], gl_CullDistance[5], 0, 1); })"; // Shader redeclares gl_ClipDistance and gl_CullDistance // But, the sum of the sizes is greater than gl_MaxCombinedClipAndCullDistances const char FragmentShaderCompileFails2[] = R"( in highp float gl_ClipDistance[5]; in highp float gl_CullDistance[4]; in highp vec4 aPosition; out highp vec4 fragColor; void main() { fragColor.x = gl_ClipDistance[gl_MaxClipDistances - 6 + 1]; fragColor.y = gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)]; fragColor.z = gl_CullDistance[gl_MaxCullDistances - 6 + 1]; fragColor.w = gl_CullDistance[gl_MaxCullDistances - int(aPosition.x)]; })"; // In fragment shader, writing to gl_ClipDistance should be denied. const char FragmentShaderCompileFails3[] = R"( out highp vec4 fragColor; void main() { gl_ClipDistance[0] = 0.0f; fragColor = vec4(1, gl_ClipDistance[0], 0, 1); })"; // In fragment shader, writing to gl_CullDistance should be denied even if redeclaring it with the // array size const char FragmentShaderCompileFails4[] = R"( out highp vec4 fragColor; in highp float gl_CullDistance[1]; void main() { gl_CullDistance[0] = 0.0f; fragColor = vec4(1, gl_CullDistance[0], 0, 1); })"; // Accessing to gl_Clip/CullDistance with non-const index should be denied if the size of // gl_Clip/CullDistance is not decided. const char FragmentShaderCompileFails5[] = R"( out highp vec4 fragColor; void main() { medium float color[3]; for(int i = 0 ; i < 3 ; i++) { color[i] = gl_CullDistance[i]; } fragColor = vec4(color[0], color[1], color[2], 1.0f); })"; class EXTClipCullDistanceTest : public sh::ShaderExtensionTest { public: void InitializeCompiler(ShShaderOutput shaderOutputType, GLenum shaderType) { DestroyCompiler(); mCompiler = sh::ConstructCompiler(shaderType, testing::get<0>(GetParam()), shaderOutputType, &mResources); ASSERT_TRUE(mCompiler != nullptr) << "Compiler could not be constructed."; } testing::AssertionResult TestShaderCompile(const char *pragma) { const char *shaderStrings[] = {testing::get<1>(GetParam()), pragma, testing::get<2>(GetParam())}; bool success = sh::Compile(mCompiler, shaderStrings, 3, SH_VARIABLES | SH_OBJECT_CODE); if (success) { return ::testing::AssertionSuccess() << "Compilation success"; } return ::testing::AssertionFailure() << sh::GetInfoLog(mCompiler); } void SetExtensionEnable(bool enable) { // GL_APPLE_clip_distance is implicitly enabled when GL_EXT_clip_cull_distance is enabled #if defined(ANGLE_ENABLE_VULKAN) mResources.APPLE_clip_distance = enable; #endif mResources.EXT_clip_cull_distance = enable; } }; class EXTClipCullDistanceForVertexShaderTest : public EXTClipCullDistanceTest { public: void InitializeCompiler() { InitializeCompiler(SH_GLSL_450_CORE_OUTPUT); } void InitializeCompiler(ShShaderOutput shaderOutputType) { EXTClipCullDistanceTest::InitializeCompiler(shaderOutputType, GL_VERTEX_SHADER); } }; class EXTClipCullDistanceForFragmentShaderTest : public EXTClipCullDistanceTest { public: void InitializeCompiler() { InitializeCompiler(SH_GLSL_450_CORE_OUTPUT); } void InitializeCompiler(ShShaderOutput shaderOutputType) { EXTClipCullDistanceTest::InitializeCompiler(shaderOutputType, GL_FRAGMENT_SHADER); } }; // Extension flag is required to compile properly. Expect failure when it is // not present. TEST_P(EXTClipCullDistanceForVertexShaderTest, CompileFailsWithoutExtension) { SetExtensionEnable(false); InitializeCompiler(); EXPECT_FALSE(TestShaderCompile(EXTPragma)); } // Extension directive is required to compile properly. Expect failure when // it is not present. TEST_P(EXTClipCullDistanceForVertexShaderTest, CompileFailsWithExtensionWithoutPragma) { SetExtensionEnable(true); InitializeCompiler(); EXPECT_FALSE(TestShaderCompile("")); } #if defined(ANGLE_ENABLE_VULKAN) // With extension flag and extension directive, compiling using TranslatorVulkan succeeds. TEST_P(EXTClipCullDistanceForVertexShaderTest, CompileSucceedsVulkan) { SetExtensionEnable(true); mResources.MaxClipDistances = 8; mResources.MaxCullDistances = 8; mResources.MaxCombinedClipAndCullDistances = 8; InitializeCompiler(SH_GLSL_VULKAN_OUTPUT); EXPECT_TRUE(TestShaderCompile(EXTPragma)); EXPECT_FALSE(TestShaderCompile("")); EXPECT_TRUE(TestShaderCompile(EXTPragma)); } #endif // Extension flag is required to compile properly. Expect failure when it is // not present. TEST_P(EXTClipCullDistanceForFragmentShaderTest, CompileFailsWithoutExtension) { SetExtensionEnable(false); InitializeCompiler(); EXPECT_FALSE(TestShaderCompile(EXTPragma)); } // Extension directive is required to compile properly. Expect failure when // it is not present. TEST_P(EXTClipCullDistanceForFragmentShaderTest, CompileFailsWithExtensionWithoutPragma) { SetExtensionEnable(true); InitializeCompiler(); EXPECT_FALSE(TestShaderCompile("")); } #if defined(ANGLE_ENABLE_VULKAN) // With extension flag and extension directive, compiling using TranslatorVulkan succeeds. TEST_P(EXTClipCullDistanceForFragmentShaderTest, CompileSucceedsVulkan) { SetExtensionEnable(true); mResources.MaxClipDistances = 8; mResources.MaxCullDistances = 8; mResources.MaxCombinedClipAndCullDistances = 8; InitializeCompiler(SH_GLSL_VULKAN_OUTPUT); EXPECT_TRUE(TestShaderCompile(EXTPragma)); EXPECT_FALSE(TestShaderCompile("")); EXPECT_TRUE(TestShaderCompile(EXTPragma)); } #endif class EXTClipCullDistanceForVertexShaderCompileFailureTest : public EXTClipCullDistanceForVertexShaderTest {}; class EXTClipCullDistanceForFragmentShaderCompileFailureTest : public EXTClipCullDistanceForFragmentShaderTest {}; #if defined(ANGLE_ENABLE_VULKAN) TEST_P(EXTClipCullDistanceForVertexShaderCompileFailureTest, CompileFails) { SetExtensionEnable(true); mResources.MaxClipDistances = 8; mResources.MaxCullDistances = 8; mResources.MaxCombinedClipAndCullDistances = 8; InitializeCompiler(SH_GLSL_VULKAN_OUTPUT); EXPECT_FALSE(TestShaderCompile(EXTPragma)); } TEST_P(EXTClipCullDistanceForFragmentShaderCompileFailureTest, CompileFails) { SetExtensionEnable(true); mResources.MaxClipDistances = 8; mResources.MaxCullDistances = 8; mResources.MaxCombinedClipAndCullDistances = 8; InitializeCompiler(SH_GLSL_VULKAN_OUTPUT); EXPECT_FALSE(TestShaderCompile(EXTPragma)); } #endif INSTANTIATE_TEST_SUITE_P(CorrectESSL300Shaders, EXTClipCullDistanceForVertexShaderTest, Combine(Values(SH_GLES3_SPEC), Values(sh::ESSLVersion300), Values(VertexShaderCompileSucceeds1, VertexShaderCompileSucceeds2))); INSTANTIATE_TEST_SUITE_P(CorrectESSL300Shaders, EXTClipCullDistanceForVertexShaderCompileFailureTest, Combine(Values(SH_GLES3_SPEC), Values(sh::ESSLVersion300), Values(VertexShaderCompileFails1, VertexShaderCompileFails2, VertexShaderCompileFails3, VertexShaderCompileFails4))); INSTANTIATE_TEST_SUITE_P(IncorrectESSL300Shaders, EXTClipCullDistanceForFragmentShaderTest, Combine(Values(SH_GLES3_SPEC), Values(sh::ESSLVersion300), Values(FragmentShaderCompileSucceeds1, FragmentShaderCompileSucceeds2))); INSTANTIATE_TEST_SUITE_P(IncorrectESSL300Shaders, EXTClipCullDistanceForFragmentShaderCompileFailureTest, Combine(Values(SH_GLES3_SPEC), Values(sh::ESSLVersion300), Values(FragmentShaderCompileFails1, FragmentShaderCompileFails2, FragmentShaderCompileFails3, FragmentShaderCompileFails4, FragmentShaderCompileFails5))); } // anonymous namespace
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
0c927b320264c5c5e0c35aec61aad151450e1c72
913039393ef26139ac8d3428be991a45daa00977
/moses/src/RuleTable/PhraseDictionaryNodeSCFG.h
a9b70ca6d6136c042bdafdecb3e1c6b99699d957
[]
no_license
braunefe/minSpanMoses
035e8b6f0060e8288f213c07c4cf555f2799389f
acd10ff6225b5bd79c191927d4a1e2bdf216caa4
refs/heads/master
2016-09-07T18:39:42.543976
2012-05-28T16:27:51
2012-05-28T16:27:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,000
h
// vim:tabstop=2 /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #pragma once #include <map> #include <vector> #include <iterator> #include <utility> #include <ostream> #include "Word.h" #include "TargetPhraseCollection.h" #include "Terminal.h" #include <boost/functional/hash.hpp> #include <boost/unordered_map.hpp> #include <boost/version.hpp> namespace Moses { class PhraseDictionarySCFG; //MSPnew : forward reference PhraseDictionaryMinSpan class PhraseDictionaryMinSpan; class NonTerminalMapKeyHasher { public: size_t operator()(const std::pair<Word, Word> & k) const { // Assumes that only the first factor of each Word is relevant. const Word & w1 = k.first; const Word & w2 = k.second; const Factor * f1 = w1[0]; const Factor * f2 = w2[0]; size_t seed = 0; boost::hash_combine(seed, *f1); boost::hash_combine(seed, *f2); return seed; } }; class NonTerminalMapKeyEqualityPred { public: bool operator()(const std::pair<Word, Word> & k1, const std::pair<Word, Word> & k2) const { // Compare first non-terminal of each key. Assumes that for Words // representing non-terminals only the first factor is relevant. { const Word & w1 = k1.first; const Word & w2 = k2.first; const Factor * f1 = w1[0]; const Factor * f2 = w2[0]; if (f1->Compare(*f2)) { return false; } } // Compare second non-terminal of each key. { const Word & w1 = k1.second; const Word & w2 = k2.second; const Factor * f1 = w1[0]; const Factor * f2 = w2[0]; if (f1->Compare(*f2)) { return false; } } return true; } }; /** One node of the PhraseDictionarySCFG structure */ class PhraseDictionaryNodeSCFG { public: typedef std::pair<Word, Word> NonTerminalMapKey; #if defined(BOOST_VERSION) && (BOOST_VERSION >= 104200) typedef boost::unordered_map<Word, PhraseDictionaryNodeSCFG, TerminalHasher, TerminalEqualityPred> TerminalMap; typedef boost::unordered_map<NonTerminalMapKey, PhraseDictionaryNodeSCFG, NonTerminalMapKeyHasher, NonTerminalMapKeyEqualityPred> NonTerminalMap; #else typedef std::map<Word, PhraseDictionaryNodeSCFG> TerminalMap; typedef std::map<NonTerminalMapKey, PhraseDictionaryNodeSCFG> NonTerminalMap; #endif private: friend std::ostream& operator<<(std::ostream&, const PhraseDictionarySCFG&); //MSPnew : make friend with PhraseDictionaryMinSpan friend std::ostream& operator<<(std::ostream&, const PhraseDictionaryMinSpan&); // only these classes are allowed to instantiate this class friend class PhraseDictionarySCFG; //MSPnew : make friend with PhraseDictionaryMinSpan friend class PhraseDictionaryMinSpan; friend class std::map<Word, PhraseDictionaryNodeSCFG>; protected: TerminalMap m_sourceTermMap; NonTerminalMap m_nonTermMap; TargetPhraseCollection *m_targetPhraseCollection; PhraseDictionaryNodeSCFG() :m_targetPhraseCollection(NULL) {} public: virtual ~PhraseDictionaryNodeSCFG(); bool IsLeaf() const { return m_sourceTermMap.empty() && m_nonTermMap.empty(); } void Prune(size_t tableLimit); void Sort(size_t tableLimit); PhraseDictionaryNodeSCFG *GetOrCreateChild(const Word &sourceTerm); PhraseDictionaryNodeSCFG *GetOrCreateChild(const Word &sourceNonTerm, const Word &targetNonTerm); const PhraseDictionaryNodeSCFG *GetChild(const Word &sourceTerm) const; const PhraseDictionaryNodeSCFG *GetChild(const Word &sourceNonTerm, const Word &targetNonTerm) const; const TargetPhraseCollection *GetTargetPhraseCollection() const { return m_targetPhraseCollection; } TargetPhraseCollection &GetOrCreateTargetPhraseCollection() { if (m_targetPhraseCollection == NULL) m_targetPhraseCollection = new TargetPhraseCollection(); return *m_targetPhraseCollection; } const NonTerminalMap & GetNonTerminalMap() const { return m_nonTermMap; } void Clear(); TO_STRING(); }; std::ostream& operator<<(std::ostream&, const PhraseDictionaryNodeSCFG&); }
[ "braune-fabienne@gmail.com" ]
braune-fabienne@gmail.com
0a122c07d304ff60df9706bd719300ef2bab9c65
210c04b58983b307e8177a014d6dc6617da1f7a8
/sec2/ps2/reference_calc.cpp
5c290e4b68a27c384010310b7ff47f16e5ad539a
[]
no_license
cxrasdfg/intro_cuda
4902911bb95e2faecf7fcad15e0d670edcaec488
37c12bdb25c3d23b8154691e6705cdb8e7eb7b8d
refs/heads/master
2020-04-08T21:31:28.454593
2018-12-25T12:19:57
2018-12-25T12:19:57
159,747,546
0
0
null
null
null
null
UTF-8
C++
false
false
2,943
cpp
#include <cmath> #include <cassert> using std::max; using std::min; void channelConvolution(const unsigned char* const channel, unsigned char* const channelBlurred, const size_t numRows, const size_t numCols, const float *filter, const int filterWidth) { //Dealing with an even width filter is trickier assert(filterWidth % 2 == 1); //For every pixel in the image for (int r = 0; r < (int)numRows; ++r) { for (int c = 0; c < (int)numCols; ++c) { float result = 0.f; //For every value in the filter around the pixel (c, r) for (int filter_r = -filterWidth/2; filter_r <= filterWidth/2; ++filter_r) { for (int filter_c = -filterWidth/2; filter_c <= filterWidth/2; ++filter_c) { //Find the global image position for this filter position //clamp to boundary of the image int image_r = min(max(r + filter_r, 0), static_cast<int>(numRows - 1)); int image_c = min(max(c + filter_c, 0), static_cast<int>(numCols - 1)); float image_value = static_cast<float>(channel[image_r * numCols + image_c]); float filter_value = filter[(filter_r + filterWidth/2) * filterWidth + filter_c + filterWidth/2]; result += image_value * filter_value; } } channelBlurred[r * numCols + c] = result; } } } void referenceCalculation(const uchar4* const rgbaImage, uchar4 *const outputImage, size_t numRows, size_t numCols, const float* const filter, const int filterWidth) { unsigned char *red = new unsigned char[numRows * numCols]; unsigned char *blue = new unsigned char[numRows * numCols]; unsigned char *green = new unsigned char[numRows * numCols]; unsigned char *redBlurred = new unsigned char[numRows * numCols]; unsigned char *blueBlurred = new unsigned char[numRows * numCols]; unsigned char *greenBlurred = new unsigned char[numRows * numCols]; //First we separate the incoming RGBA image into three separate channels //for Red, Green and Blue for (size_t i = 0; i < numRows * numCols; ++i) { uchar4 rgba = rgbaImage[i]; red[i] = rgba.x; green[i] = rgba.y; blue[i] = rgba.z; } //Now we can do the convolution for each of the color channels channelConvolution(red, redBlurred, numRows, numCols, filter, filterWidth); channelConvolution(green, greenBlurred, numRows, numCols, filter, filterWidth); channelConvolution(blue, blueBlurred, numRows, numCols, filter, filterWidth); //now recombine into the output image - Alpha is 255 for no transparency for (size_t i = 0; i < numRows * numCols; ++i) { uchar4 rgba = make_uchar4(redBlurred[i], greenBlurred[i], blueBlurred[i], 255); outputImage[i] = rgba; } delete[] red; delete[] green; delete[] blue; delete[] redBlurred; delete[] greenBlurred; delete[] blueBlurred; }
[ "734331254@qq.com" ]
734331254@qq.com
265581deeb3e753ad94349d40ff8e9e56405d4fc
cbaf03b608f2410abfac46354f069436fdf5fa73
/src/devices/board/drivers/nelson/nelson-i2c.cc
a57889efa86f4a056f42d0d3a83e858d762a1dc8
[ "BSD-2-Clause" ]
permissive
carbonatedcaffeine/zircon-rpi
d58f302bcd0bee9394c306133fd3b20156343844
b09b1eb3aa7a127c65568229fe10edd251869283
refs/heads/master
2023-03-01T19:42:04.300854
2021-02-13T02:24:09
2021-02-13T02:24:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,118
cc
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <ddk/debug.h> #include <ddk/device.h> #include <ddk/metadata.h> #include <ddk/metadata/i2c.h> #include <ddk/platform-defs.h> #include <soc/aml-s905d2/s905d2-gpio.h> #include <soc/aml-s905d2/s905d2-hw.h> #include "nelson.h" namespace nelson { static const pbus_mmio_t i2c_mmios[] = { { .base = S905D2_I2C_AO_0_BASE, .length = 0x20, }, { .base = S905D2_I2C2_BASE, .length = 0x20, }, { .base = S905D2_I2C3_BASE, .length = 0x20, }, }; static const uint32_t i2c_clock_delays[] = { 0, // Ignore I2C AO 131, // Set I2C 2 (touch) to 400 kHz 0, // Ignore I2C 3 }; static const pbus_irq_t i2c_irqs[] = { { .irq = S905D2_I2C_AO_0_IRQ, .mode = ZX_INTERRUPT_MODE_EDGE_HIGH, }, { .irq = S905D2_I2C2_IRQ, .mode = ZX_INTERRUPT_MODE_EDGE_HIGH, }, { .irq = S905D2_I2C3_IRQ, .mode = ZX_INTERRUPT_MODE_EDGE_HIGH, }, }; static const i2c_channel_t i2c_channels[] = { // Backlight I2C { .bus_id = NELSON_I2C_3, .address = I2C_BACKLIGHT_ADDR, .vid = 0, .pid = 0, .did = 0, }, // Focaltech touch screen { .bus_id = NELSON_I2C_2, .address = I2C_FOCALTECH_TOUCH_ADDR, .vid = 0, .pid = 0, .did = 0, // binds as composite device }, // Goodix touch screen { .bus_id = NELSON_I2C_2, .address = I2C_GOODIX_TOUCH_ADDR, .vid = 0, .pid = 0, .did = 0, // binds as composite device }, // Light sensor { .bus_id = NELSON_I2C_A0_0, .address = I2C_AMBIENTLIGHT_ADDR, .vid = 0, .pid = 0, .did = 0, // binds as composite device }, // Audio output { .bus_id = NELSON_I2C_3, .address = I2C_AUDIO_CODEC_ADDR, .vid = 0, .pid = 0, .did = 0, // binds as composite device }, // Audio output { .bus_id = NELSON_I2C_3, .address = I2C_AUDIO_CODEC_ADDR_P2, .vid = 0, .pid = 0, .did = 0, // binds as composite device }, // Power sensors { .bus_id = NELSON_I2C_3, .address = I2C_TI_INA231_MLB_ADDR, .vid = 0, .pid = 0, .did = 0, }, { .bus_id = NELSON_I2C_3, .address = I2C_TI_INA231_SPEAKERS_ADDR, .vid = 0, .pid = 0, .did = 0, }, { .bus_id = NELSON_I2C_A0_0, .address = I2C_SHTV3_ADDR, .vid = PDEV_VID_SENSIRION, .pid = 0, .did = PDEV_DID_SENSIRION_SHTV3, }, }; static const pbus_metadata_t i2c_metadata[] = { { .type = DEVICE_METADATA_I2C_CHANNELS, .data_buffer = reinterpret_cast<const uint8_t*>(&i2c_channels), .data_size = sizeof(i2c_channels), }, { .type = DEVICE_METADATA_PRIVATE, .data_buffer = reinterpret_cast<const uint8_t*>(&i2c_clock_delays), .data_size = sizeof(i2c_clock_delays), }, }; static const pbus_dev_t i2c_dev = []() { pbus_dev_t dev = {}; dev.name = "i2c"; dev.vid = PDEV_VID_AMLOGIC; dev.pid = PDEV_PID_GENERIC; dev.did = PDEV_DID_AMLOGIC_I2C; dev.mmio_list = i2c_mmios; dev.mmio_count = countof(i2c_mmios); dev.irq_list = i2c_irqs; dev.irq_count = countof(i2c_irqs); dev.metadata_list = i2c_metadata; dev.metadata_count = countof(i2c_metadata); return dev; }(); zx_status_t Nelson::I2cInit() { // setup pinmux for our I2C busses // i2c_ao_0 gpio_impl_.SetAltFunction(S905D2_GPIOAO(2), 1); gpio_impl_.SetAltFunction(S905D2_GPIOAO(3), 1); // i2c2 gpio_impl_.SetAltFunction(S905D2_GPIOZ(14), 3); gpio_impl_.SetAltFunction(S905D2_GPIOZ(15), 3); // i2c3 gpio_impl_.SetAltFunction(S905D2_GPIOA(14), 2); gpio_impl_.SetAltFunction(S905D2_GPIOA(15), 2); zx_status_t status = pbus_.DeviceAdd(&i2c_dev); if (status != ZX_OK) { zxlogf(ERROR, "%s: DeviceAdd failed: %d", __func__, status); return status; } return ZX_OK; } } // namespace nelson
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
caac769d98ed0cfcbdc5ba2ef2280f6f5a1a86f1
3ed697c4f06c970250ae088f359eea45820b356b
/Transparency/Test/Lighting.cpp
12bebc019637376e61b591eb5ad6405b0c292968
[]
no_license
CG-AccelWorld/Graphics
21aa11dfcf5c5c57b44ed21ea703f7876b4d02fe
4d989a2665cf2bc9209fb27740bc1c42b4d6a127
refs/heads/master
2022-02-01T22:32:11.800319
2019-06-23T09:08:55
2019-06-23T09:08:55
179,039,525
2
0
null
null
null
null
GB18030
C++
false
false
3,005
cpp
#include "StdAfx.h" #include "Lighting.h" #include "math.h" #define PI 3.14159265 #define MIN(a,b) ((a<b)?(a):(b)) #define MAX(a,b) ((a>b)?(a):(b)) CLighting::CLighting(void) { Number = 1; LightSource = new CLightSource[Number]; Ambient = CRGBA(0.3, 0.3, 0.3);//环境光是常数 } CLighting::~CLighting(void) { if (LightSource) { delete []LightSource; LightSource = NULL; } } void CLighting::SetLightNumber(int Number) { if(LightSource) delete []LightSource; this->Number = Number; LightSource = new CLightSource[Number]; } CLighting::CLighting(int Number) { this->Number = Number; LightSource = new CLightSource[Number]; Ambient = CRGBA(0.3, 0.3, 0.3); } CRGBA CLighting::illuminate(CP3 ViewPoint, CP3 Point, CVector3 Normal, CMaterial* pMaterial) { CRGBA ResultI = pMaterial->M_Emit;// 初始化“最终”光强 为自身颜色 for (int loop = 0; loop < Number; loop++)//检查光源开关状态 { if (LightSource[loop].L_OnOff)//光源开 { CRGBA I = CRGBA(0.0, 0.0, 0.0);// I代表“反射”光强 CVector3 L(Point, LightSource[loop].L_Position);// L为光矢量 double d = L.Magnitude();// d为光传播的距离 L = L.Normalize();//规范化光矢量 CVector3 N = Normal; N = N.Normalize();//规范化法矢量 //第1步,加入漫反射光 double NdotL = MAX(DotProduct(L, N), 0); I += LightSource[loop].L_Diffuse * pMaterial->M_Diffuse * NdotL; //第2步,加入镜面反射光 CVector3 V(Point, ViewPoint);//V为视矢量 V = V.Normalize();//规范化视矢量 CVector3 H = (L + V) / (L + V).Magnitude();// H为中值矢量 double NdotH = MAX(DotProduct(N, H), 0); double NdotV = MAX(DotProduct(N, V), 0); double VdotH = MAX(DotProduct(V, H), 0); if(NdotL > 0.0 && NdotV > 0.0) { // fresnel项 double F = pMaterial->M_f + (1.0 - pMaterial->M_f) * pow(1.0 - VdotH, 5.0); //beckmann分布函数 double r1 = 1.0 / (pMaterial->M_k * pMaterial->M_k * pow(NdotH, 4.0)); double r2 = (NdotH * NdotH - 1.0) / (pMaterial->M_k * pMaterial->M_k * NdotH * NdotH); double D = r1 * exp(r2); //几何衰减 double Gm = (2.0 * NdotH * NdotV) / VdotH; double Gs = (2.0 * NdotH * NdotL) / VdotH; double G = MIN(1.0, MIN(Gm, Gs)); double Rs = (F * D * G) / (NdotV * NdotL * PI); I += LightSource[loop].L_Specular * pMaterial->M_Specular * Rs; } //第3步,光强衰减 double c0 = LightSource[loop].L_C0;//c0为常数衰减因子 double c1 = LightSource[loop].L_C1;//c1为线性衰减因子 double c2 = LightSource[loop].L_C2;//c2为二次衰减因子 double f = (1.0/(c0 + c1 * d + c2 * d * d));//光强衰减函数 f = MIN(1.0, f); ResultI += I * f; } else ResultI += Point.c;//物体自身颜色 } //第4步,加入环境光 ResultI += Ambient * pMaterial->M_Ambient; //第5步,光强规范化到[0,1]区间 ResultI.Normalize(); //第6步,返回所计算顶点的最终的光强颜色 return ResultI; }
[ "879112726@qq.com" ]
879112726@qq.com
e10eb2b54af30de1516c385a2a4b7aede94968ae
dd6147bf9433298a64bbceb7fdccaa4cc477fba6
/7304/Davydov_A_A/Lab5/logs.cpp
d0d24fe5f4e62ff6a8c30ee849be0e310b306a4d
[]
no_license
moevm/oop
64a89677879341a3e8e91ba6d719ab598dcabb49
faffa7e14003b13c658ccf8853d6189b51ee30e6
refs/heads/master
2023-03-16T15:48:35.226647
2020-06-08T16:16:31
2020-06-08T16:16:31
85,785,460
42
304
null
2023-03-06T23:46:08
2017-03-22T04:37:01
C++
UTF-8
C++
false
false
525
cpp
#include "logs.h" int SIZE = 1000; Logs::~Logs() {} FileLog::FileLog(QString filename) : filename(filename){} void FileLog::log_data(QString data) { std::ofstream f(filename.toStdString(), std::ios::binary|std::ios::app); f << data.toStdString(); f.close(); } CacheLog::CacheLog(FileLog &file_log) : file_log(file_log) {} void CacheLog::log_data(QString data) { if(cache.length() + data.length() < SIZE) file_log.log_data(cache + data); else cache += data; }
[ "casha_davydov@mail.ru" ]
casha_davydov@mail.ru
0b01b1e6222cac5f15de131b704e26c452d58e19
6197740e6297da2f3d0c8ffd2a1d7ef5d8b3d2cb
/DotNet/VC++2010/Solutions/Ch20/Soln20_01/Soln20_01/stdafx.cpp
b0cf79b4b46b9fa797ab9337a216c8131e489a4d
[]
no_license
ssh352/cppcode
1159d4137b68ada253678718b3d416639d3849ba
5b7c28963286295dfc9af087bed51ac35cd79ce6
refs/heads/master
2020-11-24T18:07:17.587795
2016-07-15T13:13:05
2016-07-15T13:13:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
211
cpp
// stdafx.cpp : source file that includes just the standard includes // Soln20_01.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "qq410029478@ff87cf93-6e24-4a51-a1f1-68835326ac4f" ]
qq410029478@ff87cf93-6e24-4a51-a1f1-68835326ac4f
b02d05a711f5e4f7155e79bab762d4a1bc68b46d
fda134cfb6771f14439d783d7d1f3d30a3a4d584
/Ethereal/Private/Characters/Enemy/Standard/SoulEater.cpp
ca992c6c91ee0698738422699fb6f76ae4c983d0
[ "Apache-2.0" ]
permissive
Soleyu/EtherealLegends
b01562b7bfd48ed025faa2ba43947b5bfb9e3b2a
69c6107dba3b4c3598d72f7cee9f6a68aa71cd34
refs/heads/master
2021-01-23T20:38:44.073943
2017-04-25T22:10:53
2017-04-25T22:10:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,786
cpp
// © 2014 - 2017 Soverance Studios // http://www.soverance.com // 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 "Ethereal.h" #include "SoulEater.h" #define LOCTEXT_NAMESPACE "EtherealText" // Sets default values ASoulEater::ASoulEater(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { static ConstructorHelpers::FObjectFinder<USkeletalMesh> EnemyMesh(TEXT("SkeletalMesh'/Game/EtherealParty/SoulEater/SoulEater.SoulEater'")); static ConstructorHelpers::FObjectFinder<UClass> AnimBP(TEXT("AnimBlueprint'/Game/EtherealParty/SoulEater/Anim_SoulEater.Anim_SoulEater_C'")); static ConstructorHelpers::FObjectFinder<USoundCue> DeathAudioObject(TEXT("SoundCue'/Game/Audio/Party/SoulEater_Death_Cue.SoulEater_Death_Cue'")); S_DeathAudio = DeathAudioObject.Object; // Default Config Name = EEnemyNames::EN_SoulEater; NameText = LOCTEXT("SoulEaterText", "Soul Eater"); Realm = ERealms::R_Shiitake; BattleType = EBattleTypes::BT_Standard; CommonDrop = EMasterGearList::GL_None; UncommonDrop = EMasterGearList::GL_Potion; RareDrop = EMasterGearList::GL_Ether; AttackDelay = 2.0f; BaseEyeHeight = 16; GetCapsuleComponent()->SetRelativeScale3D(FVector(0.2f, 0.2f, 0.2f)); GetCharacterMovement()->MaxAcceleration = 30; GetCharacterMovement()->RotationRate = FRotator(0, 5, 0); // seems to do nothing? // Pawn A.I. config PawnSensing->HearingThreshold = 150; PawnSensing->LOSHearingThreshold = 200; PawnSensing->SightRadius = 250; PawnSensing->SetPeripheralVisionAngle(40.0f); AcceptanceRadius = 25.0f; RunAI = false; // Mesh Config GetMesh()->SkeletalMesh = EnemyMesh.Object; GetMesh()->SetAnimInstanceClass(AnimBP.Object); GetMesh()->SetRelativeScale3D(FVector(2, 2, 2)); GetMesh()->SetRelativeLocation(FVector(0, 0, -90)); GetMesh()->SetRelativeRotation(FRotator(0, -90, 0)); // Melee Radius Config MeleeRadius->SetSphereRadius(100); MeleeRadius->SetRelativeLocation(FVector(15, 0, 0)); // Targeting Reticle config TargetingReticle->SetRelativeLocation(FVector(0, 0, 130)); TargetingReticle->SetRelativeRotation(FRotator(0, 0, 180)); TargetingReticle->SetRelativeScale3D(FVector(0.2f, 0.2f, 0.2f)); // Death FX Config DeathFX->SetRelativeLocation(FVector(0, 0, -90)); DeathFX->SetRelativeScale3D(FVector(0.8f, 0.8f, 0.8f)); HitFX->SetRelativeLocation(FVector(0, 0, 40)); DisappearFX->SetRelativeLocation(FVector(0, 0, -20)); // Enemy-Specific Object Config DeathAudio = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("DeathAudio")); DeathAudio->Sound = S_DeathAudio; DeathAudio->bAutoActivate = false; DeathAudio->SetupAttachment(RootComponent); } // Called when the game starts or when spawned void ASoulEater::BeginPlay() { Super::BeginPlay(); PawnSensing->OnHearNoise.AddDynamic(this, &ASoulEater::OnHearNoise); // bind the OnHearNoise event PawnSensing->OnSeePawn.AddDynamic(this, &ASoulEater::OnSeePawn); // bind the OnSeePawn event OnDeath.AddDynamic(this, &ASoulEater::Death); // bind the death fuction to the OnDeath event OnReachedTarget.AddDynamic(this, &ASoulEater::MeleeAttack); // bind the attack function to the OnReachedTarget event } // Called every frame void ASoulEater::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void ASoulEater::MeleeAttack() { EnemyDealDamage(25); Attack = true; } void ASoulEater::Death() { DeathAudio->Play(); // Play death audio //Target->EtherealPlayerState->EnemyKillReward(Level, CommonDrop, UncommonDrop, RareDrop); // reward the player for killing this enemy } void ASoulEater::OnHearNoise(APawn* PawnInstigator, const FVector& Location, float Volume) { if (!IsDead) { if (!IsAggroed) { Aggro(PawnInstigator); RunToTarget(); } } } void ASoulEater::OnSeePawn(APawn* Pawn) { if (!IsDead) { if (!IsAggroed) { Roar = true; //IsAggroed = true; // Delay Aggro so the skeleton can get up from the ground FTimerDelegate DelegateAggro; DelegateAggro.BindUFunction(this, FName("Aggro"), Pawn); FTimerHandle AggroTimer; GetWorldTimerManager().SetTimer(AggroTimer, DelegateAggro, 2.5f, false); } } } #undef LOCTEXT_NAMESPACE
[ "scott.mccutchen@soverance.com" ]
scott.mccutchen@soverance.com
006143cb9397b0872d45d688022720ac9c38acb5
9bb74614947e4f4e407b88908e45dd6d9b1e69ab
/globalevent.cpp
1dc3157ff4e5ac9bb704748a42c771a9ea050513
[]
no_license
Ayato96/darkkonia
103cbba9babf0a88000ad8e50660569f70900c47
6082b24536691e52708e030d19fe9f9c0b54f8dc
refs/heads/master
2020-04-18T19:30:39.182942
2010-02-13T18:52:24
2010-02-13T18:52:24
167,713,532
0
0
null
null
null
null
UTF-8
C++
false
false
10,399
cpp
//////////////////////////////////////////////////////////////////////// // OpenTibia - an opensource roleplaying game //////////////////////////////////////////////////////////////////////// // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. //////////////////////////////////////////////////////////////////////// #include "otpch.h" #include <libxml/xmlmemory.h> #include <libxml/parser.h> #include "globalevent.h" #include "tools.h" #include "player.h" GlobalEvents::GlobalEvents(): m_interface("GlobalEvent Interface") { m_interface.initState(); } GlobalEvents::~GlobalEvents() { clear(); } void GlobalEvents::clearMap(GlobalEventMap& map) { GlobalEventMap::iterator it; for(it = map.begin(); it != map.end(); ++it) delete it->second; map.clear(); } void GlobalEvents::clear() { clearMap(thinkMap); clearMap(serverMap); clearMap(timerMap); m_interface.reInitState(); } Event* GlobalEvents::getEvent(const std::string& nodeName) { if(asLowerCaseString(nodeName) == "globalevent") return new GlobalEvent(&m_interface); return NULL; } bool GlobalEvents::registerEvent(Event* event, xmlNodePtr p, bool override) { GlobalEvent* globalEvent = dynamic_cast<GlobalEvent*>(event); if(!globalEvent) return false; GlobalEventMap* map = &thinkMap; if(globalEvent->getEventType() == GLOBALEVENT_TIMER) map = &timerMap; else if(globalEvent->getEventType() != GLOBALEVENT_NONE) map = &serverMap; GlobalEventMap::iterator it = map->find(globalEvent->getName()); if(it == map->end()) { map->insert(std::make_pair(globalEvent->getName(), globalEvent)); return true; } if(override) { delete it->second; it->second = globalEvent; return true; } std::clog << "[Warning - GlobalEvents::configureEvent] Duplicate registered globalevent with name: " << globalEvent->getName() << std::endl; return false; } void GlobalEvents::startup() { execute(GLOBALEVENT_STARTUP); Scheduler::getInstance().addEvent(createSchedulerTask(TIMER_INTERVAL, boost::bind(&GlobalEvents::timer, this))); Scheduler::getInstance().addEvent(createSchedulerTask(SCHEDULER_MINTICKS, boost::bind(&GlobalEvents::think, this))); } void GlobalEvents::timer() { time_t now = time(NULL); tm* ts = localtime(&now); for(GlobalEventMap::iterator it = timerMap.begin(); it != timerMap.end(); ++it) { int32_t tmp = it->second->getInterval(), h = tmp >> 16, m = (tmp >> 8) & 0xFF, s = tmp & 0xFF; if(h != ts->tm_hour || m != ts->tm_min || s != ts->tm_sec) continue; if(!it->second->executeEvent()) std::clog << "[Error - GlobalEvents::timer] Couldn't execute event: " << it->second->getName() << std::endl; } Scheduler::getInstance().addEvent(createSchedulerTask(TIMER_INTERVAL, boost::bind(&GlobalEvents::timer, this))); } void GlobalEvents::think() { int64_t now = OTSYS_TIME(); for(GlobalEventMap::iterator it = thinkMap.begin(); it != thinkMap.end(); ++it) { if((it->second->getLastExecution() + it->second->getInterval()) > now) continue; it->second->setLastExecution(now); if(!it->second->executeEvent()) std::clog << "[Error - GlobalEvents::think] Couldn't execute event: " << it->second->getName() << std::endl; } Scheduler::getInstance().addEvent(createSchedulerTask(SCHEDULER_MINTICKS, boost::bind(&GlobalEvents::think, this))); } void GlobalEvents::execute(GlobalEvent_t type) { for(GlobalEventMap::iterator it = serverMap.begin(); it != serverMap.end(); ++it) { if(it->second->getEventType() == type) it->second->executeEvent(); } } GlobalEventMap GlobalEvents::getEventMap(GlobalEvent_t type) { switch(type) { case GLOBALEVENT_NONE: return thinkMap; case GLOBALEVENT_TIMER: return timerMap; case GLOBALEVENT_STARTUP: case GLOBALEVENT_SHUTDOWN: case GLOBALEVENT_GLOBALSAVE: case GLOBALEVENT_RECORD: { GlobalEventMap retMap; for(GlobalEventMap::iterator it = serverMap.begin(); it != serverMap.end(); ++it) { if(it->second->getEventType() == type) retMap[it->first] = it->second; } return retMap; } default: break; } return GlobalEventMap(); } GlobalEvent::GlobalEvent(LuaInterface* _interface): Event(_interface) { m_lastExecution = OTSYS_TIME(); m_interval = 0; } bool GlobalEvent::configureEvent(xmlNodePtr p) { std::string strValue; if(!readXMLString(p, "name", strValue)) { std::clog << "[Error - GlobalEvent::configureEvent] No name for a globalevent." << std::endl; return false; } m_name = strValue; m_eventType = GLOBALEVENT_NONE; if(readXMLString(p, "type", strValue)) { std::string tmpStrValue = asLowerCaseString(strValue); if(tmpStrValue == "startup" || tmpStrValue == "start" || tmpStrValue == "load") m_eventType = GLOBALEVENT_STARTUP; else if(tmpStrValue == "shutdown" || tmpStrValue == "quit" || tmpStrValue == "exit") m_eventType = GLOBALEVENT_SHUTDOWN; else if(tmpStrValue == "globalsave" || tmpStrValue == "global") m_eventType = GLOBALEVENT_GLOBALSAVE; else if(tmpStrValue == "record" || tmpStrValue == "playersrecord") m_eventType = GLOBALEVENT_RECORD; else { std::clog << "[Error - GlobalEvent::configureEvent] No valid type \"" << strValue << "\" for globalevent with name " << m_name << std::endl; return false; } return true; } else if(readXMLString(p, "time", strValue) || readXMLString(p, "at", strValue)) { IntegerVec params = vectorAtoi(explodeString(strValue, ":")); if(params[0] > 23 || params[0] < 0) { std::clog << "[Error - GlobalEvent::configureEvent] No valid hour \"" << strValue << "\" for globalevent with name " << m_name << std::endl; return false; } m_interval |= params[0] << 16; if(params.size() > 1) { if(params[1] > 59 || params[1] < 0) { std::clog << "[Error - GlobalEvent::configureEvent] No valid minute \"" << strValue << "\" for globalevent with name " << m_name << std::endl; return false; } m_interval |= params[1] << 8; if(params.size() > 2) { if(params[2] > 59 || params[2] < 0) { std::clog << "[Error - GlobalEvent::configureEvent] No valid second \"" << strValue << "\" for globalevent with name " << m_name << std::endl; return false; } m_interval |= params[2]; } } m_eventType = GLOBALEVENT_TIMER; return true; } int32_t intValue; if(readXMLInteger(p, "interval", intValue)) { m_interval = std::max((int32_t)SCHEDULER_MINTICKS, intValue); return true; } std::clog << "[Error - GlobalEvent::configureEvent] No interval for globalevent with name " << m_name << std::endl; return false; } std::string GlobalEvent::getScriptEventName() const { switch(m_eventType) { case GLOBALEVENT_STARTUP: return "onStartup"; case GLOBALEVENT_SHUTDOWN: return "onShutdown"; case GLOBALEVENT_GLOBALSAVE: return "onGlobalSave"; case GLOBALEVENT_RECORD: return "onRecord"; case GLOBALEVENT_TIMER: return "onTime"; default: break; } return "onThink"; } std::string GlobalEvent::getScriptEventParams() const { switch(m_eventType) { case GLOBALEVENT_RECORD: return "current, old, cid"; case GLOBALEVENT_NONE: return "interval"; case GLOBALEVENT_TIMER: return "time"; default: break; } return ""; } int32_t GlobalEvent::executeRecord(uint32_t current, uint32_t old, Player* player) { //onRecord(current, old, cid) if(m_interface->reserveEnv()) { ScriptEnviroment* env = m_interface->getEnv(); if(m_scripted == EVENT_SCRIPT_BUFFER) { std::stringstream scriptstream; scriptstream << "local current = " << current << std::endl; scriptstream << "local old = " << old << std::endl; scriptstream << "local cid = " << env->addThing(player) << std::endl; scriptstream << m_scriptData; bool result = true; if(m_interface->loadBuffer(scriptstream.str())) { lua_State* L = m_interface->getState(); result = m_interface->getGlobalBool(L, "_result", true); } m_interface->releaseEnv(); return result; } else { #ifdef __DEBUG_LUASCRIPTS__ char desc[125]; sprintf(desc, "%s - %i to %i (%s)", getName().c_str(), old, current, player->getName().c_str()); env->setEvent(desc); #endif env->setScriptId(m_scriptId, m_interface); lua_State* L = m_interface->getState(); m_interface->pushFunction(m_scriptId); lua_pushnumber(L, current); lua_pushnumber(L, old); lua_pushnumber(L, env->addThing(player)); bool result = m_interface->callFunction(3); m_interface->releaseEnv(); return result; } } else { std::clog << "[Error - GlobalEvent::executeRecord] Call stack overflow." << std::endl; return 0; } } int32_t GlobalEvent::executeEvent() { if(m_interface->reserveEnv()) { ScriptEnviroment* env = m_interface->getEnv(); if(m_scripted == EVENT_SCRIPT_BUFFER) { std::stringstream scriptstream; if(m_eventType == GLOBALEVENT_NONE) scriptstream << "local interval = " << m_interval << std::endl; else if(m_eventType == GLOBALEVENT_TIMER) scriptstream << "local time = " << m_interval << std::endl; scriptstream << m_scriptData; bool result = true; if(m_interface->loadBuffer(scriptstream.str())) { lua_State* L = m_interface->getState(); result = m_interface->getGlobalBool(L, "_result", true); } m_interface->releaseEnv(); return result; } else { env->setScriptId(m_scriptId, m_interface); lua_State* L = m_interface->getState(); m_interface->pushFunction(m_scriptId); int32_t params = 0; if(m_eventType == GLOBALEVENT_NONE || m_eventType == GLOBALEVENT_TIMER) { lua_pushnumber(L, m_interval); params = 1; } bool result = m_interface->callFunction(params); m_interface->releaseEnv(); return result; } } else { std::clog << "[Error - GlobalEvent::executeEvent] Call stack overflow." << std::endl; return 0; } }
[ "MartyX@fa47c1b4-18cb-11df-85bb-b9a83fee2cb1" ]
MartyX@fa47c1b4-18cb-11df-85bb-b9a83fee2cb1
6adf731b5cc40b2647f116686ca823ef0bae336d
ee704c87559f6ed95b02265e04eeadc431a4e3a7
/src/qt/optionsmodel.h
55fe9f879692e62dfae0c1cc6c5ed0ba6eee9f09
[ "MIT" ]
permissive
InternetCafeCoin/ICC-CORE-OLD
02797a94c35bfb26367051b83ab8124e8f09a136
b63046643b40db1abd623a03a8f921ec306b1190
refs/heads/master
2020-06-05T00:54:20.256839
2019-06-17T02:01:59
2019-06-17T02:01:59
192,258,054
0
0
null
null
null
null
UTF-8
C++
false
false
3,229
h
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_OPTIONSMODEL_H #define BITCOIN_QT_OPTIONSMODEL_H #include "amount.h" #include <QAbstractListModel> QT_BEGIN_NAMESPACE class QNetworkProxy; QT_END_NAMESPACE /** Interface from Qt to configuration data structure for Bitcoin client. To Qt, the options are presented as a list with the different options laid out vertically. This can be changed to a tree once the settings become sufficiently complex. */ class OptionsModel : public QAbstractListModel { Q_OBJECT public: explicit OptionsModel(QObject* parent = 0); enum OptionID { StartAtStartup, // bool MinimizeToTray, // bool MapPortUPnP, // bool MinimizeOnClose, // bool ProxyUse, // bool ProxyIP, // QString ProxyPort, // int DisplayUnit, // BitcoinUnits::Unit ThirdPartyTxUrls, // QString Digits, // QString Theme, // QString Language, // QString CoinControlFeatures, // bool ThreadsScriptVerif, // int DatabaseCache, // int SpendZeroConfChange, // bool DarksendRounds, // int AnonymizeICCAmount, //int ShowMasternodesTab, // bool Listen, // bool OptionIDRowCount, }; void Init(); void Reset(); int rowCount(const QModelIndex& parent = QModelIndex()) const; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); /** Updates current unit in memory, settings and emits displayUnitChanged(newUnit) signal */ void setDisplayUnit(const QVariant& value); /* Explicit getters */ bool getMinimizeToTray() { return fMinimizeToTray; } bool getMinimizeOnClose() { return fMinimizeOnClose; } int getDisplayUnit() { return nDisplayUnit; } QString getThirdPartyTxUrls() { return strThirdPartyTxUrls; } bool getProxySettings(QNetworkProxy& proxy) const; bool getCoinControlFeatures() { return fCoinControlFeatures; } const QString& getOverriddenByCommandLine() { return strOverriddenByCommandLine; } /* Restart flag helper */ void setRestartRequired(bool fRequired); bool isRestartRequired(); bool resetSettings; private: /* Qt-only settings */ bool fMinimizeToTray; bool fMinimizeOnClose; QString language; int nDisplayUnit; QString strThirdPartyTxUrls; bool fCoinControlFeatures; /* settings that were overriden by command-line */ QString strOverriddenByCommandLine; /// Add option to list of GUI options overridden through command line/config file void addOverriddenOption(const std::string& option); signals: void displayUnitChanged(int unit); void DarksendRoundsChanged(int); void anonymizeICCAmountChanged(int); void coinControlFeaturesChanged(bool); }; #endif // BITCOIN_QT_OPTIONSMODEL_H
[ "iccforworld@gmail.com" ]
iccforworld@gmail.com
6cedd75fada95d17ac5dc50ac88504a13a8a724a
daacd479a7ad189b8476c4a57b815f4719c0c0d3
/src/ProgramObject.cc
030ea66b8cce845d3eaf2d3e4a82e575b71eaa59
[ "MIT" ]
permissive
krux02/sdl2-cpp-project-template
d41468d31a608c139bb7b51689215aa3a893ea79
ae3f31480cd0f154a388e029b5f0c2e580be33ba
refs/heads/master
2016-09-06T19:49:26.070647
2015-05-09T00:23:43
2015-05-09T00:23:43
24,334,186
1
0
null
null
null
null
UTF-8
C++
false
false
1,957
cc
#include "ProgramObject.hh" #include <iostream> using std::cerr; using std::endl; void ProgramObject::Quit() { state = ProgramState::Quit; } bool ProgramObject::ProcessEvent(const SDL_Event &event) { switch (event.type) { case SDL_QUIT: Quit(); return true; case SDL_KEYDOWN: if (event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) { Quit(); return true; } else { return false; } case SDL_MOUSEBUTTONDOWN: PlaySound(); default: return false; } } void ProgramObject::MainLoop() { StartMusic(); while (state != ProgramState::Quit) { SDL_Event event; while (SDL_PollEvent(&event)) { ProcessEvent(event); } // clear screen SDL_SetRenderDrawColor(renderer.get(), 0, 0, 0, 255); SDL_RenderClear(renderer.get()); Update(); Render(); // make things visible SDL_RenderPresent(renderer.get()); } } void ProgramObject::Update() { // insert code here } void ProgramObject::Render() const { // insert code here SDL_Renderer* r = renderer.get(); SDL_SetRenderDrawColor(r, 255,255,255,255); SDL_RenderDrawLine(r, 100,100,200,200); SDL_RenderDrawLine(r, 200,200,150,250); SDL_RenderDrawLine(r, 150,250,100,200); SDL_RenderDrawLine(r, 100,200,200,100); SDL_RenderDrawLine(r, 200,100,200,200); SDL_RenderDrawLine(r, 200,200,100,200); SDL_RenderDrawLine(r, 100,200,100,100); SDL_RenderDrawLine(r, 100,100,200,100); text_renderer.RenderBaked(sample_text_object, glm::ivec2(100,250)); text_renderer.RenderDirect("direct Hello World!", glm::ivec2(100,282)); } void ProgramObject::PlaySound() { Mix_PlayChannel(0,sample_chunk.get(),0); } void ProgramObject::StartMusic() { // -1 for infinite loop Mix_PlayMusic(sample_music.get(), -1); Mix_VolumeMusic(MIX_MAX_VOLUME); }
[ "arne.doering@gmx.net" ]
arne.doering@gmx.net
1c18ddff997539dd9976589686879592af83d605
54ffb3747c9b4adf3d5de434835554ee71eca1d0
/Computer_Room_Reservation_system/Computer_Room_Reservation_system/identity.h
80a1083307deaf9a9bd74f7c4d53b2b1eced3ca4
[]
no_license
LAND-CRUISERSYH/Cpp
b4dee08f9a2702468e0f2aa51820918c0f14b86e
a8dd0db59552814897d6a2bf79538877c730fea7
refs/heads/master
2023-01-22T14:08:08.907158
2020-12-02T10:45:30
2020-12-02T10:45:30
288,696,926
1
0
null
null
null
null
GB18030
C++
false
false
266
h
#pragma once //防止头文件重复包含 #include<iostream> using namespace std; //身份抽象基类 class Identity { public: virtual void Menu() = 0; //操作菜单 纯虚函数 string m_Name; //用户名 string m_pwd; //密码 };
[ "1354843647@qq.com" ]
1354843647@qq.com
4e05f863b15d988d4675cb3081a81185958e0393
802a8f80cefc39644979cf2038356f63de866398
/Server Lib/Projeto IOCP/PANGYA_DB/cmd_rate_config_info.hpp
d23d25543bc25a3bbd3b38386c4b2865f323d3ab
[ "MIT" ]
permissive
Acrisio-Filho/SuperSS-Dev
3a3b78e15e0ec8edc9aae0ca1a632eb02be5d19c
9b1bdd4a2536ec13de50b11e6feb63e5c351559b
refs/heads/master
2023-08-03T13:00:07.280725
2023-07-05T00:24:18
2023-07-05T00:24:18
418,925,124
32
30
MIT
2022-11-03T23:15:37
2021-10-19T12:58:05
C++
UTF-8
C++
false
false
1,304
hpp
// Aquivo cmd_rate_config_info.hpp // Criado em 09/05/2019 as 18:39 por Acrisio // Definição da classe CmdRateConfigInfo #pragma once #ifndef _STDA_CMD_RATE_CONFIG_INFO_HPP #define _STDA_CMD_RATE_CONFIG_INFO_HPP #include "../../Projeto IOCP/PANGYA_DB/pangya_db.h" #include "../../Projeto IOCP/TYPE/pangya_st.h" namespace stdA { class CmdRateConfigInfo : public pangya_db { public: CmdRateConfigInfo(bool _waiter = false); explicit CmdRateConfigInfo(uint32_t _server_uid, bool _waiter = false); virtual ~CmdRateConfigInfo(); uint32_t getServerUID(); void setServerUID(uint32_t _server_uid); RateConfigInfo& getInfo(); bool isError(); protected: void lineResult(result_set::ctx_res* _result, uint32_t _index_result) override; response* prepareConsulta(database& _db) override; // get Class Name virtual std::string _getName() override { return "CmdRateConfigInfo"; }; virtual std::wstring _wgetName() override { return L"CmdRateConfigInfo"; }; private: RateConfigInfo m_rate_info; uint32_t m_server_uid; bool m_error; const char* m_szConsulta = "pangya.ProcGetRateConfigInfo"; }; } #endif // !_STDA_CMD_RATE_CONFIG_INFO_HPP
[ "acrisio_299@hotmail.com" ]
acrisio_299@hotmail.com
66e377b2727822ad956d7dc9de221b6deb96ab6c
2f424a53777376da2280308402c78f9e00878552
/src/qt/bitcoinunits.cpp
7539e7cad7d7d5b7ffe02e9d452b0ff646cf788f
[ "MIT" ]
permissive
mammix2/boostcoin-legacy
6514d77e012097e92a2ad98d4f6c57d67fabd2e1
7b1b63f6941306c23b8784fa964ead72b4050146
refs/heads/master
2020-03-28T03:20:13.403062
2014-05-31T15:46:13
2014-05-31T15:46:13
147,638,131
1
0
null
null
null
null
UTF-8
C++
false
false
4,288
cpp
#include "bitcoinunits.h" #include <QStringList> BitcoinUnits::BitcoinUnits(QObject *parent): QAbstractListModel(parent), unitlist(availableUnits()) { } QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits() { QList<BitcoinUnits::Unit> unitlist; unitlist.append(BTC); unitlist.append(mBTC); unitlist.append(uBTC); return unitlist; } bool BitcoinUnits::valid(int unit) { switch(unit) { case BTC: case mBTC: case uBTC: return true; default: return false; } } QString BitcoinUnits::name(int unit) { switch(unit) { case BTC: return QString("BOST"); case mBTC: return QString("mSUM"); case uBTC: return QString::fromUtf8("μSUM"); default: return QString("???"); } } QString BitcoinUnits::description(int unit) { switch(unit) { case BTC: return QString("BoostCoins"); case mBTC: return QString("Milli-BoostCoins (1 / 1,000)"); case uBTC: return QString("Micro-BoostCoins (1 / 1,000,000)"); default: return QString("???"); } } qint64 BitcoinUnits::factor(int unit) { switch(unit) { case BTC: return 100000000; case mBTC: return 100000; case uBTC: return 100; default: return 100000000; } } int BitcoinUnits::amountDigits(int unit) { switch(unit) { case BTC: return 8; // 21,000,000 (# digits, without commas) case mBTC: return 11; // 21,000,000,000 case uBTC: return 14; // 21,000,000,000,000 default: return 0; } } int BitcoinUnits::decimals(int unit) { switch(unit) { case BTC: return 8; case mBTC: return 5; case uBTC: return 2; default: return 0; } } QString BitcoinUnits::format(int unit, qint64 n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if(!valid(unit)) return QString(); // Refuse to format invalid unit qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Right-trim excess zeros after the decimal point int nTrim = 0; for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i) ++nTrim; remainder_str.chop(nTrim); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); return quotient_str + QString(".") + remainder_str; } QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign) { return format(unit, amount, plussign) + QString(" ") + name(unit); } bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out) { if(!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); QStringList parts = value.split("."); if(parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if(parts.size() > 1) { decimals = parts[1]; } if(decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if(str.size() > 18) { return false; // Longer numbers will exceed 63 bits } qint64 retvalue = str.toLongLong(&ok); if(val_out) { *val_out = retvalue; } return ok; } int BitcoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant BitcoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if(row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch(role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); }
[ "matt@ffptechnologies.co.uk" ]
matt@ffptechnologies.co.uk
7b1faa39348cfcb8732c7e83366758db75ec006c
767a49334113d375f96049f99e940123b4a712fd
/DevSkill_CP/Intermediate/Batch 5/Class 25/Ugly.cpp
ca5bae18a9feb11480039687a7c6815bde0934b9
[]
no_license
Sadman007/DevSkill-Programming-Course---Basic---Public-CodeBank
9f4effbbea048f4a6919b699bc0fb1b9a0d5fef7
d831620c44f826c3c89ca18ff95fb81ea2a2cc40
refs/heads/master
2023-09-01T03:44:37.609267
2023-08-18T19:45:41
2023-08-18T19:45:41
173,104,184
83
64
null
null
null
null
UTF-8
C++
false
false
546
cpp
#include <bits/stdc++.h> using namespace std; #define MAX 1000000000000000000LL #define ll long long #define MOD 1000000007 #define sc(n) scanf("%d",&n) #define pr(n) printf("%d\n",n) #define NL puts("") vector<ll>ugly; unordered_map<ll,int>dp; void gen(ll N) { if(N > MAX) return; if(dp.find(N)!=dp.end()) return; /// if(dp[N] == 1) return; dp[N] = 1; ugly.push_back(N); gen(2*N); gen(3*N); gen(5*N); } int main() { gen(1); sort(ugly.begin(),ugly.end()); cout << ugly[1499] << endl; return 0; }
[ "sakib.csedu21@gmail.com" ]
sakib.csedu21@gmail.com
9c8b9a80da51d43cc8d62fbb128df4b25982363b
ad3bc509c4f61424492b2949e03c60628f631a31
/examples/c/eof/05_generic_api_eof_rule.re
6ca7da8dc7b6d3798ec9fe47f9d23af760139437
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
sergeyklay/re2c
0b1cdbfe40b4514be33320b2e1d263cf5d6426d6
88ff1e5a2ad57d424fe999e17960c564886d36f4
refs/heads/master
2021-12-23T22:24:30.716697
2021-06-26T22:56:00
2021-06-27T15:23:28
299,206,360
0
0
NOASSERTION
2021-06-19T10:49:05
2020-09-28T06:10:35
C
UTF-8
C++
false
false
1,274
re
// re2c $INPUT -o $OUTPUT #include <assert.h> #include <stdlib.h> #include <string.h> // expect a string without terminating null static int lex(const char *str, unsigned int len) { const char *cur = str, *lim = str + len, *mar; int count = 0; loop: /*!re2c re2c:yyfill:enable = 0; re2c:eof = 0; re2c:flags:input = custom; re2c:api:style = free-form; re2c:define:YYCTYPE = char; re2c:define:YYLESSTHAN = "cur >= lim"; re2c:define:YYPEEK = "cur < lim ? *cur : 0"; // fake null re2c:define:YYSKIP = "++cur;"; re2c:define:YYBACKUP = "mar = cur;"; re2c:define:YYRESTORE = "cur = mar;"; * { return -1; } $ { return count; } ['] ([^'\\] | [\\][^])* ['] { ++count; goto loop; } [ ]+ { goto loop; } */ } // make a copy of the string without terminating null static void test(const char *str, unsigned int len, int res) { char *s = (char*) malloc(len); memcpy(s, str, len); int r = lex(s, len); free(s); assert(r == res); } #define TEST(s, r) test(s, sizeof(s) - 1, r) int main() { TEST("", 0); TEST("'qu\0tes' 'are' 'fine: \\'' ", 3); TEST("'unterminated\\'", -1); return 0; }
[ "skvadrik@gmail.com" ]
skvadrik@gmail.com
f21911d5d74b022788bdd5b1daa6812da18507e5
6d763845a081a6c5c372a304c3bae1ccd949e6fa
/day05/ex00/Bureaucrat.hpp
17ccc6ea9d1ba3aa8527b9158de8429d400a6fc8
[]
no_license
hmiso/CPP_modules
cc5539764b10d9005aea0ccdf894c0fd2562a649
e0608a810ef6bbb7cb29461721f6248e0c3b88eb
refs/heads/master
2023-02-28T09:12:49.284788
2021-02-06T14:40:33
2021-02-06T14:40:33
322,648,779
0
0
null
null
null
null
UTF-8
C++
false
false
1,568
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Bureaucrat.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hmiso <hmiso@student.21-school.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/12 10:02:13 by hmiso #+# #+# */ /* Updated: 2021/01/16 11:22:09 by hmiso ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef BUREAUCRAT_HPP #define BUREAUCRAT_HPP #include "iostream" class Bureaucrat{ private: std::string name; int grade; Bureaucrat(); public: Bureaucrat(std::string name, int grade); Bureaucrat(Bureaucrat const &ptr); Bureaucrat &operator = (const Bureaucrat &ptr); std::string getName () const; int getGrade() const; void upGrade(); void lowGrade(); class GradeTooHighException : public std::exception{ public: const char* what() const throw(); }; class GradeTooLowException : public std::exception{ public: const char* what() const throw(); }; ~Bureaucrat(){} }; std::ostream &operator << (std::ostream &stream, Bureaucrat const &ptr); #endif
[ "mia@itgrn.ru" ]
mia@itgrn.ru
817408bc8a5ee51c80af6432b69b8c7fc818593e
a8b15b84c8d71260d834cf8276b3e76e083c6b66
/DrClientLib(不检http头)/DrClientSrc/DrCOMSocket.cpp
aa81df571deab46fdf4e37b7bfa93db5b2639037
[]
no_license
KingsleyYau/MobileClient
c6ed3801e66dabd75a6164064c54cadae5ad1787
be755e254e4d834396f8b0fb8bc1bddb64156f63
refs/heads/master
2021-01-23T14:48:14.053326
2014-01-17T15:46:55
2014-01-17T15:46:55
null
0
0
null
null
null
null
GB18030
C++
false
false
18,420
cpp
/* * File : DrCOMSocket.cpp * Date : 2011-07-11 * Author : Keqin Su * Copyright : City Hotspot Co., Ltd. * Description : DrCOM socket */ #include "DrClientInclude.h" #if (!defined(_WIN32) && !defined(_WIN32_WCE) && !defined(_WIN32_WP8))//ISNOTWINDOWSENVIROMENT #include <unistd.h> #include <resolv.h> #include <netdb.h> #include <fcntl.h> #include <sys/ioctl.h> #include <net/if.h> #include <arpa/inet.h> #ifdef _IOS #include "IPAddress.h" #endif /* _IOS */ #endif #include "DrCOMSocket.h" #if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN32_WP8) || defined(_IOS) #if !defined(_IOS) #define ioctl ioctlsocket #endif #define tv_set tv_sec #define tv_uset tv_usec #define socklen_t int //#define usleep Sleep #endif #if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN32_WP8) int gettimeofday(struct timeval *tp, void *tzp) { time_t clock; struct tm tm; SYSTEMTIME wtm; GetLocalTime(&wtm); tm.tm_year = wtm.wYear - 1900; tm.tm_mon = wtm.wMonth - 1; tm.tm_mday = wtm.wDay; tm.tm_hour = wtm.wHour; tm.tm_min = wtm.wMinute; tm.tm_sec = wtm.wSecond; tm. tm_isdst = -1; clock = mktime(&tm); tp->tv_sec = clock; tp->tv_usec = wtm.wMilliseconds * 1000; return (0); } #endif // ---------- global function ------------ inline unsigned int GetTick() { timeval tNow; gettimeofday(&tNow, NULL); if (tNow.tv_usec != 0){ return (tNow.tv_sec * 1000 + (unsigned int)(tNow.tv_usec / 1000)); }else{ return (tNow.tv_sec * 1000); } } inline bool isTimeout(unsigned int uiStart, unsigned int uiTimeout) { unsigned int uiCurr = GetTick(); unsigned int uiDiff; if (uiTimeout == 0) return false; if (uiCurr >= uiStart) { uiDiff = uiCurr - uiStart; }else{ uiDiff = (0xFFFFFFFF - uiStart) + uiCurr; } if(uiDiff >= uiTimeout){ return true; } return false; } // -------------------------------------- tcpSocket::tcpSocket() { m_iSocket = -1; m_strAddress = ""; m_uiPort = 0; } tcpSocket::~tcpSocket() { Close(); } int tcpSocket::Connect(string strAddress, unsigned int uiPort) { return BaseConnect(strAddress, uiPort, false); } int tcpSocket::SendData(char* pBuffer, unsigned int uiSendLen, unsigned int uiTimeout) { unsigned int uiBegin = GetTick(); int iOrgLen = uiSendLen; int iRet = -1, iRetS = -1; int iSendedLen = 0; fd_set wset; while (true) { struct timeval tout; tout.tv_sec = uiTimeout / 1000; tout.tv_usec = (uiTimeout % 1000) * 1000; FD_ZERO(&wset); FD_SET(m_iSocket, &wset); iRetS = select(m_iSocket + 1, NULL, &wset, NULL, &tout); if (iRetS == -1) { return -1; } else if (iRetS == 0) { return iSendedLen; } iRet = send(m_iSocket, pBuffer, uiSendLen, 0); if (iRet == -1 || (iRetS == 1 && iRet == 0)) { if (iSendedLen == 0){ return -1; } return iSendedLen; } else if (iRet == 0) { return iSendedLen; } pBuffer += iRet; iSendedLen += iRet; uiSendLen -= iRet; if (iSendedLen >= iOrgLen) { return iSendedLen; } if (isTimeout(uiBegin, uiTimeout)) { return iSendedLen; } } return 0; } int tcpSocket::RecvData(char* pBuffer, unsigned int uiRecvLen, bool bRecvAll, unsigned int uiTimeout) { unsigned int uiBegin = GetTick(); int iOrgLen = uiRecvLen; int iRet = -1, iRetS = -1; int iRecvedLen = 0; fd_set rset; while (true) { timeval tout; tout.tv_sec = uiTimeout / 1000; tout.tv_usec = (uiTimeout % 1000) * 1000; FD_ZERO(&rset); FD_SET(m_iSocket, &rset); iRetS = select(m_iSocket + 1, &rset, NULL, NULL, &tout); if (iRetS == -1) { return -1; } else if (iRetS == 0) { return iRecvedLen; } iRet = recv(m_iSocket, pBuffer, uiRecvLen, 0); if (iRet==-1 || (iRetS == 1 && iRet == 0)) { if (iRecvedLen == 0){ return -1; } return iRecvedLen; } else if (iRet == 0) { return iRecvedLen; } pBuffer += iRet; iRecvedLen += iRet; uiRecvLen -= iRet; if (iRecvedLen >= iOrgLen) { return iRecvedLen; } if (!bRecvAll) { return iRecvedLen; } if (isTimeout(uiBegin, uiTimeout)){ return iRecvedLen; } } return 0; } int tcpSocket::Close() { if (m_iSocket != -1) { shutdown(m_iSocket, SHUT_RDWR); close(m_iSocket); m_iSocket = -1; } return 1; } // 比较本地IP是否存在输入IP bool tcpSocket::CompareLocalAddress(string strAddress) { bool bRet = false; #if (!defined(_WIN32) && !defined(_WIN32_WCE) && !defined(_WIN32_WP8)) int fd = 0, intrface = 0; struct ifconf ifc; string strTmp = ""; struct ifreq buf[DrCOM_MAX_INFERFACE]; if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) { ifc.ifc_len = sizeof(buf); ifc.ifc_buf = (caddr_t)buf; if (!ioctl(fd, SIOCGIFCONF, (char*)&ifc)) { intrface = ifc.ifc_len / sizeof (struct ifreq); while (intrface-- > 0){ if (!(ioctl(fd, SIOCGIFADDR, (char *) &buf[intrface]))) { strTmp = inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr); if (strTmp == strAddress) { bRet = true; break; } } } } } close(fd); #else char szHostName[256]; struct hostent * pHost; unsigned int i; if( gethostname(szHostName, sizeof(szHostName)) == 0 ) { pHost = gethostbyname(szHostName); for( i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ ) { string localIP = inet_ntoa((*(struct in_addr *)pHost->h_addr_list[i])); if (strAddress.compare(localIP) == 0) { bRet = true; break; } } } #endif return bRet; } string tcpSocket::GetFirstMacAddress() { string strRet = ""; #if !defined(_WIN32) && !defined(_WIN32_WCE) && !defined(_WIN32_WP8) && !defined(_IOS) int fd = 0, intrface = 0; struct ifconf ifc; struct ifreq buf[DrCOM_MAX_INFERFACE]; char cBuffer[DrCOM_BUFFER_256B] = {'\0'}; if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) { ifc.ifc_len = sizeof(buf); ifc.ifc_buf = (caddr_t)buf; if (!ioctl(fd, SIOCGIFCONF, (char*)&ifc)) { intrface = ifc.ifc_len / sizeof (struct ifreq); while (intrface-- > 0){ if (!(ioctl(fd, SIOCGIFHWADDR, (char *) &buf[intrface]))) { sprintf(cBuffer, "%02x:%02x:%02x:%02x:%02x:%02x", buf[intrface].ifr_hwaddr.sa_data[0], buf[intrface].ifr_hwaddr.sa_data[1], buf[intrface].ifr_hwaddr.sa_data[2], buf[intrface].ifr_hwaddr.sa_data[3], buf[intrface].ifr_hwaddr.sa_data[4], buf[intrface].ifr_hwaddr.sa_data[5]); if (strcmp(cBuffer, "00:00:00:00:00:00")) { strRet = cBuffer; } if (strRet.length() > 0) { break; } } } } } close(fd); #else #endif return strRet; } string tcpSocket::GetFirstIpAddress() { string strRet = ""; #if !defined(_WIN32) && !defined(_WIN32_WCE) && !defined(_WIN32_WP8) int fd = 0, intrface = 0; struct ifconf ifc; struct ifreq buf[DrCOM_MAX_INFERFACE]; if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) { ifc.ifc_len = sizeof(buf); ifc.ifc_buf = (caddr_t)buf; if (!ioctl(fd, SIOCGIFCONF, (char*)&ifc)) { intrface = ifc.ifc_len / sizeof (struct ifreq); while (intrface-- > 0){ if (!(ioctl(fd, SIOCGIFADDR, (char *) &buf[intrface]))) { strRet = inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr); if ((strRet.length() > 0) && (strRet != "127.0.0.1")) { break; } } } } } close(fd); #else char szHostName[256]; struct hostent * pHost; unsigned int i; if( gethostname(szHostName, sizeof(szHostName)) == 0 ) { pHost = gethostbyname(szHostName); for( i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ ) { strRet = inet_ntoa((*(struct in_addr *)pHost->h_addr_list[i])); if ((strRet.length() > 0) && (strRet != "127.0.0.1")) { break; } } } #endif return strRet; } string tcpSocket::GetMacAddressList() { string strRet = ""; #if !defined(_WIN32) && !defined(_WIN32_WCE) && !defined(_WIN32_WP8) && !defined(_IOS) int fd = 0, intrface = 0, iCount = 1; struct ifconf ifc; struct ifreq buf[DrCOM_MAX_INFERFACE]; char cBuffer[DrCOM_BUFFER_256B] = {'\0'}; char cBufferTmp[DrCOM_BUFFER_256B] = {'\0'}; if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) { ifc.ifc_len = sizeof(buf); ifc.ifc_buf = (caddr_t)buf; if (!ioctl(fd, SIOCGIFCONF, (char*)&ifc)) { intrface = ifc.ifc_len / sizeof (struct ifreq); while (intrface-- > 0){ if (!(ioctl(fd, SIOCGIFHWADDR, (char *) &buf[intrface]))) { sprintf(cBuffer, "%02X:%02X:%02X:%02X:%02X:%02X", buf[intrface].ifr_hwaddr.sa_data[0], buf[intrface].ifr_hwaddr.sa_data[1], buf[intrface].ifr_hwaddr.sa_data[2], buf[intrface].ifr_hwaddr.sa_data[3], buf[intrface].ifr_hwaddr.sa_data[4], buf[intrface].ifr_hwaddr.sa_data[5]); if (strcmp(cBuffer, "00:00:00:00:00:00")) { sprintf(cBufferTmp, "&m%d=%s", iCount++, cBuffer); strRet += cBufferTmp; } } } } } close(fd); #elif defined (_IOS) InitAddresses(); int count = GetIPAddresses(); GetHWAddresses(); char cBufferTmp[DrCOM_BUFFER_256B] = {'\0'}; int iCount = 1; for (int i = 0; i < count; i++) { string name = if_names[i]; string mac = hw_addrs[i]; if ((name.length() > 0) && 0!=name.compare("lo") && 0!=mac.compare("00:00:00:00:00:00")) { memset(cBufferTmp, '\0', DrCOM_BUFFER_256B); sprintf(cBufferTmp, "&m%d=%s", iCount++, hw_addrs[i]); strRet += cBufferTmp; } } FreeAddresses(); #endif if (strRet.length() > 1) { strRet = strRet.substr(1, strRet.length()); } return strRet; } inline int tcpSocket::BaseConnect(string strAddress, unsigned int uiPort, bool bBlock) { m_strAddress = strAddress; m_uiPort = uiPort; int iRet = -1, iFlag = 1; struct sockaddr_in dest; hostent* hent = NULL; #if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN32_WP8) if (INVALID_SOCKET != (m_iSocket = socket(AF_INET, SOCK_STREAM, 0))) #else if ((m_iSocket = socket(AF_INET, SOCK_STREAM, 0)) >= 0) #endif { memset(&dest, 0, sizeof(dest)); dest.sin_family = AF_INET; dest.sin_port = htons(uiPort); dest.sin_addr.s_addr = inet_addr((const char*)strAddress.c_str()); if (dest.sin_addr.s_addr == -1L) { if ((hent = gethostbyname((const char*)strAddress.c_str())) != NULL) { dest.sin_family = hent->h_addrtype; memcpy((char*)&dest.sin_addr, hent->h_addr, hent->h_length); } else { goto EXIT_ERROR_TCP; } } #if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN32_WP8) setsockopt(m_iSocket, IPPROTO_TCP, TCP_NODELAY, (const char *)&iFlag, sizeof(iFlag)); #endif iFlag = 1500; setsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (const char *)&iFlag, sizeof(iFlag)); iFlag = 1; setsockopt(m_iSocket, SOL_SOCKET, SO_REUSEADDR, (const char *)&iFlag, sizeof(iFlag)); unsigned long ul = 1; ioctl(m_iSocket, FIONBIO, &ul); //设置为非阻塞模式 #if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN32_WP8) if (connect(m_iSocket, (struct sockaddr *)&dest, sizeof(dest)) != SOCKET_ERROR || WSAGetLastError() == WSAEWOULDBLOCK) { #else if (connect(m_iSocket, (struct sockaddr *)&dest, sizeof(dest)) != -1 || errno == EINPROGRESS) { #endif timeval tm; fd_set set; int error = 0; int len = sizeof(error); tm.tv_sec = 3; tm.tv_usec = 0; FD_ZERO(&set); FD_SET(m_iSocket, &set); if( select(m_iSocket+1, NULL, &set, NULL, &tm) > 0) { #if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN32_WP8) getsockopt(m_iSocket, SOL_SOCKET, SO_ERROR, (char*)&error, (socklen_t*)&len); #endif iRet = (error == 0 ? 1 : -1); } if (iRet == 1) { ul = 0; ioctl(m_iSocket, FIONBIO, &ul); //设置为阻塞模式 } } } EXIT_ERROR_TCP: if (iRet != 1) { Close(); } return iRet; } /*****************************************************************/ udpSocket::udpSocket() { m_iSocket = -1; m_strAddress = ""; m_uiPort = 0; } udpSocket::~udpSocket() { Close(); } int udpSocket::Connect(string strAddress, unsigned int uiPort) { m_strAddress = strAddress; m_uiPort = uiPort; int iRet = -1, iFlag = 1; struct sockaddr_in dest; hostent* hent = NULL; #if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN32_WP8) if (INVALID_SOCKET != (m_iSocket = socket(AF_INET, SOCK_DGRAM, 0))) #else if ((m_iSocket = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) #endif { memset(&dest, 0, sizeof(dest)); dest.sin_family = AF_INET; dest.sin_port = htons(uiPort); dest.sin_addr.s_addr = inet_addr((const char*)strAddress.c_str()); if (dest.sin_addr.s_addr == -1L) { if ((hent = gethostbyname((const char*)strAddress.c_str())) != NULL) { dest.sin_family = hent->h_addrtype; memcpy((char*)&dest.sin_addr, hent->h_addr, hent->h_length); } else { goto EXIT_ERROR_UDP; } } #if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN32_WP8) if (connect(m_iSocket, (struct sockaddr *)&dest, sizeof(dest)) != SOCKET_ERROR ) #else if (connect(m_iSocket, (struct sockaddr *)&dest, sizeof(dest)) != -1) #endif { iRet = 1; } } EXIT_ERROR_UDP: if (iRet != 1) { Close(); } return iRet; } int udpSocket::SendData(const char* pBuffer, unsigned int uiSendLen, unsigned int uiTimeout) { int iRet = -1; const char* pBufferSend = pBuffer; unsigned int uiBufferSendLen = uiSendLen; const unsigned int uiSendStep = 1000; int iFailCount = 0; // 设置超时 struct timeval timeout; timeout.tv_sec = uiTimeout/1000; timeout.tv_usec = uiTimeout % 1000; if (setsockopt(m_iSocket,SOL_SOCKET,SO_SNDTIMEO,(char *)&timeout.tv_sec,sizeof(struct timeval)) >= 0) { iRet = 1; while (uiBufferSendLen > 0) { unsigned int uiToSend = uiBufferSendLen > uiSendStep ? uiSendStep : uiBufferSendLen; unsigned int uiSent = send(m_iSocket, pBufferSend, uiToSend, 0); if (uiSent > 0) { pBufferSend += uiSent; uiBufferSendLen -= uiSent; } else if (uiSent == 0 && iFailCount < 5) { iFailCount++; } else { iRet = -1; break; } } } return iRet; } int udpSocket::RecvData(const char* pBuffer, unsigned int uiRecvLen, unsigned int uiTimeout) { unsigned int uiBegin = GetTick(); int iRet = -1; int iRecvedLen = 0; // 设置超时 struct timeval timeout; timeout.tv_sec = uiTimeout/1000; timeout.tv_usec = uiTimeout % 1000; if (setsockopt(m_iSocket,SOL_SOCKET,SO_RCVTIMEO,(char *)&timeout.tv_sec,sizeof(struct timeval)) >= 0) { while (true) { iRet = recv(m_iSocket, (char*)pBuffer, uiRecvLen, 0); if (iRet==-1 || iRet == 0) { return iRecvedLen == 0 ? -1 : iRecvedLen; } else if (iRet == 0) { return iRecvedLen; } else { pBuffer += iRet; iRecvedLen += iRet; uiRecvLen -= iRet; return iRecvedLen; } } } return 0; } int udpSocket::Close() { if (m_iSocket != -1) { shutdown(m_iSocket, SHUT_RDWR); close(m_iSocket); m_iSocket = -1; } return 1; } /*****************************************************************/ #define GetResult(result) ((result >= 0) ? 1 : -1) #define IsSuccess(result) (result == 1) sslSocket::sslSocket() { memset(&m_ssl, 0, sizeof(m_ssl)); memset(&m_cacert, 0, sizeof(m_cacert)); memset(&m_socket, 0, sizeof(m_socket)); } sslSocket::~sslSocket() { Close(); } int sslSocket::Connect(string strAddress, unsigned int uiPort) { int iRet = -1, iFlag = -1; iRet = GetResult( InitializeEntropy() ); if ( IsSuccess(iRet) ) { iRet = GetResult( StartConnect(strAddress.c_str(), uiPort) ); } if ( IsSuccess(iRet) ) { iRet = GetResult( InitializeSSL() ); } if ( IsSuccess(iRet) ) { iRet = GetResult( SSLHandshake() ); } if ( IsSuccess(iRet) ) { iRet = GetResult( VerifySrvCert() ); } return iRet; } int sslSocket::SendData(char* pBuffer, unsigned int uiSendLen, unsigned int uiTimeout) { int ret = ssl_write(&m_ssl, (const unsigned char*)pBuffer, uiSendLen); return ret > 0 ? ret : -1; } int sslSocket::RecvData(char* pBuffer, unsigned int uiRecvLen, bool bRecvAll, unsigned int uiTimeout) { int ret = ssl_read(&m_ssl, (unsigned char*)pBuffer, uiRecvLen); return ret > 0 ? ret : -1; } int sslSocket::Close() { ReleaseResource(); return 1; } #pragma region ssl函数 // Initialize the RNG and the session data int sslSocket::InitializeEntropy() { char *pers = "ssl_client1"; memset(&m_ssl, 0, sizeof(ssl_context) ); memset(&m_cacert, 0, sizeof(x509_cert) ); entropy_init(&m_entropy); return ctr_drbg_init(&m_ctr_drbg, entropy_func, &m_entropy,(unsigned char*)pers, strlen(pers)); } // Initialize certificates int sslSocket::InitializeCertificates() { int ret; #if defined(POLARSSL_CERTS_C) ret = x509parse_crt(&m_cacert, (unsigned char*)test_ca_crt, strlen(test_ca_crt) ); #else ret = 1; #endif return ret; } // Start the connection int sslSocket::StartConnect(const char *host, int port) { return net_connect(&m_socket, host, port); } int sslSocket::InitializeSSL() { int ret = ssl_init(&m_ssl); if( ret == 0 ) { ssl_set_endpoint(&m_ssl, SSL_IS_CLIENT); ssl_set_authmode(&m_ssl, SSL_VERIFY_NONE); ssl_set_ca_chain(&m_ssl, &m_cacert, NULL, "PolarSSL"); ssl_set_bio(&m_ssl, net_recv, &m_socket, net_send, &m_socket); // Set Debug ssl_set_rng(&m_ssl, ctr_drbg_random, &m_ctr_drbg); } return ret; } // Handshake int sslSocket::SSLHandshake() { int ret; while( ( ret = ssl_handshake( &m_ssl ) ) != 0 ) { if( ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE ) { break; } } return ret; } int sslSocket::VerifySrvCert() { return ssl_get_verify_result(&m_ssl); } //释放资源 void sslSocket::ReleaseResource() { x509_free(&m_cacert); memset(&m_cacert, 0, sizeof(m_cacert)); net_close(m_socket); memset(&m_socket, 0, sizeof(m_socket)); ssl_free(&m_ssl); memset(&m_ssl, 0, sizeof(m_ssl)); } #pragma endregion
[ "Kingsleyyau@gmail.com" ]
Kingsleyyau@gmail.com
c001db2e8874bc260e346d621896ee7f1b1300fd
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/rtorrent/gumtree/rtorrent_old_hunk_38.cpp
ac4b18ec6ef9552dbaf872cc38c39a33898c99ca
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
508
cpp
if (torrent::get_read_throttle() == 0) pos = snprintf(buf + pos, 128 - pos, "off"); else pos = snprintf(buf + pos, 128 - pos, "%-3i", torrent::get_read_throttle() / 1024); m_canvas->print(0, 0, "Throttle U/D: %s Listen: %s:%i%s Handshakes: %i", buf, !torrent::get_ip().empty() ? torrent::get_ip().c_str() : "<default>", (int)torrent::get_listen_port(), !torrent::get_bind().empty() ? (" Bind: " + torrent::get_bind()).c_str() : "", torrent::get_total_handshakes()); }
[ "993273596@qq.com" ]
993273596@qq.com
f3ecb141cb3503de0ad5a41cf28551a794ac7558
90c9dc885340e28c421f129396a593b9b60e0ce1
/src/GAME/zFMV.cpp
a45b92484e104eead75ad878c6de351d694bf1f6
[]
no_license
Gota7/incredibles
3b493718fb1a1145371811966a2024b5c8fec39f
14dd4a94edbe84c30482a8e873b5c8e9f48d1535
refs/heads/main
2023-06-16T12:38:46.252815
2021-07-10T07:59:53
2021-07-10T07:59:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,314
cpp
#include "zFMV.h" #include "zGlobals.h" #include "zMenu.h" #include "../Core/x/xSubTitles.h" #include "../Core/x/xSndMgr.h" #include "../Core/p2/iFMV.h" #include "../Core/x/xPad.h" // clang-format off static zFMVFile zFMVFileTable[] = { eFMVFile_NoMovie, "", 0, eFMVFile_PixarLOGO, "FMV\\Pixar", 0, eFMVFile_DisneyLOGO, "FMV\\Disney", 0, eFMVFile_NickLOGO, "FMV\\Nicklogo", 0, eFMVFile_THQLOGO, "FMV\\THQLogo", 0, eFMVFile_HeavyIronLOGO, "FMV\\HILogo", 0, eFMVFile_AttractMode, "FMV\\Attract", 0, eFMVFile_FMVOM01, "FMV\\FMVOM01", 0xC6472871, eFMVFile_FMVOM03, "FMV\\FMVOM03", 0x6DF46B37, eFMVFile_FMVOM03a, "FMV\\FMVOM03a", 0x288395FA, eFMVFile_FMVLD01, "FMV\\FMVLD01", 0x6F4C6D4B, eFMVFile_FMVLD01a, "FMV\\FMVLD01a", 0xD88CA636, eFMVFile_FMVNJO2, "FMV\\FMVNJ02", 0x7D1F8B72, eFMVFile_FMVNJ03, "FMV\\FMVNJ03", 0x50F62CD5, eFMVFile_FMVNI01, "FMV\\FMVNI01", 0x0A805494, eFMVFile_FMVNI01a, "FMV\\FMVNI01a", 0x441C0091, eFMVFile_FMVCI03, "FMV\\FMVCI03", 0xEB1C2DFF, eFMVFile_FMVCI01a, "FMV\\FMVCI01a", 0x66331700, eFMVFile_FMVFT01, "FMV\\FMVFT01", 0xD7FAD155, eFMVFile_FMVFT01a, "FMV\\FMVFT01a", 0x69C9D754, eFMVFile_FMVFT02, "FMV\\FMVFT02", 0xABD172B8, eFMVFile_FMVFT02a, "FMV\\FMVFT02a", 0xD09E6CFD, eFMVFile_FMVFT03a, "FMV\\FMVFT03a", 0x377302A6, eFMVFile_FMVFT04, "FMV\\FMVFT04", 0x537EB57E, eFMVFile_FMVFT04a, "FMV\\FMVFT04a", 0x9E47984F, eFMVFile_FMVRS01, "FMV\\FMVRS01", 0x40E82326, eFMVFile_FMVRS01a, "FMV\\FMVRS01a", 0x1B3AB547, eFMVFile_FMVRS02a, "FMV\\FMVRS02a", 0x820F4AF0, eFMVFile_FMVHS01a, "FMV\\FMVHS01a", 0x517E3E09, eFMVFile_FMVHS01b, "FMV\\FMVHS01b", 0x2554DF6C, eFMVFile_FMVNI01b, "FMV\\FMVNI01b", 0x17F2A1F4, eFMVFile_FMVNI03a, "FMV\\FMVNI03a", 0x11C52BE3, eFMVFile_FMVHS01, "FMV\\FMVHS01", 0xBA7B37BC, eFMVFile_FMVNJ01b, "FMV\\FMVNJ01b", 0x58971FE5, eFMVFile_FMVNJ01, "FMV\\FMVNJ01", 0xA948EA0F, eFMVFile_D3, "FMV\\D3", 0, eFMVFile_PROMO1, "FMV\\PROMO1", 0xF5B911C5, eFMVFile_PROMO2, "FMV\\PROMO2", 0xC98FB328 }; // clang-format on zFMVFile* zFMVFileGetFile(eFMVFile fmvId) { for (int32 i = 0; i < sizeof(zFMVFileTable) / sizeof(zFMVFile); i++) { if (fmvId == zFMVFileTable[i].fmvCode) { return &zFMVFileTable[i]; } } return NULL; } const char* zFMVFileGetName(eFMVFile fmvId) { zFMVFile* file = zFMVFileGetFile(fmvId); if (file == NULL) // If I do (!file) here the branches get flipped... { return NULL; } return file->fileName; } uint32 zFMVPlay(const char* name, uint32 buttons, float32 time, uint32 uSubtitlesAID, bool skippable, bool lockController, bool r8) { uint32 retval = 0; if (!globals.noMovies) { zMenuPause(true); float32 oldSubtitlesSize = xSubTitlesGetSize(); xSubTitlesSetSize(0.18f); xSndEffect oldSndEffect = xSndMgrGetEffect(); xSndMgrSetEffect(xSndEffect_NONE); retval = iFMVPlay(name, buttons, time, uSubtitlesAID, skippable, lockController, r8); xSndMgrSetEffect(oldSndEffect); xSubTitlesSetSize(oldSubtitlesSize); xPadUpdate(0, 0.0001f); xPadUpdate(0, 0.0001f); zMenuPause(false); } return retval; }
[ "32021834+seilweiss@users.noreply.github.com" ]
32021834+seilweiss@users.noreply.github.com
2fb62a8b92cd347c875d1d8da056cf2ff31befb9
bc60aa0d1f865d712dfac1893c84f08e71957387
/src/main.h
ced81a085cdb7827782008e4ecd3de164897db5d
[ "MIT" ]
permissive
x314network/x314-source
83e86bda7ccf458fc1e2b468e77431ac835a8952
c1fc4c2d8b4fdca68e66217bc0e688143c0770f5
refs/heads/master
2021-08-30T22:53:00.226220
2017-12-19T18:23:29
2017-12-19T18:23:29
114,797,730
1
0
null
null
null
null
UTF-8
C++
false
false
45,213
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_MAIN_H #define BITCOIN_MAIN_H #include "bignum.h" #include "sync.h" #include "net.h" #include "script.h" #include "scrypt.h" #include "zerocoin/Zerocoin.h" #include <list> class CWallet; class CBlock; class CBlockIndex; class CKeyItem; class CReserveKey; class COutPoint; class CAddress; class CInv; class CRequestTracker; class CNode; class CTxMemPool; static const int LAST_POW_BLOCK = 1000; /** The maximum allowed size for a serialized block, in bytes (network rule) */ static const unsigned int MAX_BLOCK_SIZE = 1000000; /** The maximum size for mined blocks */ static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2; /** The maximum size for transactions we're willing to relay/mine **/ static const unsigned int MAX_STANDARD_TX_SIZE = MAX_BLOCK_SIZE_GEN/5; /** The maximum allowed number of signature check operations in a block (network rule) */ static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; /** The maximum number of orphan transactions kept in memory */ static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100; /** The maximum number of entries in an 'inv' protocol message */ static const unsigned int MAX_INV_SZ = 50000; /** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */ static const int64_t MIN_TX_FEE = 10000; /** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */ static const int64_t MIN_RELAY_TX_FEE = MIN_TX_FEE; /** No amount larger than this (in satoshi) is valid */ static const int64_t MAX_MONEY = 1400000 * COIN; inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */ static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC static const int64_t COIN_YEAR_REWARD = 10 * CENT; static const uint256 hashGenesisBlock("0x0000017e8f2f2b99cfd207545616f7ef96d11f040adab370c612c0edbbc4123f"); static const uint256 hashGenesisBlockTestNet("0x0000017e8f2f2b99cfd207545616f7ef96d11f040adab370c612c0edbbc4123f"); inline int64_t PastDrift(int64_t nTime) { return nTime - 10 * 60; } // up to 10 minutes from the past inline int64_t FutureDrift(int64_t nTime) { return nTime + 10 * 60; } // up to 10 minutes from the future extern libzerocoin::Params* ZCParams; extern CScript COINBASE_FLAGS; extern CCriticalSection cs_main; extern std::map<uint256, CBlockIndex*> mapBlockIndex; extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen; extern CBlockIndex* pindexGenesisBlock; extern unsigned int nTargetSpacing; extern unsigned int nStakeMinAge; extern unsigned int nStakeMaxAge; extern unsigned int nNodeLifespan; extern int nCoinbaseMaturity; extern int nBestHeight; extern uint256 nBestChainTrust; extern uint256 nBestInvalidTrust; extern uint256 hashBestChain; extern CBlockIndex* pindexBest; extern unsigned int nTransactionsUpdated; extern uint64_t nLastBlockTx; extern uint64_t nLastBlockSize; extern int64_t nLastCoinStakeSearchInterval; extern const std::string strMessageMagic; extern int64_t nTimeBestReceived; extern CCriticalSection cs_setpwalletRegistered; extern std::set<CWallet*> setpwalletRegistered; extern unsigned char pchMessageStart[4]; extern std::map<uint256, CBlock*> mapOrphanBlocks; // Settings extern int64_t nTransactionFee; extern int64_t nReserveBalance; extern int64_t nMinimumInputValue; extern bool fUseFastIndex; extern unsigned int nDerivationMethodIndex; extern bool fEnforceCanonical; // Minimum disk space required - used in CheckDiskSpace() static const uint64_t nMinDiskSpace = 52428800; class CReserveKey; class CTxDB; class CTxIndex; void RegisterWallet(CWallet* pwalletIn); void UnregisterWallet(CWallet* pwalletIn); void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true); bool ProcessBlock(CNode* pfrom, CBlock* pblock); bool CheckDiskSpace(uint64_t nAdditionalBytes=0); FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb"); FILE* AppendBlockFile(unsigned int& nFileRet); bool LoadBlockIndex(bool fAllowNew=true); void PrintBlockTree(); CBlockIndex* FindBlockByHeight(int nHeight); bool ProcessMessages(CNode* pfrom); bool SendMessages(CNode* pto, bool fSendTrickle); bool LoadExternalBlockFile(FILE* fileIn); bool CheckProofOfWork(uint256 hash, unsigned int nBits); unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake); int64_t GetProofOfWorkReward(int64_t nFees); int64_t GetProofOfStakeReward(int64_t nCoinAge, int64_t nFees); unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime); unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime); int GetNumBlocksOfPeers(); bool IsInitialBlockDownload(); std::string GetWarnings(std::string strFor); bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock); uint256 WantedByOrphan(const CBlock* pblockOrphan); const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake); void StakeMiner(CWallet *pwallet); void ResendWalletTransactions(bool fForce = false); /** (try to) add transaction to memory pool **/ bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx, bool* pfMissingInputs); bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut); /** Position on disk for a particular transaction. */ class CDiskTxPos { public: unsigned int nFile; unsigned int nBlockPos; unsigned int nTxPos; CDiskTxPos() { SetNull(); } CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn) { nFile = nFileIn; nBlockPos = nBlockPosIn; nTxPos = nTxPosIn; } IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; } bool IsNull() const { return (nFile == (unsigned int) -1); } friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b) { return (a.nFile == b.nFile && a.nBlockPos == b.nBlockPos && a.nTxPos == b.nTxPos); } friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b) { return !(a == b); } std::string ToString() const { if (IsNull()) return "null"; else return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos); } void print() const { printf("%s", ToString().c_str()); } }; /** An inpoint - a combination of a transaction and an index n into its vin */ class CInPoint { public: CTransaction* ptx; unsigned int n; CInPoint() { SetNull(); } CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; } void SetNull() { ptx = NULL; n = (unsigned int) -1; } bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); } }; /** An outpoint - a combination of a transaction hash and an index n into its vout */ class COutPoint { public: uint256 hash; unsigned int n; COutPoint() { SetNull(); } COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; } IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { hash = 0; n = (unsigned int) -1; } bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); } friend bool operator<(const COutPoint& a, const COutPoint& b) { return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n)); } friend bool operator==(const COutPoint& a, const COutPoint& b) { return (a.hash == b.hash && a.n == b.n); } friend bool operator!=(const COutPoint& a, const COutPoint& b) { return !(a == b); } std::string ToString() const { return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n); } void print() const { printf("%s\n", ToString().c_str()); } }; /** An input of a transaction. It contains the location of the previous * transaction's output that it claims and a signature that matches the * output's public key. */ class CTxIn { public: COutPoint prevout; CScript scriptSig; unsigned int nSequence; CTxIn() { nSequence = std::numeric_limits<unsigned int>::max(); } explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max()) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max()) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } IMPLEMENT_SERIALIZE ( READWRITE(prevout); READWRITE(scriptSig); READWRITE(nSequence); ) bool IsFinal() const { return (nSequence == std::numeric_limits<unsigned int>::max()); } friend bool operator==(const CTxIn& a, const CTxIn& b) { return (a.prevout == b.prevout && a.scriptSig == b.scriptSig && a.nSequence == b.nSequence); } friend bool operator!=(const CTxIn& a, const CTxIn& b) { return !(a == b); } std::string ToStringShort() const { return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n); } std::string ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig).c_str()); else str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str()); if (nSequence != std::numeric_limits<unsigned int>::max()) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } void print() const { printf("%s\n", ToString().c_str()); } }; /** An output of a transaction. It contains the public key that the next input * must be able to sign with to claim it. */ class CTxOut { public: int64_t nValue; CScript scriptPubKey; CTxOut() { SetNull(); } CTxOut(int64_t nValueIn, CScript scriptPubKeyIn) { nValue = nValueIn; scriptPubKey = scriptPubKeyIn; } IMPLEMENT_SERIALIZE ( READWRITE(nValue); READWRITE(scriptPubKey); ) void SetNull() { nValue = -1; scriptPubKey.clear(); } bool IsNull() { return (nValue == -1); } void SetEmpty() { nValue = 0; scriptPubKey.clear(); } bool IsEmpty() const { return (nValue == 0 && scriptPubKey.empty()); } uint256 GetHash() const { return SerializeHash(*this); } friend bool operator==(const CTxOut& a, const CTxOut& b) { return (a.nValue == b.nValue && a.scriptPubKey == b.scriptPubKey); } friend bool operator!=(const CTxOut& a, const CTxOut& b) { return !(a == b); } std::string ToStringShort() const { return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str()); } std::string ToString() const { if (IsEmpty()) return "CTxOut(empty)"; return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str()); } void print() const { printf("%s\n", ToString().c_str()); } }; enum GetMinFee_mode { GMF_BLOCK, GMF_RELAY, GMF_SEND, }; typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx; /** The basic transaction that is broadcasted on the network and contained in * blocks. A transaction can contain multiple inputs and outputs. */ class CTransaction { public: static const int CURRENT_VERSION=1; int nVersion; unsigned int nTime; std::vector<CTxIn> vin; std::vector<CTxOut> vout; unsigned int nLockTime; // Denial-of-service detection: mutable int nDoS; bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; } CTransaction() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(nTime); READWRITE(vin); READWRITE(vout); READWRITE(nLockTime); ) void SetNull() { nVersion = CTransaction::CURRENT_VERSION; nTime = GetAdjustedTime(); vin.clear(); vout.clear(); nLockTime = 0; nDoS = 0; // Denial-of-service prevention } bool IsNull() const { return (vin.empty() && vout.empty()); } uint256 GetHash() const { return SerializeHash(*this); } bool IsNewerThan(const CTransaction& old) const { if (vin.size() != old.vin.size()) return false; for (unsigned int i = 0; i < vin.size(); i++) if (vin[i].prevout != old.vin[i].prevout) return false; bool fNewer = false; unsigned int nLowest = std::numeric_limits<unsigned int>::max(); for (unsigned int i = 0; i < vin.size(); i++) { if (vin[i].nSequence != old.vin[i].nSequence) { if (vin[i].nSequence <= nLowest) { fNewer = false; nLowest = vin[i].nSequence; } if (old.vin[i].nSequence < nLowest) { fNewer = true; nLowest = old.vin[i].nSequence; } } } return fNewer; } bool IsCoinBase() const { return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1); } bool IsCoinStake() const { // ppcoin: the coin stake transaction is marked with the first output empty return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty()); } /** Check for standard transaction types @param[in] mapInputs Map of previous transactions that have outputs we're spending @return True if all inputs (scriptSigs) use only standard transaction forms @see CTransaction::FetchInputs */ bool AreInputsStandard(const MapPrevTx& mapInputs) const; /** Count ECDSA signature operations the old-fashioned (pre-0.6) way @return number of sigops this transaction's outputs will produce when spent @see CTransaction::FetchInputs */ unsigned int GetLegacySigOpCount() const; /** Count ECDSA signature operations in pay-to-script-hash inputs. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return maximum number of sigops required to validate this transaction's inputs @see CTransaction::FetchInputs */ unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const; /** Amount of bitcoins spent by this transaction. @return sum of all outputs (note: does not include fees) */ int64_t GetValueOut() const { int64_t nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); } return nValueOut; } /** Amount of bitcoins coming in to this transaction Note that lightweight clients may not know anything besides the hash of previous transactions, so may not be able to calculate this. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return Sum of value of all inputs (scriptSigs) @see CTransaction::FetchInputs */ int64_t GetValueIn(const MapPrevTx& mapInputs) const; int64_t GetMinFee(unsigned int nBlockSize=1, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const; bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL) { CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION); if (!filein) return error("CTransaction::ReadFromDisk() : OpenBlockFile failed"); // Read transaction if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return error("CTransaction::ReadFromDisk() : fseek failed"); try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Return file pointer if (pfileRet) { if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return error("CTransaction::ReadFromDisk() : second fseek failed"); *pfileRet = filein.release(); } return true; } friend bool operator==(const CTransaction& a, const CTransaction& b) { return (a.nVersion == b.nVersion && a.nTime == b.nTime && a.vin == b.vin && a.vout == b.vout && a.nLockTime == b.nLockTime); } friend bool operator!=(const CTransaction& a, const CTransaction& b) { return !(a == b); } std::string ToStringShort() const { std::string str; str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user")); return str; } std::string ToString() const { std::string str; str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction"); str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n", GetHash().ToString().substr(0,10).c_str(), nTime, nVersion, vin.size(), vout.size(), nLockTime); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; } void print() const { printf("%s", ToString().c_str()); } bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet); bool ReadFromDisk(CTxDB& txdb, COutPoint prevout); bool ReadFromDisk(COutPoint prevout); bool DisconnectInputs(CTxDB& txdb); /** Fetch from memory and/or disk. inputsRet keys are transaction hashes. @param[in] txdb Transaction database @param[in] mapTestPool List of pending changes to the transaction index database @param[in] fBlock True if being called to add a new best-block to the chain @param[in] fMiner True if being called by CreateNewBlock @param[out] inputsRet Pointers to this transaction's inputs @param[out] fInvalid returns true if transaction is invalid @return Returns true if all inputs are in txdb or mapTestPool */ bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid); /** Sanity check previous transactions, then, if all checks succeed, mark them as spent by this transaction. @param[in] inputs Previous transactions (from FetchInputs) @param[out] mapTestPool Keeps track of inputs that need to be updated on disk @param[in] posThisTx Position of this transaction on disk @param[in] pindexBlock @param[in] fBlock true if called from ConnectBlock @param[in] fMiner true if called from CreateNewBlock @return Returns true if all checks succeed */ bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner); bool CheckTransaction() const; bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const; // ppcoin: get transaction coin age protected: const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const; }; /** Check for standard transaction types @return True if all outputs (scriptPubKeys) use only standard transaction forms */ bool IsStandardTx(const CTransaction& tx); bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0); /** A transaction with a merkle branch linking it to the block chain. */ class CMerkleTx : public CTransaction { private: int GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const; public: uint256 hashBlock; std::vector<uint256> vMerkleBranch; int nIndex; // memory only mutable bool fMerkleVerified; CMerkleTx() { Init(); } CMerkleTx(const CTransaction& txIn) : CTransaction(txIn) { Init(); } void Init() { hashBlock = 0; nIndex = -1; fMerkleVerified = false; } IMPLEMENT_SERIALIZE ( nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action); nVersion = this->nVersion; READWRITE(hashBlock); READWRITE(vMerkleBranch); READWRITE(nIndex); ) int SetMerkleBranch(const CBlock* pblock=NULL); // Return depth of transaction in blockchain: // -1 : not in blockchain, and not in memory pool (conflicted transaction) // 0 : in memory pool, waiting to be included in a block // >=1 : this many blocks deep in the main chain int GetDepthInMainChain(CBlockIndex* &pindexRet) const; int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); } bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; } int GetBlocksToMaturity() const; bool AcceptToMemoryPool(); }; /** A txdb record that contains the disk location of a transaction and the * locations of transactions that spend its outputs. vSpent is really only * used as a flag, but having the location is very helpful for debugging. */ class CTxIndex { public: CDiskTxPos pos; std::vector<CDiskTxPos> vSpent; CTxIndex() { SetNull(); } CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs) { pos = posIn; vSpent.resize(nOutputs); } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(pos); READWRITE(vSpent); ) void SetNull() { pos.SetNull(); vSpent.clear(); } bool IsNull() { return pos.IsNull(); } friend bool operator==(const CTxIndex& a, const CTxIndex& b) { return (a.pos == b.pos && a.vSpent == b.vSpent); } friend bool operator!=(const CTxIndex& a, const CTxIndex& b) { return !(a == b); } int GetDepthInMainChain() const; }; /** Nodes collect new transactions into a block, hash them into a hash tree, * and scan through nonce values to make the block's hash satisfy proof-of-work * requirements. When they solve the proof-of-work, they broadcast the block * to everyone and the block is added to the block chain. The first transaction * in the block is a special one that creates a new coin owned by the creator * of the block. * * Blocks are appended to blk0001.dat files on disk. Their location on disk * is indexed by CBlockIndex objects in memory. */ class CBlock { public: // header static const int CURRENT_VERSION=6; int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; // network and disk std::vector<CTransaction> vtx; // ppcoin: block signature - signed by one of the coin base txout[N]'s owner std::vector<unsigned char> vchBlockSig; // memory only mutable std::vector<uint256> vMerkleTree; // Denial-of-service detection: mutable int nDoS; bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; } CBlock() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(hashPrevBlock); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); // ConnectBlock depends on vtx following header to generate CDiskTxPos if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY))) { READWRITE(vtx); READWRITE(vchBlockSig); } else if (fRead) { const_cast<CBlock*>(this)->vtx.clear(); const_cast<CBlock*>(this)->vchBlockSig.clear(); } ) void SetNull() { nVersion = CBlock::CURRENT_VERSION; hashPrevBlock = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; vtx.clear(); vchBlockSig.clear(); vMerkleTree.clear(); nDoS = 0; } bool IsNull() const { return (nBits == 0); } uint256 GetHash() const { return GetPoWHash(); } uint256 GetPoWHash() const { return scrypt_blockhash(CVOIDBEGIN(nVersion)); } int64_t GetBlockTime() const { return (int64_t)nTime; } void UpdateTime(const CBlockIndex* pindexPrev); // entropy bit for stake modifier if chosen by modifier unsigned int GetStakeEntropyBit() const { // Take last bit of block hash as entropy bit unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu); if (fDebug && GetBoolArg("-printstakemodifier")) printf("GetStakeEntropyBit: hashBlock=%s nEntropyBit=%u\n", GetHash().ToString().c_str(), nEntropyBit); return nEntropyBit; } // ppcoin: two types of block: proof-of-work or proof-of-stake bool IsProofOfStake() const { return (vtx.size() > 1 && vtx[1].IsCoinStake()); } bool IsProofOfWork() const { return !IsProofOfStake(); } std::pair<COutPoint, unsigned int> GetProofOfStake() const { return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0); } // ppcoin: get max transaction timestamp int64_t GetMaxTransactionTime() const { int64_t maxTransactionTime = 0; BOOST_FOREACH(const CTransaction& tx, vtx) maxTransactionTime = std::max(maxTransactionTime, (int64_t)tx.nTime); return maxTransactionTime; } uint256 BuildMerkleTree() const { vMerkleTree.clear(); BOOST_FOREACH(const CTransaction& tx, vtx) vMerkleTree.push_back(tx.GetHash()); int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { for (int i = 0; i < nSize; i += 2) { int i2 = std::min(i+1, nSize-1); vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); } j += nSize; } return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); } std::vector<uint256> GetMerkleBranch(int nIndex) const { if (vMerkleTree.empty()) BuildMerkleTree(); std::vector<uint256> vMerkleBranch; int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { int i = std::min(nIndex^1, nSize-1); vMerkleBranch.push_back(vMerkleTree[j+i]); nIndex >>= 1; j += nSize; } return vMerkleBranch; } static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return 0; BOOST_FOREACH(const uint256& otherside, vMerkleBranch) { if (nIndex & 1) hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); else hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside)); nIndex >>= 1; } return hash; } bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet) { // Open history file to append CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION); if (!fileout) return error("CBlock::WriteToDisk() : AppendBlockFile failed"); // Write index header unsigned int nSize = fileout.GetSerializeSize(*this); fileout << FLATDATA(pchMessageStart) << nSize; // Write block long fileOutPos = ftell(fileout); if (fileOutPos < 0) return error("CBlock::WriteToDisk() : ftell failed"); nBlockPosRet = fileOutPos; fileout << *this; // Flush stdio buffers and commit to disk before returning fflush(fileout); if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0) FileCommit(fileout); return true; } bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true) { SetNull(); // Open history file to read CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION); if (!filein) return error("CBlock::ReadFromDisk() : OpenBlockFile failed"); if (!fReadTransactions) filein.nType |= SER_BLOCKHEADERONLY; // Read block try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Check the header if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetPoWHash(), nBits)) return error("CBlock::ReadFromDisk() : errors in block header"); return true; } void print() const { printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n", GetHash().ToString().c_str(), nVersion, hashPrevBlock.ToString().c_str(), hashMerkleRoot.ToString().c_str(), nTime, nBits, nNonce, vtx.size(), HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str()); for (unsigned int i = 0; i < vtx.size(); i++) { printf(" "); vtx[i].print(); } printf(" vMerkleTree: "); for (unsigned int i = 0; i < vMerkleTree.size(); i++) printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str()); printf("\n"); } bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex); bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false); bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true); bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew); bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos, const uint256& hashProof); bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const; bool AcceptBlock(); bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block bool SignBlock(CWallet& keystore, int64_t nFees); bool CheckBlockSignature() const; private: bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew); }; /** The block chain is a tree shaped structure starting with the * genesis block at the root, with each block potentially having multiple * candidates to be the next block. pprev and pnext link a path through the * main/longest chain. A blockindex may have multiple pprev pointing back * to it, but pnext will only point forward to the longest branch, or will * be null if the block is not part of the longest chain. */ class CBlockIndex { public: const uint256* phashBlock; CBlockIndex* pprev; CBlockIndex* pnext; unsigned int nFile; unsigned int nBlockPos; uint256 nChainTrust; // ppcoin: trust score of block chain int nHeight; int64_t nMint; int64_t nMoneySupply; unsigned int nFlags; // ppcoin: block index flags enum { BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier }; uint64_t nStakeModifier; // hash modifier for proof-of-stake unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only // proof-of-stake specific fields COutPoint prevoutStake; unsigned int nStakeTime; uint256 hashProof; // block header int nVersion; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; CBlockIndex() { phashBlock = NULL; pprev = NULL; pnext = NULL; nFile = 0; nBlockPos = 0; nHeight = 0; nChainTrust = 0; nMint = 0; nMoneySupply = 0; nFlags = 0; nStakeModifier = 0; nStakeModifierChecksum = 0; hashProof = 0; prevoutStake.SetNull(); nStakeTime = 0; nVersion = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; } CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block) { phashBlock = NULL; pprev = NULL; pnext = NULL; nFile = nFileIn; nBlockPos = nBlockPosIn; nHeight = 0; nChainTrust = 0; nMint = 0; nMoneySupply = 0; nFlags = 0; nStakeModifier = 0; nStakeModifierChecksum = 0; hashProof = 0; if (block.IsProofOfStake()) { SetProofOfStake(); prevoutStake = block.vtx[1].vin[0].prevout; nStakeTime = block.vtx[1].nTime; } else { prevoutStake.SetNull(); nStakeTime = 0; } nVersion = block.nVersion; hashMerkleRoot = block.hashMerkleRoot; nTime = block.nTime; nBits = block.nBits; nNonce = block.nNonce; } CBlock GetBlockHeader() const { CBlock block; block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 GetBlockHash() const { return *phashBlock; } int64_t GetBlockTime() const { return (int64_t)nTime; } uint256 GetBlockTrust() const; bool IsInMainChain() const { return (pnext || this == pindexBest); } bool CheckIndex() const { return true; } int64_t GetPastTimeLimit() const { return GetMedianTimePast(); } enum { nMedianTimeSpan=11 }; int64_t GetMedianTimePast() const { int64_t pmedian[nMedianTimeSpan]; int64_t* pbegin = &pmedian[nMedianTimeSpan]; int64_t* pend = &pmedian[nMedianTimeSpan]; const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) *(--pbegin) = pindex->GetBlockTime(); std::sort(pbegin, pend); return pbegin[(pend - pbegin)/2]; } /** * Returns true if there are nRequired or more blocks of minVersion or above * in the last nToCheck blocks, starting at pstart and going backwards. */ static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck); bool IsProofOfWork() const { return !(nFlags & BLOCK_PROOF_OF_STAKE); } bool IsProofOfStake() const { return (nFlags & BLOCK_PROOF_OF_STAKE); } void SetProofOfStake() { nFlags |= BLOCK_PROOF_OF_STAKE; } unsigned int GetStakeEntropyBit() const { return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1); } bool SetStakeEntropyBit(unsigned int nEntropyBit) { if (nEntropyBit > 1) return false; nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0); return true; } bool GeneratedStakeModifier() const { return (nFlags & BLOCK_STAKE_MODIFIER); } void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier) { nStakeModifier = nModifier; if (fGeneratedStakeModifier) nFlags |= BLOCK_STAKE_MODIFIER; } std::string ToString() const { return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRIx64", nStakeModifierChecksum=%08x, hashProof=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)", pprev, pnext, nFile, nBlockPos, nHeight, FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(), GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW", nStakeModifier, nStakeModifierChecksum, hashProof.ToString().c_str(), prevoutStake.ToString().c_str(), nStakeTime, hashMerkleRoot.ToString().c_str(), GetBlockHash().ToString().c_str()); } void print() const { printf("%s\n", ToString().c_str()); } }; /** Used to marshal pointers into hashes for db storage. */ class CDiskBlockIndex : public CBlockIndex { private: uint256 blockHash; public: uint256 hashPrev; uint256 hashNext; CDiskBlockIndex() { hashPrev = 0; hashNext = 0; blockHash = 0; } explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) { hashPrev = (pprev ? pprev->GetBlockHash() : 0); hashNext = (pnext ? pnext->GetBlockHash() : 0); } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(hashNext); READWRITE(nFile); READWRITE(nBlockPos); READWRITE(nHeight); READWRITE(nMint); READWRITE(nMoneySupply); READWRITE(nFlags); READWRITE(nStakeModifier); if (IsProofOfStake()) { READWRITE(prevoutStake); READWRITE(nStakeTime); } else if (fRead) { const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull(); const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0; } READWRITE(hashProof); // block header READWRITE(this->nVersion); READWRITE(hashPrev); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); READWRITE(blockHash); ) uint256 GetBlockHash() const { if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0) return blockHash; CBlock block; block.nVersion = nVersion; block.hashPrevBlock = hashPrev; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash(); return blockHash; } std::string ToString() const { std::string str = "CDiskBlockIndex("; str += CBlockIndex::ToString(); str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)", GetBlockHash().ToString().c_str(), hashPrev.ToString().c_str(), hashNext.ToString().c_str()); return str; } void print() const { printf("%s\n", ToString().c_str()); } }; /** Describes a place in the block chain to another node such that if the * other node doesn't have the same branch, it can find a recent common trunk. * The further back it is, the further before the fork it may be. */ class CBlockLocator { protected: std::vector<uint256> vHave; public: CBlockLocator() { } explicit CBlockLocator(const CBlockIndex* pindex) { Set(pindex); } explicit CBlockLocator(uint256 hashBlock) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end()) Set((*mi).second); } CBlockLocator(const std::vector<uint256>& vHaveIn) { vHave = vHaveIn; } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vHave); ) void SetNull() { vHave.clear(); } bool IsNull() { return vHave.empty(); } void Set(const CBlockIndex* pindex) { vHave.clear(); int nStep = 1; while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Exponentially larger steps back for (int i = 0; pindex && i < nStep; i++) pindex = pindex->pprev; if (vHave.size() > 10) nStep *= 2; } vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)); } int GetDistanceBack() { // Retrace how far back it was in the sender's branch int nDistance = 0; int nStep = 1; BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return nDistance; } nDistance += nStep; if (nDistance > 10) nStep *= 2; } return nDistance; } CBlockIndex* GetBlockIndex() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return pindex; } } return pindexGenesisBlock; } uint256 GetBlockHash() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return hash; } } return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet); } int GetHeight() { CBlockIndex* pindex = GetBlockIndex(); if (!pindex) return 0; return pindex->nHeight; } }; class CTxMemPool { public: mutable CCriticalSection cs; std::map<uint256, CTransaction> mapTx; std::map<COutPoint, CInPoint> mapNextTx; bool addUnchecked(const uint256& hash, CTransaction &tx); bool remove(const CTransaction &tx, bool fRecursive = false); bool removeConflicts(const CTransaction &tx); void clear(); void queryHashes(std::vector<uint256>& vtxid); unsigned long size() const { LOCK(cs); return mapTx.size(); } bool exists(uint256 hash) const { LOCK(cs); return (mapTx.count(hash) != 0); } bool lookup(uint256 hash, CTransaction& result) const { LOCK(cs); std::map<uint256, CTransaction>::const_iterator i = mapTx.find(hash); if (i == mapTx.end()) return false; result = i->second; return true; } }; extern CTxMemPool mempool; #endif
[ "hello@x314.network" ]
hello@x314.network
485160210ab739d860f84dd1a764d25dec6b386b
9c0c785a565d71fbc00341cbf5de02870cf4184b
/codes - ac/Gym/101653O/19559377_AC_30ms_176kB.cpp
761fef96c555117a4cd99d511715c86b49682dda
[]
no_license
NUC-NCE/algorithm-codes
bd833b4c7b8299704163feffc31dc37e832a6e00
cbe9f78a0b921f5bf433f27587e7eeb944f7eb37
refs/heads/master
2020-06-28T05:14:48.180851
2019-08-02T02:40:51
2019-08-02T02:40:51
200,150,460
2
0
null
null
null
null
UTF-8
C++
false
false
671
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; struct node{ double x,y; bool operator>(const node &a)const{ return x>a.x&&y<a.y; } node(){} }nd[250]; int dp[250]; int main() { int t; cin>>t; while(t--){ memset(dp,0,sizeof(dp)); int n; cin>>n; for(int i=1;i<=n;i++){ cin>>nd[i].x>>nd[i].y; dp[i]=1; } int ans=0; for(int i=1;i<=n;i++){ for(int j=1;j<=i;j++){ if(nd[i]>nd[j]) dp[i]=max(dp[i],dp[j]+1); ans=max(dp[i],ans); } } cout<<ans<<endl; } return 0; }
[ "Nce0506@outlook.com" ]
Nce0506@outlook.com
fb71e3a0ac30b938a0fdb411273f29104f972a66
b96546571289a5096dbb6093107e618d5aef49d3
/CS3388_Assignment4-raytracer/RGB.h
250e13d9d9ba52656ecfa5484d8a741907f0f555
[]
no_license
jstol/CS3388_Assignment4-raytracer
e790785d65a9ffcc0596e60a218ce01147a67467
8c283e42cb274ced44a10cb03f9546b8db6e43b6
refs/heads/master
2020-04-11T05:29:19.924217
2013-12-08T03:28:55
2013-12-08T03:28:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
642
h
// // RGB.h // CS3388_Assignment4-raytracer // // This is a utility class for dealing with RGB colour values. // // Created by Jake on 2013-12-06. // #ifndef CS3388_Assignment4_raytracer_RGB_h #define CS3388_Assignment4_raytracer_RGB_h class RGB{ public: double r; double g; double b; RGB(); RGB(double,double,double); }; // Default constructor // Input: none // Output: N/A RGB::RGB(){ r = 0; g = 0; b = 0; } // Constructor that takes initial RGB values // Input: r,g,b (double) // Output: N/A RGB::RGB(double r, double g, double b){ this->r = r; this->g = g; this->b = b; } #endif
[ "jakestolee@gmail.com" ]
jakestolee@gmail.com
acf3ab224db9c9a037df3c77624bd664bded1630
3f75457ea8a95802b67d1e917335390e2c32bf65
/src/Compiler/Frontend/SLParser.h
33ae4f7197949650c4c2f5b0bb7114816468318b
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
Jgoga/XShaderCompiler
20488c8ec38e88d0ea028b5ce49e6bee5c4fd775
329cb1ca5838827715eafe8550ed12dd3278a917
refs/heads/master
2020-03-26T22:08:08.457938
2018-08-12T21:59:38
2018-08-12T21:59:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,975
h
/* * SLParser.h * * This file is part of the XShaderCompiler project (Copyright (c) 2014-2017 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #ifndef XSC_SL_PARSER_H #define XSC_SL_PARSER_H #include "Parser.h" #include "Visitor.h" #include "Token.h" #include "Variant.h" #include <Xsc/Log.h> #include <vector> #include <string> namespace Xsc { // Syntax parser base class for HLSL and GLSL. class SLParser : public Parser { public: SLParser(Log* log = nullptr); protected: /* === Functions === */ // Accepts the semicolon token (Accept(Tokens::Semicolon)). void Semi(); /* ----- Parsing ----- */ virtual CodeBlockPtr ParseCodeBlock() = 0; virtual VarDeclStmntPtr ParseParameter() = 0; virtual StmntPtr ParseLocalStmnt() = 0; virtual StmntPtr ParseForLoopInitializer() = 0; virtual SwitchCasePtr ParseSwitchCase() = 0; virtual VarDeclPtr ParseVarDecl(VarDeclStmnt* declStmntRef, const TokenPtr& identTkn = nullptr) = 0; ArrayDimensionPtr ParseArrayDimension(bool allowDynamicDimension = false); NullStmntPtr ParseNullStmnt(); CodeBlockStmntPtr ParseCodeBlockStmnt(); ForLoopStmntPtr ParseForLoopStmnt(); WhileLoopStmntPtr ParseWhileLoopStmnt(); DoWhileLoopStmntPtr ParseDoWhileLoopStmnt(); IfStmntPtr ParseIfStmnt(); ElseStmntPtr ParseElseStmnt(); SwitchStmntPtr ParseSwitchStmnt(); CtrlTransferStmntPtr ParseCtrlTransferStmnt(); ReturnStmntPtr ParseReturnStmnt(); ExprStmntPtr ParseExprStmnt(const ExprPtr& expr = nullptr); ExprPtr ParseExpr(); // expr ExprPtr ParseExprWithSequenceOpt(); // expr (, expr)* ExprPtr ParseArrayIndex(); // [ expr ] ExprPtr ParseInitializer(); // = expr SequenceExprPtr ParseSequenceExpr(const ExprPtr& firstExpr); ArrayExprPtr ParseArrayExpr(const ExprPtr& expr); InitializerExprPtr ParseInitializerExpr(); std::vector<VarDeclPtr> ParseVarDeclList(VarDeclStmnt* declStmntRef, TokenPtr firstIdentTkn = nullptr); std::vector<VarDeclStmntPtr> ParseParameterList(); std::vector<StmntPtr> ParseLocalStmntList(); std::vector<ExprPtr> ParseExprList(const Tokens listTerminatorToken, bool allowLastComma = false); std::vector<ArrayDimensionPtr> ParseArrayDimensionList(bool allowDynamicDimension = false); std::vector<ExprPtr> ParseArrayIndexList(); std::vector<ExprPtr> ParseArgumentList(); std::vector<ExprPtr> ParseInitializerList(); std::vector<SwitchCasePtr> ParseSwitchCaseList(); std::string ParseIdent(TokenPtr identTkn = nullptr, SourceArea* area = nullptr); TypeDenoterPtr ParseTypeDenoterWithArrayOpt(const TypeDenoterPtr& baseTypeDenoter); VoidTypeDenoterPtr ParseVoidTypeDenoter(); Variant ParseAndEvaluateConstExpr(); int ParseAndEvaluateConstExprInt(); int ParseAndEvaluateVectorDimension(); void ParseStmntWithCommentOpt(std::vector<StmntPtr>& stmnts, const std::function<StmntPtr()>& parseFunction); }; } // /namespace Xsc #endif // ================================================================================
[ "lukas.hermanns90@gmail.com" ]
lukas.hermanns90@gmail.com
dc4038aa9e9e36a43565141a5c221a14b797ba05
6e7f9fe0dc8a5da6e80c78c240613abfa9c61b89
/codechef/FEB16/CHEFDETE.cpp
e8d48963456755cce7030e460c49c23fc7158648
[]
no_license
aufarg/competitive-programming
131eaebb7efcb9a62765b9e72a996bb325e6ae90
5f7ab03f8b9158aeb1c1847f1d4d2cd87f5d49a4
refs/heads/master
2023-08-31T07:15:32.847738
2016-10-18T03:08:55
2016-10-18T03:08:55
36,449,343
0
0
null
null
null
null
UTF-8
C++
false
false
1,778
cpp
/* DELAPAN.3gp */ #include <vector> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <algorithm> #include <utility> #include <numeric> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <ctime> #include <cassert> using namespace std; #ifdef DEBUG #define debug(...) printf(__VA_ARGS__) #define GetTime() fprintf(stderr,"Running time: %.3lf second\n",((double)clock())/CLOCKS_PER_SEC) #else #define debug(...) #define GetTime() #endif //type definitions typedef long long ll; typedef double db; typedef pair<int,int> pii; typedef vector<int> vint; //abbreviations #define A first #define B second #define F first #define S second #define MP make_pair #define PB push_back //macros #define REP(i,n) for (int i = 0; i < (n); ++i) #define REPD(i,n) for (int i = (n)-1; 0 <= i; --i) #define FOR(i,a,b) for (int i = (a); i <= (b); ++i) #define FORD(i,a,b) for (int i = (a); (b) <= i; --i) #define FORIT(it,c) for (__typeof ((c).begin()) it = (c).begin(); it != (c).end(); it++) #define ALL(a) (a).begin(),(a).end() #define SZ(a) ((int)(a).size()) #define RESET(a,x) memset(a,x,sizeof(a)) #define EXIST(a,s) ((s).find(a) != (s).end()) #define MX(a,b) a = max((a),(b)); #define MN(a,b) a = min((a),(b)); inline void OPEN(const string &s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } /* -------------- end of DELAPAN.3gp's template -------------- */ #define MAXN 100000 int n; int a[MAXN+5]; int main(){ scanf("%d", &n); for (int i = 1; i <= n; ++i) { int x; scanf("%d", &x); a[x] = 1; } for (int i = 1; i <= n; ++i) if (a[i] == 0) printf("%d ", i); puts(""); return 0; }
[ "aufargilbran@gmail.com" ]
aufargilbran@gmail.com
f6836ab5aba2fa6c745403eab047f8feef59b625
29a4c1e436bc90deaaf7711e468154597fc379b7
/modules/boost_math/include/nt2/toolbox/boost_math/function/simd/vmx/altivec/tgamma1pm1.hpp
35451c2ae6e108ac3b0c0c62c3b8b9bcd15b7425
[ "BSL-1.0" ]
permissive
brycelelbach/nt2
31bdde2338ebcaa24bb76f542bd0778a620f8e7c
73d7e8dd390fa4c8d251c6451acdae65def70e0b
refs/heads/master
2021-01-17T12:41:35.021457
2011-04-03T17:37:15
2011-04-03T17:37:15
1,263,345
1
0
null
null
null
null
UTF-8
C++
false
false
749
hpp
////////////////////////////////////////////////////////////////////////////// /// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand /// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI /// /// Distributed under the Boost Software License, Version 1.0 /// See accompanying file LICENSE.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt ////////////////////////////////////////////////////////////////////////////// #ifndef NT2_TOOLBOX_BOOST_MATH_FUNCTION_SIMD_VMX_ALTIVEC_TGAMMA1PM1_HPP_INCLUDED #define NT2_TOOLBOX_BOOST_MATH_FUNCTION_SIMD_VMX_ALTIVEC_TGAMMA1PM1_HPP_INCLUDED #include <nt2/toolbox/boost_math/function/simd/vmx/common/tgamma1pm1.hpp> #endif
[ "jtlapreste@gmail.com" ]
jtlapreste@gmail.com
56e1289ace411a103a5c73e13ffa373c562c1e73
d2d9b2098e73cd41dfee2a1d0a7bdcf89b7d400f
/src/rpcmisc.cpp
4645e1d8db245e5c5cffd15504381554e61dd4d6
[ "MIT" ]
permissive
phonecoin-PHON/PhoneCoinCore
ca02ba48c561d337723b754bfde671398a1de6f8
c7de845fd6feb8390a75788799abc5a34c4fee5d
refs/heads/master
2020-03-28T02:28:11.974392
2019-02-16T19:40:42
2019-02-16T19:40:42
147,572,400
1
0
null
null
null
null
UTF-8
C++
false
false
23,236
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2018 The Bulwark developers // Copyright (c) 2018-2019 The PhoneCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "clientversion.h" #include "init.h" #include "main.h" #include "masternode-sync.h" #include "net.h" #include "netbase.h" #include "rpcserver.h" #include "spork.h" #include "timedata.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet.h" #include "walletdb.h" #endif #include <stdint.h> #include <boost/assign/list_of.hpp> #include <univalue.h> using namespace boost; using namespace boost::assign; using namespace std; /** * @note Do not add or change anything in the information returned by this * method. `getinfo` exists for backwards-compatibility only. It combines * information from wildly different sources in the program, which is a mess, * and is thus planned to be deprecated eventually. * * Based on the source of the information, new information should be added to: * - `getblockchaininfo`, * - `getnetworkinfo` or * - `getwalletinfo` * * Or alternatively, create a specific query method for the information. **/ UniValue getinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info.\n" "\nResult:\n" "{\n" " \"version\": xxxxx, (numeric) the server version\n" " \"protocolversion\": xxxxx, (numeric) the protocol version\n" " \"walletversion\": xxxxx, (numeric) the wallet version\n" " \"balance\": xxxxxxx, (numeric) the total phonecoin balance of the wallet\n" " \"obfuscation_balance\": xxxxxx, (numeric) the anonymized balance of the wallet\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"timeoffset\": xxxxx, (numeric) the time offset\n" " \"connections\": xxxxx, (numeric) the number of connections\n" " \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"testnet\": true|false, (boolean) if the server is using testnet or not\n" " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n" " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n" " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n" " \"paytxfee\": x.xxxx, (numeric) the transaction fee set in phonecoin/kb\n" " \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in phonecoin/kb\n" " \"staking status\": true|false, (boolean) if the wallet is staking or not\n" " \"errors\": \"...\" (string) any error messages\n" "}\n" "\nExamples:\n" + HelpExampleCli("getinfo", "") + HelpExampleRpc("getinfo", "")); proxyType proxy; GetProxy(NET_IPV4, proxy); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("version", CLIENT_VERSION)); obj.push_back(Pair("protocolversion", PROTOCOL_VERSION)); #ifdef ENABLE_WALLET if (pwalletMain) { obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); if (!fLiteMode) obj.push_back(Pair("obfuscation_balance", ValueFromAmount(pwalletMain->GetAnonymizedBalance()))); } #endif obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("timeoffset", GetTimeOffset())); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string()))); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC())); #ifdef ENABLE_WALLET if (pwalletMain) { obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize())); } if (pwalletMain && pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", nWalletUnlockTime)); obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK()))); #endif obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK()))); bool nStaking = false; if (mapHashedBlocks.count(chainActive.Tip()->nHeight)) nStaking = true; else if (mapHashedBlocks.count(chainActive.Tip()->nHeight - 1) && nLastCoinStakeSearchInterval) nStaking = true; obj.push_back(Pair("staking status", (nStaking ? "Staking Active" : "Staking Not Active"))); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } UniValue mnsync(const UniValue& params, bool fHelp) { std::string strMode; if (params.size() == 1) strMode = params[0].get_str(); if (fHelp || params.size() != 1 || (strMode != "status" && strMode != "reset")) { throw runtime_error( "mnsync \"status|reset\"\n" "\nReturns the sync status or resets sync.\n" "\nArguments:\n" "1. \"mode\" (string, required) either 'status' or 'reset'\n" "\nResult ('status' mode):\n" "{\n" " \"IsBlockchainSynced\": true|false, (boolean) 'true' if blockchain is synced\n" " \"lastMasternodeList\": xxxx, (numeric) Timestamp of last MN list message\n" " \"lastMasternodeWinner\": xxxx, (numeric) Timestamp of last MN winner message\n" " \"lastFailure\": xxxx, (numeric) Timestamp of last failed sync\n" " \"nCountFailures\": n, (numeric) Number of failed syncs (total)\n" " \"sumMasternodeList\": n, (numeric) Number of MN list messages (total)\n" " \"sumMasternodeWinner\": n, (numeric) Number of MN winner messages (total)\n" " \"countMasternodeList\": n, (numeric) Number of MN list messages (local)\n" " \"countMasternodeWinner\": n, (numeric) Number of MN winner messages (local)\n" " \"RequestedMasternodeAssets\": n, (numeric) Status code of last sync phase\n" " \"RequestedMasternodeAttempt\": n, (numeric) Status code of last sync attempt\n" "}\n" "\nResult ('reset' mode):\n" "\"status\" (string) 'success'\n" "\nExamples:\n" + HelpExampleCli("mnsync", "\"status\"") + HelpExampleRpc("mnsync", "\"status\"")); } if (strMode == "status") { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("IsBlockchainSynced", masternodeSync.IsBlockchainSynced())); obj.push_back(Pair("lastMasternodeList", masternodeSync.lastMasternodeList)); obj.push_back(Pair("lastMasternodeWinner", masternodeSync.lastMasternodeWinner)); obj.push_back(Pair("lastFailure", masternodeSync.lastFailure)); obj.push_back(Pair("nCountFailures", masternodeSync.nCountFailures)); obj.push_back(Pair("sumMasternodeList", masternodeSync.sumMasternodeList)); obj.push_back(Pair("sumMasternodeWinner", masternodeSync.sumMasternodeWinner)); obj.push_back(Pair("countMasternodeList", masternodeSync.countMasternodeList)); obj.push_back(Pair("countMasternodeWinner", masternodeSync.countMasternodeWinner)); obj.push_back(Pair("RequestedMasternodeAssets", masternodeSync.RequestedMasternodeAssets)); obj.push_back(Pair("RequestedMasternodeAttempt", masternodeSync.RequestedMasternodeAttempt)); return obj; } if (strMode == "reset") { masternodeSync.Reset(); return "success"; } return "failure"; } #ifdef ENABLE_WALLET class DescribeAddressVisitor : public boost::static_visitor<UniValue> { private: isminetype mine; public: DescribeAddressVisitor(isminetype mineIn) : mine(mineIn) {} UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); } UniValue operator()(const CKeyID &keyID) const { UniValue obj(UniValue::VOBJ); CPubKey vchPubKey; obj.push_back(Pair("isscript", false)); if (mine == ISMINE_SPENDABLE) { pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("pubkey", HexStr(vchPubKey))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); } return obj; } UniValue operator()(const CScriptID &scriptID) const { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("isscript", true)); if (mine != ISMINE_NO) { CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end()))); UniValue a(UniValue::VARR); BOOST_FOREACH (const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); } return obj; } }; #endif /* Used for updating/reading spork settings on the network */ UniValue spork(const UniValue& params, bool fHelp) { if (params.size() == 1 && params[0].get_str() == "show") { UniValue ret(UniValue::VOBJ); for (int nSporkID = SPORK_START; nSporkID <= SPORK_END; nSporkID++) { if (sporkManager.GetSporkNameByID(nSporkID) != "Unknown") ret.push_back(Pair(sporkManager.GetSporkNameByID(nSporkID), GetSporkValue(nSporkID))); } return ret; } else if (params.size() == 1 && params[0].get_str() == "active") { UniValue ret(UniValue::VOBJ); for (int nSporkID = SPORK_START; nSporkID <= SPORK_END; nSporkID++) { if (sporkManager.GetSporkNameByID(nSporkID) != "Unknown") ret.push_back(Pair(sporkManager.GetSporkNameByID(nSporkID), IsSporkActive(nSporkID))); } return ret; } else if (params.size() == 2) { int nSporkID = sporkManager.GetSporkIDByName(params[0].get_str()); if (nSporkID == -1) { return "Invalid spork name"; } // SPORK VALUE int64_t nValue = params[1].get_int(); //broadcast new spork if (sporkManager.UpdateSpork(nSporkID, nValue)) { ExecuteSpork(nSporkID, nValue); return "success"; } else { return "failure"; } } throw runtime_error( "spork <name> [<value>]\n" "<name> is the corresponding spork name, or 'show' to show all current spork settings, active to show which sporks are active" "<value> is a epoch datetime to enable or disable spork" + HelpRequiringPassphrase()); } UniValue validateaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress \"phonecoinaddress\"\n" "\nReturn information about the given phonecoin address.\n" "\nArguments:\n" "1. \"phonecoinaddress\" (string, required) The phonecoin address to validate\n" "\nResult:\n" "{\n" " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n" " \"address\" : \"phonecoinaddress\", (string) The phonecoin address validated\n" " \"ismine\" : true|false, (boolean) If the address is yours or not\n" " \"isscript\" : true|false, (boolean) If the key is a script\n" " \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n" " \"iscompressed\" : true|false, (boolean) If the address is compressed\n" " \"account\" : \"account\" (string) The account associated with the address, \"\" is the default account\n" "}\n" "\nExamples:\n" + HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); UniValue ret(UniValue::VOBJ); ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); #ifdef ENABLE_WALLET isminetype mine = pwalletMain ? IsMine(*pwalletMain, dest) : ISMINE_NO; ret.push_back(Pair("ismine", (mine & ISMINE_SPENDABLE) ? true : false)); if (mine != ISMINE_NO) { ret.push_back(Pair("iswatchonly", (mine & ISMINE_WATCH_ONLY) ? true : false)); UniValue detail = boost::apply_visitor(DescribeAddressVisitor(mine), dest); ret.pushKVs(detail); } if (pwalletMain && pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name)); #endif } return ret; } /** * Used by addmultisigaddress / createmultisig: */ CScript _createmultisig_redeemScript(const UniValue& params) { int nRequired = params[0].get_int(); const UniValue& keys = params[1].get_array(); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %u keys, but need at least %d to redeem)", keys.size(), nRequired)); if (keys.size() > 16) throw runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number"); std::vector<CPubKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); #ifdef ENABLE_WALLET // Case 1: PhoneCoin address and we have full public key: CBitcoinAddress address(ks); if (pwalletMain && address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key", ks)); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s", ks)); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: " + ks); pubkeys[i] = vchPubKey; } // Case 2: hex public key else #endif if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: " + ks); pubkeys[i] = vchPubKey; } else { throw runtime_error(" Invalid public key: " + ks); } } CScript result = GetScriptForMultisig(nRequired, pubkeys); if (result.size() > MAX_SCRIPT_ELEMENT_SIZE) throw runtime_error( strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE)); return result; } UniValue createmultisig(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 2) { string msg = "createmultisig nrequired [\"key\",...]\n" "\nCreates a multi-signature address with n signature of m keys required.\n" "It returns a json object with the address and redeemScript.\n" "\nArguments:\n" "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n" "2. \"keys\" (string, required) A json array of keys which are phonecoin addresses or hex-encoded public keys\n" " [\n" " \"key\" (string) phonecoin address or hex-encoded public key\n" " ,...\n" " ]\n" "\nResult:\n" "{\n" " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n" " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n" "}\n" "\nExamples:\n" "\nCreate a multisig address from 2 addresses\n" + HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\""); throw runtime_error(msg); } // Construct using pay-to-script-hash: CScript inner = _createmultisig_redeemScript(params); CScriptID innerID(inner); CBitcoinAddress address(innerID); UniValue result(UniValue::VOBJ); result.push_back(Pair("address", address.ToString())); result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end()))); return result; } UniValue verifymessage(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage \"phonecoinaddress\" \"signature\" \"message\"\n" "\nVerify a signed message\n" "\nArguments:\n" "1. \"phonecoinaddress\" (string, required) The phonecoin address to use for the signature.\n" "2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n" "3. \"message\" (string, required) The message that was signed.\n" "\nResult:\n" "true|false (boolean) If the signature is verified or not.\n" "\nExamples:\n" "\nUnlock the wallet for 30 seconds\n" + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") + "\nCreate the signature\n" + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") + "\nAs json rpc\n" + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\"")); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CPubKey pubkey; if (!pubkey.RecoverCompact(ss.GetHash(), vchSig)) return false; return (pubkey.GetID() == keyID); } UniValue setmocktime(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "setmocktime timestamp\n" "\nSet the local time to given timestamp (-regtest only)\n" "\nArguments:\n" "1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n" " Pass 0 to go back to using the system time."); if (!Params().MineBlocksOnDemand()) throw runtime_error("setmocktime for regression testing (-regtest mode) only"); RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)); SetMockTime(params[0].get_int64()); return NullUniValue; } #ifdef ENABLE_WALLET UniValue getstakingstatus(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getstakingstatus\n" "Returns an object containing various staking information.\n" "\nResult:\n" "{\n" " \"validtime\": true|false, (boolean) if the chain tip is within staking phases\n" " \"haveconnections\": true|false, (boolean) if network connections are present\n" " \"walletunlocked\": true|false, (boolean) if the wallet is unlocked\n" " \"mintablecoins\": true|false, (boolean) if the wallet has mintable coins\n" " \"enoughcoins\": true|false, (boolean) if available coins are greater than reserve balance\n" " \"mnsync\": true|false, (boolean) if masternode data is synced\n" " \"staking status\": true|false, (boolean) if the wallet is staking or not\n" "}\n" "\nExamples:\n" + HelpExampleCli("getstakingstatus", "") + HelpExampleRpc("getstakingstatus", "")); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("validtime", chainActive.Tip()->nTime > 1471482000)); obj.push_back(Pair("haveconnections", !vNodes.empty())); if (pwalletMain) { obj.push_back(Pair("walletunlocked", !pwalletMain->IsLocked())); obj.push_back(Pair("mintablecoins", pwalletMain->MintableCoins())); obj.push_back(Pair("enoughcoins", nReserveBalance <= pwalletMain->GetBalance())); } obj.push_back(Pair("mnsync", masternodeSync.IsSynced())); bool nStaking = false; if (mapHashedBlocks.count(chainActive.Tip()->nHeight)) nStaking = true; else if (mapHashedBlocks.count(chainActive.Tip()->nHeight - 1) && nLastCoinStakeSearchInterval) nStaking = true; obj.push_back(Pair("staking status", nStaking)); return obj; } #endif // ENABLE_WALLET
[ "dev@phonecoin.space" ]
dev@phonecoin.space
ae9f5ee783152781018636e835e0d64e6cb6acfd
72b8ef207bdb32dd54d6c8e40dc32ec0316fc42c
/tests/lunasa/component/tb_lunasa_basic_allocations.cpp
cec79bdfbef7801cf53ca257d59deb5cdbcabb05
[ "MIT" ]
permissive
JudithYi/faodel
567156145b48c7300111f0f60d7564c2f27edf5d
7dc8d2d1ec5bc5c6c107c05f046b8f0a2758c12a
refs/heads/master
2023-02-24T08:08:56.001886
2021-01-25T17:04:31
2021-01-25T17:04:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,036
cpp
// Copyright 2018 National Technology & Engineering Solutions of Sandia, // LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. #include "gtest/gtest.h" #include <iostream> #include <algorithm> #include <pthread.h> #include <sys/time.h> #include <limits.h> #include "faodel-common/Common.hh" #include "lunasa/Lunasa.hh" #include "lunasa/DataObject.hh" using namespace std; using namespace faodel; using namespace lunasa; string default_config = R"EOF( #lkv settings for the server server.max_capacity 32M server.mutex_type rwlock node_role server )EOF"; class LunasaBasic : public testing::Test { protected: void SetUp() override {} void TearDown() override {} uint64_t offset; }; TEST_F(LunasaBasic, inits) { EXPECT_TRUE(Lunasa::SanityCheck()); EXPECT_EQ(0, Lunasa::TotalAllocated()); } TEST_F(LunasaBasic, simpleAlloc) { //Allocate simple data and free it size_t num_bytes = 100*sizeof(int); DataObject obj(0, num_bytes, DataObject::AllocatorType::eager); EXPECT_TRUE(Lunasa::SanityCheck()); EXPECT_LE(num_bytes, Lunasa::TotalAllocated()); //Try writing data to make sure we can use it. int *memi = static_cast<int *>(obj.GetDataPtr()); for(int i = 0; i<100; i++) memi[i] = i; for(int i = 0; i<100; i++) EXPECT_EQ(i, memi[i]); const char *filename = "tb_LunasaTest1.out"; obj.writeToFile(filename); DataObject read_obj(0, num_bytes, DataObject::AllocatorType::eager); read_obj.readFromFile(filename); EXPECT_EQ(0, memcmp(obj.internal_use_only.GetHeaderPtr(), read_obj.internal_use_only.GetHeaderPtr(), obj.GetWireSize())); obj = DataObject(); read_obj = DataObject(); EXPECT_EQ(0, Lunasa::TotalAllocated()); } TEST_F(LunasaBasic, multipleAllocs) { int sizes[] = {16, 81, 92, 48, 54, 64, 112, 3, 12}; //Small chunks, should sum < 1024 vector<pair<int, DataObject>> mems; int spot = 0; int tot_bytes = 0; for(auto s : sizes) { cerr << "allocating " << s << endl; DataObject obj(0, s, DataObject::AllocatorType::eager); mems.push_back(pair<int, DataObject>(s, obj)); tot_bytes += s; } //cerr <<"Total Allocated: "<<lunasa_instance.TotalAllocated()<<endl; //Allocate simple data and free it EXPECT_TRUE(Lunasa::SanityCheck()); EXPECT_LE(tot_bytes, Lunasa::TotalAllocated()); random_shuffle(mems.begin(), mems.end()); for(auto &id_ptr : mems) { id_ptr.second = DataObject(); tot_bytes -= id_ptr.first; EXPECT_LE(tot_bytes, Lunasa::TotalAllocated()); } EXPECT_EQ(0, Lunasa::TotalAllocated()); } const int ALLOCATIONS = 1000; const int THREADS = 4; int main(int argc, char **argv) { int rc = 0; ::testing::InitGoogleTest(&argc, argv); int mpi_rank = 0, mpi_size; /* INITIALIZE Lunasa */ bootstrap::Init(Configuration(default_config), lunasa::bootstrap); bootstrap::Start(); rc = RUN_ALL_TESTS(); /* FINALIZE Lunasa */ bootstrap::Finish(); return rc; }
[ "cdulmer@sandia.gov" ]
cdulmer@sandia.gov
e6d34265b758f6a1999321472ce548b73a0c644a
e3ed6806fd48764d1600c157e97166e99bb83a10
/LowLevelProgramming/LowLevelProgramming/Heap.h
4d23c0a5d9e0981ff51cabef07353ae184e1a684
[]
no_license
tomin83r/LowLevelGames
63f314baf8652a75b02dd3b0f58e3a0bb0cb42fc
b5643de63a0541440c383b2da93eb25ee60ef0c7
refs/heads/master
2020-04-01T12:03:22.437567
2018-10-15T22:25:29
2018-10-15T22:25:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
345
h
#pragma once class Heap { public: Heap(const char name); Heap(); ~Heap(); const char * GetName() const; void AddAllocation(size_t size); void RemoveAllocation(size_t size); size_t TotalAllocation() { return m_allocatedBytes; } void * operator new (size_t size, Heap * pHeap); private: char m_Name[8]; size_t m_allocatedBytes; };
[ "i012997f@student.staffs.ac.uk" ]
i012997f@student.staffs.ac.uk
38147fb74d4997cd2f43b1555dc56e974e13ed76
9a16257581955415465ebeea66d1dc61f943ce7e
/MyProject/MyProject.cpp
ba4fc1ee7d174c5112fc83fe0e0d16562a94d52a
[]
no_license
ricolynx/myProject
c1372c8f580309928f542a173c11be9cda38f19b
c407c521f279aa467719877d89cade4e8656c453
refs/heads/master
2021-01-21T12:03:33.127174
2013-11-05T12:56:29
2013-11-05T12:56:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
506
cpp
// MyProject.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> int _tmain(int argc, _TCHAR* argv[]) { std::cout << "test" <<std::endl; int a =0 , b=0; std::cin >> a >> b; std::cout << a << " * " << b << " = " << a*b << std::endl; std::cout << "the sum of " << a; std::cout << " and " << b; std::cout << " is " << a + b << std::endl; std::cout<< "/*"; std::cout<< "*/"; std::cout<< /* "*/" */"; std::cout<< /*"*/"/* "/*"*/; return -1; }
[ "eric.giraud@gmail.com" ]
eric.giraud@gmail.com
986f5f15eef4da0e31af758924bc53bc72ac3e3c
9b96e57babfb89c724e051f3b3c8aaa3ee36d88b
/代码/EX2_Cal/main.cpp
29d3bb2f551f05a8df79e288ef6441bf1ceccd54
[]
no_license
Sindyang/graduation-project
99cb4d2e91c9aece7f8de8e767debadb99a24032
5a3f0f919e15f447fd1594f3190e6078a502da20
refs/heads/master
2021-04-27T00:11:59.886581
2018-03-04T12:29:00
2018-03-04T12:29:00
123,768,069
0
0
null
null
null
null
GB18030
C++
false
false
15,184
cpp
/* * main.cpp * * Created on: 2016年3月3日 * Author: wangsy */ #include<iostream> #include<fstream> #include<string.h> #include<algorithm> #include<io.h> #include "story.h" using namespace std; void getfiles(string path, vector<string>& files); string getROI(string readpath); string getNE(string readpath); double getdatenum(string ROI); double getlocationnum(string ROI); double getmoneynum(string ROI); double getorgannum(string ROI); double getpernum(string ROI); double getpersonnum(string ROI); double gettimenum(string ROI); double getjjnum(string ROI); double getvbnum(string ROI); double getrbnum(string ROI); double getcdnum(string ROI); int main() { //存储每一篇报道 vector<story> allstory; vector<story>::iterator it; vector<story>::iterator itvec; //存储所有单词的df map<string, double> worddf; map<string, double>::iterator itdf; double maxsim = 0; double sim = 0; string maxid = ""; ifstream in("D:\\TDT\\Result\\path\\path4.txt"); //判断文件是否能打开 if (!in) { cout << "fail to open the file"; return 0; } int count = 0; int num = 0; string readpath; string word; string ROI; string NE; double weight; while (!in.eof()) { vector<string> files; //创建一个新报道 getline(in, readpath); story newstory(readpath); ROI = getROI(readpath); //cout << "ROI = " << ROI << endl; //得到该目录下所有文件 getfiles(readpath, files); int size = files.size(); //读入报道的每一个单词 for (int i = 0; i < size; i++) { string s = files[i]; NE = getNE(files[i]); //cout << NE << endl; if ((NE == "afterStem") || (NE == "nonNE") || (NE == "nn") || (NE == "jj") || (NE == "vb") || (NE == "rb") || (NE == "cd")) continue; fstream filename(files[i].c_str()); if (NE == "date") { weight = getdatenum(ROI); } else if (NE == "location") { weight = getlocationnum(ROI); } else if (NE == "money") { weight = getmoneynum(ROI); } else if (NE == "organization") { weight = getorgannum(ROI); } else if (NE == "percentage") { weight = getpernum(ROI); } else if (NE == "person") { weight = getpersonnum(ROI); } else if (NE == "time") { weight = gettimenum(ROI); } else if (NE == "nnafterStem") { weight = 0.1; } else if (NE == "jjafterStem") { weight = 0.1 * getjjnum(ROI); } else if (NE == "vbafterStem") { weight = 0.1 * getvbnum(ROI); } else if (NE == "rbafterStem") { weight = 0.1 * getrbnum(ROI); } else if (NE == "cdafterStem") { weight = 0.1 * getcdnum(ROI); } else { cout << "The NE is wrong" << endl; } while (!filename.eof()) { getline(filename, word); //去除空白行 if (word != "") { newstory.addword(word, weight); } } filename.close(); } //计算每个单词的df //得到该报道下所有单词 vector<string> words = newstory.getwords(); vector<string>::iterator itwords; for (itwords = words.begin(); itwords != words.end(); itwords++) { itdf = worddf.find(*itwords); if (itdf == worddf.end()) { worddf.insert(pair<string, int>(*itwords, 1)); } else { itdf->second += 1; } } //统计报道中的单词总数 newstory.calnumber(); //计算每一个单词的tf newstory.caltf(); allstory.push_back(newstory); count++; //每50篇报道作为一个单位进行计算 if (count == 50 || allstory.size() == 10000) { //计算tf-idf值 for (itvec = allstory.begin(); itvec != allstory.end(); itvec++) { itvec->caltfidf(worddf, allstory.size()); } //计算余弦相似度 for (itvec = allstory.begin() + 50 * num; itvec != allstory.end(); itvec++) { for (it = allstory.begin(); it != itvec; it++) { sim = itvec->calsim(it); if (sim > maxsim) { maxsim = sim; maxid = it->getid(); } } itvec->getstorysim(maxsim); cout << maxsim << endl; //cout << "id = " << itvec->getid() << endl; //cout << "maxid = " << maxid << endl; maxsim = 0; maxid = ""; } count = 0; num++; } } in.close(); cout << "allstory = " << allstory.size() << endl; //输出相似度 ofstream outfile; outfile.open("D:\\TDT\\Result\\EX13\\EX13_sim.txt"); if (!outfile) { cout << "fail to open the file" << endl; } for (itvec = allstory.begin(); itvec != allstory.end(); itvec++) { itvec->putsim(outfile); } outfile.close(); return 0; } string getROI(string readpath) { int i = readpath.find("2003"); string ROI = readpath.substr(11, i - 12); return ROI; } string getNE(string readpath) { int i = readpath.rfind("\\"); string NE = readpath.substr(i + 1, readpath.length() - i - 5); return NE; } double getdatenum(string ROI) { double weight; if (ROI == "Accidents") { weight = 0.73; } else if (ROI == "Acts of Violence or War") { weight = 0.62; } else if (ROI == "Celebrity and Human Interest News") { weight = 0.64; } else if (ROI == "Elections") { weight = 0.86; } else if (ROI == "Financial News") { weight = 0.61; } else if (ROI == "Legal Criminal Cases") { weight = 0.60; } else if (ROI == "Miscellaneous News") { weight = 0.50; } else if (ROI == "Natural Disasters") { weight = 0.95; } else if (ROI == "New Laws") { weight = 0.498; } else if (ROI == "Political and Diplomatic Meetings") { weight = 0.39; } else if (ROI == "Scandals Hearings") { weight = 0.74; } else if (ROI == "Science and Discovery News") { weight = 0.55; } else if (ROI == "Sports News") { weight = 0.67; } else { cout << "The ROI is wrong" << endl; } return weight; } double getlocationnum(string ROI) { double weight; if (ROI == "Accidents") { weight = 1; } else if (ROI == "Acts of Violence or War") { weight = 1; } else if (ROI == "Celebrity and Human Interest News") { weight = 0.91; } else if (ROI == "Elections") { weight = 0.96; } else if (ROI == "Financial News") { weight = 1; } else if (ROI == "Legal Criminal Cases") { weight = 1; } else if (ROI == "Miscellaneous News") { weight = 1; } else if (ROI == "Natural Disasters") { weight = 1; } else if (ROI == "New Laws") { weight = 0.25; } else if (ROI == "Political and Diplomatic Meetings") { weight = 1; } else if (ROI == "Scandals Hearings") { weight = 0.69; } else if (ROI == "Science and Discovery News") { weight = 1; } else if (ROI == "Sports News") { weight = 0.79; } else { cout << "The ROI is wrong" << endl; } return weight; } double getmoneynum(string ROI) { double weight; if (ROI == "Accidents") { weight = 0.01; } else if (ROI == "Acts of Violence or War") { weight = 0.01; } else if (ROI == "Celebrity and Human Interest News") { weight = 0.01; } else if (ROI == "Elections") { weight = 0.005; } else if (ROI == "Financial News") { weight = 0.01; } else if (ROI == "Legal Criminal Cases") { weight = 0.01; } else if (ROI == "Miscellaneous News") { weight = 0.01; } else if (ROI == "Natural Disasters") { weight = 0.01; } else if (ROI == "New Laws") { weight = 0.18; } else if (ROI == "Political and Diplomatic Meetings") { weight = 0.005; } else if (ROI == "Scandals Hearings") { weight = 0.07; } else if (ROI == "Science and Discovery News") { weight = 0.03; } else if (ROI == "Sports News") { weight = 0.01; } else { cout << "The ROI is wrong" << endl; } return weight; } double getorgannum(string ROI) { double weight; if (ROI == "Accidents") { weight = 0.46; } else if (ROI == "Acts of Violence or War") { weight = 0.52; } else if (ROI == "Celebrity and Human Interest News") { weight = 0.52; } else if (ROI == "Elections") { weight = 0.83; } else if (ROI == "Financial News") { weight = 0.37; } else if (ROI == "Legal Criminal Cases") { weight = 0.64; } else if (ROI == "Miscellaneous News") { weight = 0.38; } else if (ROI == "Natural Disasters") { weight = 0.30; } else if (ROI == "New Laws") { weight = 1; } else if (ROI == "Political and Diplomatic Meetings") { weight = 0.44; } else if (ROI == "Scandals Hearings") { weight = 0.63; } else if (ROI == "Science and Discovery News") { weight = 0.37; } else if (ROI == "Sports News") { weight = 0.42; } else { cout << "The ROI is wrong" << endl; } return weight; } double getpernum(string ROI) { double weight; if (ROI == "Accidents") { weight = 0.01; } else if (ROI == "Acts of Violence or War") { weight = 0.01; } else if (ROI == "Celebrity and Human Interest News") { weight = 0.005; } else if (ROI == "Elections") { weight = 0.09; } else if (ROI == "Financial News") { weight = 0.31; } else if (ROI == "Legal Criminal Cases") { weight = 0.008; } else if (ROI == "Miscellaneous News") { weight = 0.01; } else if (ROI == "Natural Disasters") { weight = 0.01; } else if (ROI == "New Laws") { weight = 0.04; } else if (ROI == "Political and Diplomatic Meetings") { weight = 0.005; } else if (ROI == "Scandals Hearings") { weight = 0.01; } else if (ROI == "Science and Discovery News") { weight = 0.06; } else if (ROI == "Sports News") { weight = 0.008; } else { cout << "The ROI is wrong" << endl; } return weight; } double getpersonnum(string ROI) { double weight; if (ROI == "Accidents") { weight = 0.51; } else if (ROI == "Acts of Violence or War") { weight = 0.63; } else if (ROI == "Celebrity and Human Interest News") { weight = 1; } else if (ROI == "Elections") { weight = 1; } else if (ROI == "Financial News") { weight = 0.43; } else if (ROI == "Legal Criminal Cases") { weight = 0.74; } else if (ROI == "Miscellaneous News") { weight = 0.37; } else if (ROI == "Natural Disasters") { weight = 0.35; } else if (ROI == "New Laws") { weight = 0.503; } else if (ROI == "Political and Diplomatic Meetings") { weight = 0.60; } else if (ROI == "Scandals Hearings") { weight = 1; } else if (ROI == "Science and Discovery News") { weight = 0.26; } else if (ROI == "Sports News") { weight = 1; } else { cout << "The ROI is wrong" << endl; } return weight; } double gettimenum(string ROI) { double weight; if (ROI == "Accidents") { weight = 0.10; } else if (ROI == "Acts of Violence or War") { weight = 0.06; } else if (ROI == "Celebrity and Human Interest News") { weight = 0.03; } else if (ROI == "Elections") { weight = 0.05; } else if (ROI == "Financial News") { weight = 0.001; } else if (ROI == "Legal Criminal Cases") { weight = 0.01; } else if (ROI == "Miscellaneous News") { weight = 0.05; } else if (ROI == "Natural Disasters") { weight = 0.13; } else if (ROI == "New Laws") { weight = 0.02; } else if (ROI == "Political and Diplomatic Meetings") { weight = 0.03; } else if (ROI == "Scandals Hearings") { weight = 0.05; } else if (ROI == "Science and Discovery News") { weight = 0.008; } else if (ROI == "Sports News") { weight = 0.05; } else { cout << "The ROI is wrong" << endl; } return weight; } double getjjnum(string ROI) { double weight; if (ROI == "Accidents") { weight = 0.12; } else if (ROI == "Acts of Violence or War") { weight = 0.12; } else if (ROI == "Celebrity and Human Interest News") { weight = 0.15; } else if (ROI == "Elections") { weight = 0.16; } else if (ROI == "Financial News") { weight = 0.12; } else if (ROI == "Legal Criminal Cases") { weight = 0.13; } else if (ROI == "Miscellaneous News") { weight = 0.13; } else if (ROI == "Natural Disasters") { weight = 0.13; } else if (ROI == "New Laws") { weight = 0.13; } else if (ROI == "Political and Diplomatic Meetings") { weight = 0.15; } else if (ROI == "Scandals Hearings") { weight = 0.12; } else if (ROI == "Science and Discovery News") { weight = 0.16; } else if (ROI == "Sports News") { weight = 0.11; } else { cout << "The ROI is wrong" << endl; } return weight; } double getvbnum(string ROI) { double weight; if (ROI == "Accidents") { weight = 0.3; } else if (ROI == "Acts of Violence or War") { weight = 0.32; } else if (ROI == "Celebrity and Human Interest News") { weight = 0.33; } else if (ROI == "Elections") { weight = 0.31; } else if (ROI == "Financial News") { weight = 0.29; } else if (ROI == "Legal Criminal Cases") { weight = 0.32; } else if (ROI == "Miscellaneous News") { weight = 0.29; } else if (ROI == "Natural Disasters") { weight = 0.32; } else if (ROI == "New Laws") { weight = 0.39; } else if (ROI == "Political and Diplomatic Meetings") { weight = 0.28; } else if (ROI == "Scandals Hearings") { weight = 0.32; } else if (ROI == "Science and Discovery News") { weight = 0.3; } else if (ROI == "Sports News") { weight = 0.32; } else { cout << "The ROI is wrong" << endl; } return weight; } double getrbnum(string ROI) { double weight; if (ROI == "Accidents") { weight = 0.03; } else if (ROI == "Acts of Violence or War") { weight = 0.03; } else if (ROI == "Celebrity and Human Interest News") { weight = 0.04; } else if (ROI == "Elections") { weight = 0.03; } else if (ROI == "Financial News") { weight = 0.04; } else if (ROI == "Legal Criminal Cases") { weight = 0.03; } else if (ROI == "Miscellaneous News") { weight = 0.03; } else if (ROI == "Natural Disasters") { weight = 0.03; } else if (ROI == "New Laws") { weight = 0.05; } else if (ROI == "Political and Diplomatic Meetings") { weight = 0.02; } else if (ROI == "Scandals Hearings") { weight = 0.04; } else if (ROI == "Science and Discovery News") { weight = 0.02; } else if (ROI == "Sports News") { weight = 0.03; } else { cout << "The ROI is wrong" << endl; } return weight; } double getcdnum(string ROI) { double weight; if (ROI == "Accidents") { weight = 0.1; } else if (ROI == "Acts of Violence or War") { weight = 0.05; } else if (ROI == "Celebrity and Human Interest News") { weight = 0.04; } else if (ROI == "Elections") { weight = 0.06; } else if (ROI == "Financial News") { weight = 0.09; } else if (ROI == "Legal Criminal Cases") { weight = 0.05; } else if (ROI == "Miscellaneous News") { weight = 0.05; } else if (ROI == "Natural Disasters") { weight = 0.16; } else if (ROI == "New Laws") { weight = 0.06; } else if (ROI == "Political and Diplomatic Meetings") { weight = 0.03; } else if (ROI == "Scandals Hearings") { weight = 0.06; } else if (ROI == "Science and Discovery News") { weight = 0.06; } else if (ROI == "Sports News") { weight = 0.17; } else { cout << "The ROI is wrong" << endl; } return weight; } void getfiles(string path, vector<string>& files) { //文件句柄 long hFile = 0; //文件信息 struct _finddata_t fileinfo; string p; if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) { do { //如果是目录,迭代之 //如果不是,加入列表 if ((fileinfo.attrib & _A_SUBDIR)) { if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) getfiles(p.assign(path).append("\\").append(fileinfo.name), files); } else { files.push_back( p.assign(path).append("\\").append(fileinfo.name)); } } while (_findnext(hFile, &fileinfo) == 0); _findclose(hFile); } }
[ "863326066@qq.com" ]
863326066@qq.com
7dde062603fa4be0869a896e385c0fb27dc90dcf
3b682e18e6fac1865259507d01f7de41da0f123a
/src/test/test_coolnode.cpp
d548a2fd6cff908f17f9cabd5050fa1415811ed2
[ "MIT" ]
permissive
famousnode/coolnode
d03f3f97c6d554f0d430e23c92cdc4a9f0390249
500c93bc6c6c8956c96a9ac9ebdf750f064ee296
refs/heads/master
2020-03-30T19:42:47.083848
2018-10-12T10:20:15
2018-10-12T10:20:15
149,499,106
1
0
null
null
null
null
UTF-8
C++
false
false
2,427
cpp
// Copyright (c) 2011-2013 The Bitcoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #define BOOST_TEST_MODULE COOL Test Suite #include "main.h" #include "random.h" #include "txdb.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "db.h" #include "wallet.h" #endif #include <boost/filesystem.hpp> #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> CClientUIInterface uiInterface; CWallet* pwalletMain; extern bool fPrintToConsole; extern void noui_connect(); struct TestingSetup { CCoinsViewDB *pcoinsdbview; boost::filesystem::path pathTemp; boost::thread_group threadGroup; TestingSetup() { SetupEnvironment(); fPrintToDebugLog = false; // don't want to write to debug.log file fCheckBlockIndex = true; SelectParams(CBaseChainParams::UNITTEST); noui_connect(); #ifdef ENABLE_WALLET bitdb.MakeMock(); #endif pathTemp = GetTempPath() / strprintf("test_vivaldi_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); boost::filesystem::create_directories(pathTemp); mapArgs["-datadir"] = pathTemp.string(); pblocktree = new CBlockTreeDB(1 << 20, true); pcoinsdbview = new CCoinsViewDB(1 << 23, true); pcoinsTip = new CCoinsViewCache(pcoinsdbview); InitBlockIndex(); #ifdef ENABLE_WALLET bool fFirstRun; pwalletMain = new CWallet("wallet.dat"); pwalletMain->LoadWallet(fFirstRun); RegisterValidationInterface(pwalletMain); #endif nScriptCheckThreads = 3; for (int i=0; i < nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); RegisterNodeSignals(GetNodeSignals()); } ~TestingSetup() { threadGroup.interrupt_all(); threadGroup.join_all(); UnregisterNodeSignals(GetNodeSignals()); #ifdef ENABLE_WALLET delete pwalletMain; pwalletMain = NULL; #endif delete pcoinsTip; delete pcoinsdbview; delete pblocktree; #ifdef ENABLE_WALLET bitdb.Flush(true); #endif boost::filesystem::remove_all(pathTemp); } }; BOOST_GLOBAL_FIXTURE(TestingSetup); void Shutdown(void* parg) { exit(0); } void StartShutdown() { exit(0); } bool ShutdownRequested() { return false; }
[ "43374780+famousnode@users.noreply.github.com" ]
43374780+famousnode@users.noreply.github.com
e4e03b3662378d1281c6a09bcd20e9ac5382918a
822c7cad9a37ec9643eec5007d897617c4b18fd8
/tools/Wires/Tiler/WireTiler.h
40895062cfe05e4039fa411055f08196a2ee178a
[]
no_license
gaoyue17/PyMesh
951bcfaa96df5ccf35259e2efdbf4cb5cddee15d
2198fb23c8885f095cdd02aa4d3b21b42542a3d2
refs/heads/master
2020-12-29T02:19:22.650447
2016-04-10T19:57:52
2016-04-10T19:57:52
55,990,646
1
0
null
2016-04-11T16:55:12
2016-04-11T16:55:12
null
UTF-8
C++
false
false
1,056
h
/* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */ #pragma once #include <vector> #include <Mesh.h> #include <Wires/WireNetwork/WireNetwork.h> #include <Wires/Parameters/ParameterManager.h> class WireTiler { public: typedef Mesh::Ptr MeshPtr; WireTiler(WireNetwork::Ptr unit_wire_network) : m_unit_wire_network(unit_wire_network) {} void with_parameters(ParameterManager::Ptr params) { m_params = params; } public: WireNetwork::Ptr tile_with_guide_bbox( const VectorF& bbox_min, const VectorF& bbox_max, const VectorI& repetitions); WireNetwork::Ptr tile_with_guide_mesh(const MeshPtr mesh); WireNetwork::Ptr tile_with_mixed_patterns( const std::vector<WireNetwork::Ptr>& patterns, const MeshPtr mesh, bool per_vertex_thickness, bool isotropic); private: WireNetwork::Ptr m_unit_wire_network; ParameterManager::Ptr m_params; };
[ "devnull@localhost" ]
devnull@localhost
bae8d0b5dc7bb44e994bb90e0ba0100bcf17d28a
00ef8d964caf4abef549bbeff81a744c282c8c16
/components/certificate_transparency/single_tree_tracker_unittest.cc
a84a78d1ce3f282505209e2698956d293cd3bf27
[ "BSD-3-Clause" ]
permissive
czhang03/browser-android-tabs
8295f466465e89d89109659cff74d6bb9adb8633
0277ceb50f9a90a2195c02e0d96da7b157f3b192
refs/heads/master
2023-02-16T23:55:29.149602
2018-09-14T07:46:16
2018-09-14T07:46:16
149,174,398
1
0
null
null
null
null
UTF-8
C++
false
false
40,451
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/certificate_transparency/single_tree_tracker.h" #include <string> #include <utility> #include <memory> #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/test/histogram_tester.h" #include "components/base32/base32.h" #include "components/certificate_transparency/log_dns_client.h" #include "components/certificate_transparency/mock_log_dns_traffic.h" #include "crypto/sha2.h" #include "net/base/network_change_notifier.h" #include "net/cert/ct_log_verifier.h" #include "net/cert/ct_serialization.h" #include "net/cert/merkle_tree_leaf.h" #include "net/cert/signed_certificate_timestamp.h" #include "net/cert/signed_tree_head.h" #include "net/cert/x509_certificate.h" #include "net/dns/dns_client.h" #include "net/dns/mock_host_resolver.h" #include "net/log/net_log.h" #include "net/log/test_net_log.h" #include "net/log/test_net_log_util.h" #include "net/test/ct_test_util.h" #include "testing/gtest/include/gtest/gtest.h" using net::ct::SignedCertificateTimestamp; using net::ct::SignedTreeHead; using net::ct::GetSampleSignedTreeHead; using net::ct::GetTestPublicKeyId; using net::ct::GetTestPublicKey; using net::ct::kSthRootHashLength; using net::ct::GetX509CertSCT; namespace certificate_transparency { namespace { const char kHostname[] = "example.test"; const char kCanCheckForInclusionHistogramName[] = "Net.CertificateTransparency.CanInclusionCheckSCT"; const char kInclusionCheckResultHistogramName[] = "Net.CertificateTransparency.InclusionCheckResult"; const char kDNSRequestSuffix[] = "dns.example.com"; // These tests use a 0 time-to-live for HostCache entries, so all entries will // be stale. This is fine because SingleTreeTracker considers stale entries to // still be evidence that a DNS lookup was performed for a given hostname. // Ignoring stale entries could be exploited, as an attacker could set their // website's DNS record to have a very short TTL in order to avoid having // inclusion checks performed on the SCTs they provide. constexpr base::TimeDelta kZeroTTL; constexpr base::TimeDelta kMoreThanMMD = base::TimeDelta::FromHours(25); bool GetOldSignedTreeHead(SignedTreeHead* sth) { sth->version = SignedTreeHead::V1; sth->timestamp = base::Time::UnixEpoch() + base::TimeDelta::FromMilliseconds(INT64_C(1348589665525)); sth->tree_size = 12u; const uint8_t kOldSTHRootHash[] = { 0x18, 0x04, 0x1b, 0xd4, 0x66, 0x50, 0x83, 0x00, 0x1f, 0xba, 0x8c, 0x54, 0x11, 0xd2, 0xd7, 0x48, 0xe8, 0xab, 0xbf, 0xdc, 0xdf, 0xd9, 0x21, 0x8c, 0xb0, 0x2b, 0x68, 0xa7, 0x8e, 0x7d, 0x4c, 0x23}; memcpy(sth->sha256_root_hash, kOldSTHRootHash, kSthRootHashLength); sth->log_id = GetTestPublicKeyId(); const uint8_t kOldSTHSignatureData[] = { 0x04, 0x03, 0x00, 0x47, 0x30, 0x45, 0x02, 0x20, 0x15, 0x7b, 0x23, 0x42, 0xa2, 0x5f, 0x88, 0xc9, 0x0b, 0x30, 0xa6, 0xb4, 0x49, 0x50, 0xb3, 0xab, 0xf5, 0x25, 0xfe, 0x27, 0xf0, 0x3f, 0x9a, 0xbf, 0xc1, 0x16, 0x5a, 0x7a, 0xc0, 0x62, 0x2b, 0xbb, 0x02, 0x21, 0x00, 0xe6, 0x57, 0xa3, 0xfe, 0xfc, 0x5a, 0x82, 0x9b, 0x29, 0x46, 0x15, 0x1d, 0xbc, 0xfd, 0x9e, 0x87, 0x7f, 0xd0, 0x00, 0x5d, 0x62, 0x4f, 0x9a, 0x1a, 0x9f, 0x20, 0x79, 0xd0, 0xc1, 0x34, 0x2e, 0x08}; base::StringPiece sp(reinterpret_cast<const char*>(kOldSTHSignatureData), sizeof(kOldSTHSignatureData)); return DecodeDigitallySigned(&sp, &(sth->signature)) && sp.empty(); } scoped_refptr<SignedCertificateTimestamp> GetSCT() { scoped_refptr<SignedCertificateTimestamp> sct; // TODO(eranm): Move setting of the origin field to ct_test_util.cc GetX509CertSCT(&sct); sct->origin = SignedCertificateTimestamp::SCT_FROM_OCSP_RESPONSE; return sct; } std::string LeafHash(const net::X509Certificate* cert, const SignedCertificateTimestamp* sct) { net::ct::MerkleTreeLeaf leaf; if (!GetMerkleTreeLeaf(cert, sct, &leaf)) return std::string(); std::string leaf_hash; if (!HashMerkleTreeLeaf(leaf, &leaf_hash)) return std::string(); return leaf_hash; } std::string Base32LeafHash(const net::X509Certificate* cert, const SignedCertificateTimestamp* sct) { std::string leaf_hash = LeafHash(cert, sct); if (leaf_hash.empty()) return std::string(); return base32::Base32Encode(leaf_hash, base32::Base32EncodePolicy::OMIT_PADDING); } // Fills in |sth| for a tree of size 2, where the root hash is a hash of // the test SCT (from GetX509CertSCT) and another entry, // whose hash is '0a' 32 times. bool GetSignedTreeHeadForTreeOfSize2(SignedTreeHead* sth) { sth->version = SignedTreeHead::V1; // Timestamp is after the timestamp of the test SCT (GetX509CertSCT) // to indicate it can be audited using this STH. sth->timestamp = base::Time::UnixEpoch() + base::TimeDelta::FromMilliseconds(INT64_C(1365354256089)); sth->tree_size = 2; // Root hash is: // HASH (0x01 || HASH(log entry made of test SCT) || HASH(0x0a * 32)) // The proof provided by FillVectorWithValidAuditProofForTreeOfSize2 would // validate with this root hash for the log entry made of the test SCT + // cert. const uint8_t kRootHash[] = {0x16, 0x80, 0xbd, 0x5a, 0x1b, 0xc1, 0xb6, 0xcf, 0x1b, 0x7e, 0x77, 0x41, 0xeb, 0xed, 0x86, 0x8b, 0x73, 0x81, 0x87, 0xf5, 0xab, 0x93, 0x6d, 0xb2, 0x0a, 0x79, 0x0d, 0x9e, 0x40, 0x55, 0xc3, 0xe6}; memcpy(sth->sha256_root_hash, reinterpret_cast<const char*>(kRootHash), kSthRootHashLength); sth->log_id = GetTestPublicKeyId(); // valid signature over the STH, using the test log key at: // https://github.com/google/certificate-transparency/blob/master/test/testdata/ct-server-key.pem const uint8_t kTreeHeadSignatureData[] = { 0x04, 0x03, 0x00, 0x46, 0x30, 0x44, 0x02, 0x20, 0x25, 0xa1, 0x9d, 0x7b, 0xf6, 0xe6, 0xfc, 0x47, 0xa7, 0x2d, 0xef, 0x6b, 0xf4, 0x84, 0x71, 0xb7, 0x7b, 0x7e, 0xd4, 0x4c, 0x7a, 0x5c, 0x4f, 0x9a, 0xb7, 0x04, 0x71, 0x6e, 0xd0, 0xa8, 0x0f, 0x53, 0x02, 0x20, 0x27, 0xe5, 0xed, 0x7d, 0xc3, 0x5d, 0x4c, 0xf0, 0x67, 0x35, 0x5d, 0x8a, 0x10, 0xae, 0x25, 0x87, 0x1a, 0xef, 0xea, 0xd2, 0xf7, 0xe3, 0x73, 0x2f, 0x07, 0xb3, 0x4b, 0xea, 0x5b, 0xdd, 0x81, 0x2d}; base::StringPiece sp(reinterpret_cast<const char*>(kTreeHeadSignatureData), sizeof(kTreeHeadSignatureData)); return DecodeDigitallySigned(&sp, &sth->signature); } void FillVectorWithValidAuditProofForTreeOfSize2( std::vector<std::string>* out_proof) { std::string node(crypto::kSHA256Length, '\0'); for (size_t i = 0; i < crypto::kSHA256Length; ++i) { node[i] = static_cast<char>(0x0a); } out_proof->push_back(node); } void AddCacheEntry(net::HostCache* cache, const std::string& hostname, net::HostCache::Entry::Source source, base::TimeDelta ttl) { cache->Set(net::HostCache::Key(hostname, net::ADDRESS_FAMILY_UNSPECIFIED, 0), net::HostCache::Entry(net::OK, net::AddressList(), source), base::TimeTicks::Now(), ttl); } } // namespace class SingleTreeTrackerTest : public ::testing::Test { void SetUp() override { log_ = net::CTLogVerifier::Create(GetTestPublicKey(), "testlog", kDNSRequestSuffix); ASSERT_TRUE(log_); ASSERT_EQ(log_->key_id(), GetTestPublicKeyId()); const std::string der_test_cert(net::ct::GetDerEncodedX509Cert()); chain_ = net::X509Certificate::CreateFromBytes(der_test_cert.data(), der_test_cert.length()); ASSERT_TRUE(chain_.get()); GetX509CertSCT(&cert_sct_); cert_sct_->origin = SignedCertificateTimestamp::SCT_FROM_OCSP_RESPONSE; net_change_notifier_ = base::WrapUnique(net::NetworkChangeNotifier::CreateMock()); mock_dns_.InitializeDnsConfig(); } protected: void CreateTreeTracker() { log_dns_client_ = std::make_unique<LogDnsClient>( mock_dns_.CreateDnsClient(), net_log_with_source_, 1); tree_tracker_ = std::make_unique<SingleTreeTracker>( log_, log_dns_client_.get(), &host_resolver_, &net_log_); } void CreateTreeTrackerWithDefaultDnsExpectation() { // Default to throttling requests as it means observed log entries will // be frozen in a pending state, simplifying testing of the // SingleTreeTracker. ASSERT_TRUE(ExpectLeafIndexRequestAndThrottle(chain_, cert_sct_)); CreateTreeTracker(); } // Configured the |mock_dns_| to expect a request for the leaf index // and have th mock DNS client throttle it. bool ExpectLeafIndexRequestAndThrottle( const scoped_refptr<net::X509Certificate>& chain, const scoped_refptr<SignedCertificateTimestamp>& sct) { return mock_dns_.ExpectRequestAndSocketError( Base32LeafHash(chain.get(), sct.get()) + ".hash." + kDNSRequestSuffix, net::Error::ERR_TEMPORARILY_THROTTLED); } bool MatchAuditingResultInNetLog(net::TestNetLog& net_log, std::string expected_leaf_hash, bool expected_success) { net::TestNetLogEntry::List entries; net_log.GetEntries(&entries); if (entries.size() == 0) return false; size_t pos = net::ExpectLogContainsSomewhere( entries, 0, net::NetLogEventType::CT_LOG_ENTRY_AUDITED, net::NetLogEventPhase::NONE); const net::TestNetLogEntry& logged_entry = entries[pos]; std::string logged_log_id, logged_leaf_hash; if (!logged_entry.GetStringValue("log_id", &logged_log_id) || !logged_entry.GetStringValue("log_entry", &logged_leaf_hash)) return false; if (base::HexEncode(GetTestPublicKeyId().data(), GetTestPublicKeyId().size()) != logged_log_id) return false; if (base::HexEncode(expected_leaf_hash.data(), expected_leaf_hash.size()) != logged_leaf_hash) return false; bool logged_success; if (!logged_entry.GetBooleanValue("success", &logged_success)) return false; return logged_success == expected_success; } base::MessageLoopForIO message_loop_; MockLogDnsTraffic mock_dns_; scoped_refptr<const net::CTLogVerifier> log_; std::unique_ptr<net::NetworkChangeNotifier> net_change_notifier_; std::unique_ptr<LogDnsClient> log_dns_client_; net::MockCachingHostResolver host_resolver_; std::unique_ptr<SingleTreeTracker> tree_tracker_; scoped_refptr<net::X509Certificate> chain_; scoped_refptr<SignedCertificateTimestamp> cert_sct_; net::TestNetLog net_log_; net::NetLogWithSource net_log_with_source_; }; // Test that an SCT is discarded if the HostResolver cache does not indicate // that the hostname lookup was done using DNS. To perform an inclusion check // in this case could compromise privacy, as the DNS resolver would learn that // the user had visited that host. TEST_F(SingleTreeTrackerTest, DiscardsSCTWhenHostnameNotLookedUpUsingDNS) { CreateTreeTrackerWithDefaultDnsExpectation(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_UNKNOWN, kZeroTTL); base::HistogramTester histograms; // Provide an STH to the tree_tracker_. SignedTreeHead sth; GetSampleSignedTreeHead(&sth); tree_tracker_->NewSTHObserved(sth); // Make sure the SCT status is the same as if there's no STH for this log. EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); // The status for this SCT should still be 'not observed'. EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Exactly one value should be logged, indicating that the SCT could not be // checked for inclusion because of no prior DNS lookup for this hostname. histograms.ExpectUniqueSample(kCanCheckForInclusionHistogramName, 4, 1); // Nothing should be logged in the result histogram or net log since an // inclusion check wasn't performed. histograms.ExpectTotalCount(kInclusionCheckResultHistogramName, 0); EXPECT_EQ(0u, net_log_.GetSize()); } // Test that an SCT is discarded if the hostname it was obtained from is an IP // literal. To perform an inclusion check in this case could compromise privacy, // as the DNS resolver would learn that the user had visited that host. TEST_F(SingleTreeTrackerTest, DiscardsSCTWhenHostnameIsIPLiteral) { CreateTreeTrackerWithDefaultDnsExpectation(); base::HistogramTester histograms; // Provide an STH to the tree_tracker_. SignedTreeHead sth; GetSampleSignedTreeHead(&sth); tree_tracker_->NewSTHObserved(sth); // Make sure the SCT status is the same as if there's no STH for this log. EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); tree_tracker_->OnSCTVerified("::1", chain_.get(), cert_sct_.get()); // The status for this SCT should still be 'not observed'. EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Exactly one value should be logged, indicating that the SCT could not be // checked for inclusion because of no prior DNS lookup for this hostname // (because it's an IP literal). histograms.ExpectUniqueSample(kCanCheckForInclusionHistogramName, 4, 1); // Nothing should be logged in the result histogram or net log since an // inclusion check wasn't performed. histograms.ExpectTotalCount(kInclusionCheckResultHistogramName, 0); EXPECT_EQ(0u, net_log_.GetSize()); } // Test that an SCT is discarded if the network has changed since the hostname // lookup was performed. To perform an inclusion check in this case could // compromise privacy, as the current DNS resolver would learn that the user had // visited that host (it would not already know this already because the // hostname lookup was performed on a different network, using a different DNS // resolver). TEST_F(SingleTreeTrackerTest, DiscardsSCTWhenHostnameLookedUpUsingDNSOnDiffNetwork) { CreateTreeTrackerWithDefaultDnsExpectation(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); // Simulate network change. host_resolver_.GetHostCache()->OnNetworkChange(); base::HistogramTester histograms; // Provide an STH to the tree_tracker_. SignedTreeHead sth; GetSampleSignedTreeHead(&sth); tree_tracker_->NewSTHObserved(sth); // Make sure the SCT status is the same as if there's no STH for this log. EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); // The status for this SCT should still be 'not observed'. EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Exactly one value should be logged, indicating that the SCT could not be // checked for inclusion because of no prior DNS lookup for this hostname on // the current network. histograms.ExpectUniqueSample(kCanCheckForInclusionHistogramName, 4, 1); // Nothing should be logged in the result histogram or net log since an // inclusion check wasn't performed. histograms.ExpectTotalCount(kInclusionCheckResultHistogramName, 0); EXPECT_EQ(0u, net_log_.GetSize()); } // Test that an SCT is classified as pending for a newer STH if the // SingleTreeTracker has not seen any STHs so far. TEST_F(SingleTreeTrackerTest, CorrectlyClassifiesUnobservedSCTNoSTH) { CreateTreeTrackerWithDefaultDnsExpectation(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); base::HistogramTester histograms; // First make sure the SCT has not been observed at all. EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); // Since no STH was provided to the tree_tracker_ the status should be that // the SCT is pending a newer STH. EXPECT_EQ( SingleTreeTracker::SCT_PENDING_NEWER_STH, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Expect logging of a value indicating a valid STH is required. histograms.ExpectUniqueSample(kCanCheckForInclusionHistogramName, 0, 1); EXPECT_EQ(0u, net_log_.GetSize()); } // Test that an SCT is classified as pending an inclusion check if the // SingleTreeTracker has a fresh-enough STH to check inclusion against. TEST_F(SingleTreeTrackerTest, CorrectlyClassifiesUnobservedSCTWithRecentSTH) { CreateTreeTrackerWithDefaultDnsExpectation(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); base::HistogramTester histograms; // Provide an STH to the tree_tracker_. SignedTreeHead sth; GetSampleSignedTreeHead(&sth); tree_tracker_->NewSTHObserved(sth); // Make sure the SCT status is the same as if there's no STH for // this log. EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); // The status for this SCT should be 'pending inclusion check' since the STH // provided at the beginning of the test is newer than the SCT. EXPECT_EQ( SingleTreeTracker::SCT_PENDING_INCLUSION_CHECK, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Exactly one value should be logged, indicating the SCT can be checked for // inclusion, as |tree_tracker_| did have a valid STH when it was notified // of a new SCT. histograms.ExpectUniqueSample(kCanCheckForInclusionHistogramName, 2, 1); // Nothing should be logged in the result histogram since inclusion check // didn't finish. histograms.ExpectTotalCount(kInclusionCheckResultHistogramName, 0); EXPECT_EQ(0u, net_log_.GetSize()); } // Test that the SingleTreeTracker correctly queues verified SCTs for inclusion // checking such that, upon receiving a fresh STH, it changes the SCT's status // from pending newer STH to pending inclusion check. TEST_F(SingleTreeTrackerTest, CorrectlyUpdatesSCTStatusOnNewSTH) { CreateTreeTrackerWithDefaultDnsExpectation(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); base::HistogramTester histograms; // Report an observed SCT and make sure it's in the pending newer STH // state. tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); EXPECT_EQ( SingleTreeTracker::SCT_PENDING_NEWER_STH, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); histograms.ExpectTotalCount(kCanCheckForInclusionHistogramName, 1); // Provide with a fresh STH SignedTreeHead sth; GetSampleSignedTreeHead(&sth); tree_tracker_->NewSTHObserved(sth); // Test that its status has changed. EXPECT_EQ( SingleTreeTracker::SCT_PENDING_INCLUSION_CHECK, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Check that no additional UMA was logged for this case as the histogram is // only supposed to measure the state of newly-observed SCTs, not pending // ones. histograms.ExpectTotalCount(kCanCheckForInclusionHistogramName, 1); EXPECT_EQ(0u, net_log_.GetSize()); } // Test that the SingleTreeTracker does not change an SCT's status if an STH // from the log it was issued by is observed, but that STH is too old to check // inclusion against. TEST_F(SingleTreeTrackerTest, DoesNotUpdatesSCTStatusOnOldSTH) { CreateTreeTrackerWithDefaultDnsExpectation(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); // Notify of an SCT and make sure it's in the 'pending newer STH' state. tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); EXPECT_EQ( SingleTreeTracker::SCT_PENDING_NEWER_STH, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Provide an old STH for the same log. SignedTreeHead sth; GetOldSignedTreeHead(&sth); tree_tracker_->NewSTHObserved(sth); // Make sure the SCT's state hasn't changed. EXPECT_EQ( SingleTreeTracker::SCT_PENDING_NEWER_STH, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); EXPECT_EQ(0u, net_log_.GetSize()); } // Test that the SingleTreeTracker correctly logs that an SCT is pending a new // STH, when it has a valid STH, but the observed SCT is not covered by the // STH. TEST_F(SingleTreeTrackerTest, LogsUMAForNewSCTAndOldSTH) { CreateTreeTrackerWithDefaultDnsExpectation(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); base::HistogramTester histograms; // Provide an old STH for the same log. SignedTreeHead sth; GetOldSignedTreeHead(&sth); tree_tracker_->NewSTHObserved(sth); histograms.ExpectTotalCount(kCanCheckForInclusionHistogramName, 0); // Notify of an SCT and make sure it's in the 'pending newer STH' state. tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); // Exactly one value should be logged, indicating the SCT cannot be checked // for inclusion as the STH is too old. histograms.ExpectUniqueSample(kCanCheckForInclusionHistogramName, 1, 1); EXPECT_EQ(0u, net_log_.GetSize()); } // Test that an entry transitions to the "not found" state if the LogDnsClient // fails to get a leaf index. TEST_F(SingleTreeTrackerTest, TestEntryNotPendingAfterLeafIndexFetchFailure) { ASSERT_TRUE(mock_dns_.ExpectRequestAndSocketError( Base32LeafHash(chain_.get(), cert_sct_.get()) + ".hash." + kDNSRequestSuffix, net::Error::ERR_FAILED)); CreateTreeTracker(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); EXPECT_EQ( SingleTreeTracker::SCT_PENDING_NEWER_STH, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Provide with a fresh STH SignedTreeHead sth; GetSampleSignedTreeHead(&sth); tree_tracker_->NewSTHObserved(sth); base::RunLoop().RunUntilIdle(); EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // There should have been one NetLog event, logged with failure. EXPECT_TRUE(MatchAuditingResultInNetLog( net_log_, LeafHash(chain_.get(), cert_sct_.get()), false)); } // Test that an entry transitions to the "not found" state if the LogDnsClient // succeeds to get a leaf index but fails to get an inclusion proof. TEST_F(SingleTreeTrackerTest, TestEntryNotPendingAfterInclusionCheckFailure) { // Return 12 as the index of this leaf. ASSERT_TRUE(mock_dns_.ExpectLeafIndexRequestAndResponse( Base32LeafHash(chain_.get(), cert_sct_.get()) + ".hash." + kDNSRequestSuffix, 12)); // Expect a request for an inclusion proof for leaf #12 in a tree of size // 21, which is the size of the tree in the STH returned by // GetSampleSignedTreeHead. ASSERT_TRUE(mock_dns_.ExpectRequestAndSocketError( std::string("0.12.21.tree.") + kDNSRequestSuffix, net::Error::ERR_FAILED)); CreateTreeTracker(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); EXPECT_EQ( SingleTreeTracker::SCT_PENDING_NEWER_STH, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Provide with a fresh STH SignedTreeHead sth; GetSampleSignedTreeHead(&sth); tree_tracker_->NewSTHObserved(sth); base::RunLoop().RunUntilIdle(); EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // There should have been one NetLog event, logged with failure. EXPECT_TRUE(MatchAuditingResultInNetLog( net_log_, LeafHash(chain_.get(), cert_sct_.get()), false)); } // Test that an entry transitions to the "included" state if the LogDnsClient // succeeds to get a leaf index and an inclusion proof. TEST_F(SingleTreeTrackerTest, TestEntryIncludedAfterInclusionCheckSuccess) { std::vector<std::string> audit_proof; FillVectorWithValidAuditProofForTreeOfSize2(&audit_proof); // Return 0 as the index for this leaf, so the proof provided // later on would verify. ASSERT_TRUE(mock_dns_.ExpectLeafIndexRequestAndResponse( Base32LeafHash(chain_.get(), cert_sct_.get()) + ".hash." + kDNSRequestSuffix, 0)); // The STH (later on) is for a tree of size 2 and the entry has index 0 // in the tree, so expect an inclusion proof for entry 0 in a tree // of size 2 (0.0.2). ASSERT_TRUE(mock_dns_.ExpectAuditProofRequestAndResponse( std::string("0.0.2.tree.") + kDNSRequestSuffix, audit_proof.begin(), audit_proof.begin() + 1)); CreateTreeTracker(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); EXPECT_EQ( SingleTreeTracker::SCT_PENDING_NEWER_STH, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Provide with a fresh STH, which is for a tree of size 2. SignedTreeHead sth; ASSERT_TRUE(GetSignedTreeHeadForTreeOfSize2(&sth)); ASSERT_TRUE(log_->VerifySignedTreeHead(sth)); tree_tracker_->NewSTHObserved(sth); base::RunLoop().RunUntilIdle(); EXPECT_EQ( SingleTreeTracker::SCT_INCLUDED_IN_LOG, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // There should have been one NetLog event, with success logged. EXPECT_TRUE(MatchAuditingResultInNetLog( net_log_, LeafHash(chain_.get(), cert_sct_.get()), true)); } // Tests that inclusion checks are aborted and SCTs discarded if under critical // memory pressure. TEST_F(SingleTreeTrackerTest, TestInclusionCheckCancelledIfUnderMemoryPressure) { CreateTreeTracker(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); EXPECT_EQ( SingleTreeTracker::SCT_PENDING_NEWER_STH, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Provide with a fresh STH, which is for a tree of size 2. SignedTreeHead sth; ASSERT_TRUE(GetSignedTreeHeadForTreeOfSize2(&sth)); ASSERT_TRUE(log_->VerifySignedTreeHead(sth)); // Make the first event that is processed a critical memory pressure // notification. This should be handled before the response to the first DNS // request, so no requests after the first one should be sent (the leaf index // request). base::MemoryPressureListener::NotifyMemoryPressure( base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL); ASSERT_TRUE(mock_dns_.ExpectLeafIndexRequestAndResponse( Base32LeafHash(chain_.get(), cert_sct_.get()) + ".hash." + kDNSRequestSuffix, 0)); tree_tracker_->NewSTHObserved(sth); base::RunLoop().RunUntilIdle(); // Expect the SCT to have been discarded. EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); } // Test that pending entries transition states correctly according to the // STHs provided: // * Start without an STH. // * Add a collection of entries with mixed timestamps (i.e. SCTs not added // in the order of their timestamps). // * Provide an STH that covers some of the entries, test these are audited. // * Provide another STH that covers more of the entries, test that the entries // already audited are not audited again and that those that need to be // audited are audited, while those that are not covered by that STH are // not audited. TEST_F(SingleTreeTrackerTest, TestMultipleEntriesTransitionStateCorrectly) { SignedTreeHead old_sth; GetOldSignedTreeHead(&old_sth); SignedTreeHead new_sth; GetSampleSignedTreeHead(&new_sth); base::TimeDelta kLessThanMMD = base::TimeDelta::FromHours(23); // Assert the gap between the two timestamps is big enough so that // all assumptions below on which SCT can be audited with the // new STH are true. ASSERT_LT(old_sth.timestamp + (kMoreThanMMD * 2), new_sth.timestamp); // Oldest SCT - auditable by the old and new STHs. scoped_refptr<SignedCertificateTimestamp> oldest_sct(GetSCT()); oldest_sct->timestamp = old_sth.timestamp - kMoreThanMMD; // SCT that's older than the old STH's timestamp but by less than the MMD, // so not auditable by old STH. scoped_refptr<SignedCertificateTimestamp> not_auditable_by_old_sth_sct( GetSCT()); not_auditable_by_old_sth_sct->timestamp = old_sth.timestamp - kLessThanMMD; // SCT that's newer than the old STH's timestamp so is only auditable by // the new STH. scoped_refptr<SignedCertificateTimestamp> newer_than_old_sth_sct(GetSCT()); newer_than_old_sth_sct->timestamp = old_sth.timestamp + kLessThanMMD; // SCT that's older than the new STH's timestamp but by less than the MMD, // so isn't auditable by the new STH. scoped_refptr<SignedCertificateTimestamp> not_auditable_by_new_sth_sct( GetSCT()); not_auditable_by_new_sth_sct->timestamp = new_sth.timestamp - kLessThanMMD; // SCT that's newer than the new STH's timestamp so isn't auditable by the // the new STH. scoped_refptr<SignedCertificateTimestamp> newer_than_new_sth_sct(GetSCT()); newer_than_new_sth_sct->timestamp = new_sth.timestamp + kLessThanMMD; // Set up DNS expectations based on inclusion proof request order. ASSERT_TRUE(ExpectLeafIndexRequestAndThrottle(chain_, oldest_sct)); ASSERT_TRUE( ExpectLeafIndexRequestAndThrottle(chain_, not_auditable_by_old_sth_sct)); ASSERT_TRUE( ExpectLeafIndexRequestAndThrottle(chain_, newer_than_old_sth_sct)); CreateTreeTracker(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); // Add SCTs in mixed order. tree_tracker_->OnSCTVerified(kHostname, chain_.get(), newer_than_new_sth_sct.get()); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), oldest_sct.get()); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), not_auditable_by_new_sth_sct.get()); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), newer_than_old_sth_sct.get()); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), not_auditable_by_old_sth_sct.get()); // Ensure all are in the PENDING_NEWER_STH state. for (const auto& sct : {oldest_sct, not_auditable_by_old_sth_sct, newer_than_old_sth_sct, not_auditable_by_new_sth_sct, newer_than_new_sth_sct}) { ASSERT_EQ( SingleTreeTracker::SCT_PENDING_NEWER_STH, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), sct.get())) << "SCT age: " << sct->timestamp; } // Provide the old STH, ensure only the oldest one is auditable. tree_tracker_->NewSTHObserved(old_sth); // Ensure all but the oldest are in the PENDING_NEWER_STH state. ASSERT_EQ(SingleTreeTracker::SCT_PENDING_INCLUSION_CHECK, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), oldest_sct.get())); for (const auto& sct : {not_auditable_by_old_sth_sct, newer_than_old_sth_sct, not_auditable_by_new_sth_sct, newer_than_new_sth_sct}) { ASSERT_EQ( SingleTreeTracker::SCT_PENDING_NEWER_STH, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), sct.get())) << "SCT age: " << sct->timestamp; } // Provide the newer one, ensure two more are auditable but the // rest aren't. tree_tracker_->NewSTHObserved(new_sth); for (const auto& sct : {not_auditable_by_old_sth_sct, newer_than_old_sth_sct}) { ASSERT_EQ( SingleTreeTracker::SCT_PENDING_INCLUSION_CHECK, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), sct.get())) << "SCT age: " << sct->timestamp; } for (const auto& sct : {not_auditable_by_new_sth_sct, newer_than_new_sth_sct}) { ASSERT_EQ( SingleTreeTracker::SCT_PENDING_NEWER_STH, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), sct.get())) << "SCT age: " << sct->timestamp; } } // Test that if a request for an entry is throttled, it remains in a // pending state. // Test that if several entries are throttled, when the LogDnsClient notifies // of un-throttling all entries are handled. TEST_F(SingleTreeTrackerTest, TestThrottledEntryGetsHandledAfterUnthrottling) { std::vector<std::string> audit_proof; FillVectorWithValidAuditProofForTreeOfSize2(&audit_proof); ASSERT_TRUE(mock_dns_.ExpectLeafIndexRequestAndResponse( Base32LeafHash(chain_.get(), cert_sct_.get()) + ".hash." + kDNSRequestSuffix, 0)); ASSERT_TRUE(mock_dns_.ExpectAuditProofRequestAndResponse( std::string("0.0.2.tree.") + kDNSRequestSuffix, audit_proof.begin(), audit_proof.begin() + 1)); scoped_refptr<SignedCertificateTimestamp> second_sct(GetSCT()); second_sct->timestamp -= base::TimeDelta::FromHours(1); // Process request for |second_sct| ASSERT_TRUE(mock_dns_.ExpectLeafIndexRequestAndResponse( Base32LeafHash(chain_.get(), second_sct.get()) + ".hash." + kDNSRequestSuffix, 1)); ASSERT_TRUE(mock_dns_.ExpectAuditProofRequestAndResponse( std::string("0.1.2.tree.") + kDNSRequestSuffix, audit_proof.begin(), audit_proof.begin() + 1)); CreateTreeTracker(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); SignedTreeHead sth; ASSERT_TRUE(GetSignedTreeHeadForTreeOfSize2(&sth)); tree_tracker_->NewSTHObserved(sth); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), second_sct.get()); // Both entries should be in the pending state, the first because the // LogDnsClient did not invoke the callback yet, the second one because // the LogDnsClient is "busy" with the first entry and so would throttle. ASSERT_EQ( SingleTreeTracker::SCT_PENDING_INCLUSION_CHECK, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); ASSERT_EQ(SingleTreeTracker::SCT_PENDING_INCLUSION_CHECK, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), second_sct.get())); // Process pending DNS queries so later assertions are on handling // of the entries based on replies received. base::RunLoop().RunUntilIdle(); // Check that the first sct is included in the log. ASSERT_EQ( SingleTreeTracker::SCT_INCLUDED_IN_LOG, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Check that the second SCT got an invalid proof and is not included, rather // than being in the pending state. ASSERT_EQ(SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), second_sct.get())); } // Test that proof fetching failure due to DNS config errors is handled // correctly: // (1) Entry removed from pending queue. // (2) UMA logged TEST_F(SingleTreeTrackerTest, TestProofLookupDueToBadDNSConfigHandledCorrectly) { base::HistogramTester histograms; // Provide an STH to the tree_tracker_. SignedTreeHead sth; GetSampleSignedTreeHead(&sth); // Clear existing DNS configuration, so that the DnsClient created // by the MockLogDnsTraffic has no valid DnsConfig. net_change_notifier_.reset(); net_change_notifier_ = base::WrapUnique(net::NetworkChangeNotifier::CreateMock()); CreateTreeTracker(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); tree_tracker_->NewSTHObserved(sth); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); // Make sure the SCT status indicates the entry has been removed from // the SingleTreeTracker's internal queue as the DNS lookup failed // synchronously. EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), cert_sct_.get())); // Exactly one value should be logged, indicating the SCT can be checked for // inclusion, as |tree_tracker_| did have a valid STH when it was notified // of a new SCT. histograms.ExpectUniqueSample(kCanCheckForInclusionHistogramName, 2, 1); // Failure due to DNS configuration should be logged in the result histogram. histograms.ExpectUniqueSample(kInclusionCheckResultHistogramName, 3, 1); } // Test that entries are no longer pending after a network state // change. TEST_F(SingleTreeTrackerTest, DiscardsPendingEntriesAfterNetworkChange) { // Setup expectations for 2 SCTs to pass inclusion checking. // However, the first should be cancelled half way through (when the network // change occurs) and the second should be throttled (and then cancelled) so, // by the end of test, neither should actually have passed the checks. std::vector<std::string> audit_proof; FillVectorWithValidAuditProofForTreeOfSize2(&audit_proof); ASSERT_TRUE(mock_dns_.ExpectLeafIndexRequestAndResponse( Base32LeafHash(chain_.get(), cert_sct_.get()) + ".hash." + kDNSRequestSuffix, 0)); ASSERT_TRUE(mock_dns_.ExpectAuditProofRequestAndResponse( std::string("0.0.2.tree.") + kDNSRequestSuffix, audit_proof.begin(), audit_proof.begin() + 1)); scoped_refptr<SignedCertificateTimestamp> second_sct(GetSCT()); second_sct->timestamp -= base::TimeDelta::FromHours(1); ASSERT_TRUE(mock_dns_.ExpectLeafIndexRequestAndResponse( Base32LeafHash(chain_.get(), second_sct.get()) + ".hash." + kDNSRequestSuffix, 1)); ASSERT_TRUE(mock_dns_.ExpectAuditProofRequestAndResponse( std::string("0.1.2.tree.") + kDNSRequestSuffix, audit_proof.begin(), audit_proof.begin() + 1)); CreateTreeTracker(); AddCacheEntry(host_resolver_.GetHostCache(), kHostname, net::HostCache::Entry::SOURCE_DNS, kZeroTTL); // Provide an STH to the tree_tracker_. SignedTreeHead sth; GetSignedTreeHeadForTreeOfSize2(&sth); tree_tracker_->NewSTHObserved(sth); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), cert_sct_.get()); tree_tracker_->OnSCTVerified(kHostname, chain_.get(), second_sct.get()); for (auto sct : {cert_sct_, second_sct}) { EXPECT_EQ( SingleTreeTracker::SCT_PENDING_INCLUSION_CHECK, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), sct.get())); } net_change_notifier_->NotifyObserversOfNetworkChangeForTests( net::NetworkChangeNotifier::CONNECTION_UNKNOWN); base::RunLoop().RunUntilIdle(); for (auto sct : {cert_sct_, second_sct}) { EXPECT_EQ( SingleTreeTracker::SCT_NOT_OBSERVED, tree_tracker_->GetLogEntryInclusionStatus(chain_.get(), sct.get())); } } } // namespace certificate_transparency
[ "artem@brave.com" ]
artem@brave.com
0caacd3a1724b719bed2ab1d64ff0480b4a860ca
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_1243_httpd-2.2.16.cpp
89eb9af5e0bc0f3663775a9331e3452ec962edc1
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,649
cpp
static int setup_choice_response(request_rec *r, negotiation_state *neg, var_rec *variant) { request_rec *sub_req; const char *sub_vary; if (!variant->sub_req) { int status; sub_req = ap_sub_req_lookup_file(variant->file_name, r, NULL); status = sub_req->status; if (status != HTTP_OK && !apr_table_get(sub_req->err_headers_out, "TCN")) { ap_destroy_sub_req(sub_req); return status; } variant->sub_req = sub_req; } else { sub_req = variant->sub_req; } /* The variant selection algorithm told us to return a "Choice" * response. This is the normal variant response, with * some extra headers. First, ensure that the chosen * variant did or will not itself engage in transparent negotiation. * If not, set the appropriate headers, and fall through to * the normal variant handling */ /* This catches the error that a transparent type map selects a * transparent multiviews resource as the best variant. * * XXX: We do not signal an error if a transparent type map * selects a _non_transparent multiviews resource as the best * variant, because we can generate a legal negotiation response * in this case. In this case, the vlist_validator of the * nontransparent subrequest will be lost however. This could * lead to cases in which a change in the set of variants or the * negotiation algorithm of the nontransparent resource is never * propagated up to a HTTP/1.1 cache which interprets Vary. To be * completely on the safe side we should return HTTP_VARIANT_ALSO_VARIES * for this type of recursive negotiation too. */ if (neg->is_transparent && apr_table_get(sub_req->err_headers_out, "TCN")) { return HTTP_VARIANT_ALSO_VARIES; } /* This catches the error that a transparent type map recursively * selects, as the best variant, another type map which itself * causes transparent negotiation to be done. * * XXX: Actually, we catch this error by catching all cases of * type map recursion. There are some borderline recursive type * map arrangements which would not produce transparent * negotiation protocol errors or lack of cache propagation * problems, but such arrangements are very hard to detect at this * point in the control flow, so we do not bother to single them * out. * * Recursive type maps imply a recursive arrangement of negotiated * resources which is visible to outside clients, and this is not * supported by the transparent negotiation caching protocols, so * if we are to have generic support for recursive type maps, we * have to create some configuration setting which makes all type * maps non-transparent when recursion is enabled. Also, if we * want recursive type map support which ensures propagation of * type map changes into HTTP/1.1 caches that handle Vary, we * would have to extend the current mechanism for generating * variant list validators. */ if (sub_req->handler && strcmp(sub_req->handler, "type-map") == 0) { return HTTP_VARIANT_ALSO_VARIES; } /* This adds an appropriate Variant-Vary header if the subrequest * is a multiviews resource. * * XXX: TODO: Note that this does _not_ handle any Vary header * returned by a CGI if sub_req is a CGI script, because we don't * see that Vary header yet at this point in the control flow. * This won't cause any cache consistency problems _unless_ the * CGI script also returns a Cache-Control header marking the * response as cachable. This needs to be fixed, also there are * problems if a CGI returns an Etag header which also need to be * fixed. */ if ((sub_vary = apr_table_get(sub_req->err_headers_out, "Vary")) != NULL) { apr_table_setn(r->err_headers_out, "Variant-Vary", sub_vary); /* Move the subreq Vary header into the main request to * prevent having two Vary headers in the response, which * would be legal but strange. */ apr_table_setn(r->err_headers_out, "Vary", sub_vary); apr_table_unset(sub_req->err_headers_out, "Vary"); } apr_table_setn(r->err_headers_out, "Content-Location", ap_escape_path_segment(r->pool, variant->file_name)); set_neg_headers(r, neg, alg_choice); /* add Alternates and Vary */ /* Still to do by caller: add Expires */ return 0; }
[ "993273596@qq.com" ]
993273596@qq.com
e4a69e2a7ef8a47f50804916b2ee57c906b0ca58
40554cc498001226d69c81e060c879e32e633058
/libs/MaidSafe-Transport/src/maidsafe/transport/nat_detection.cc
caf708c15f26ac36a6748c55012ab4faa4916790
[]
no_license
AdrienLE/p2pstorage
9c39840b406475aa82f16e944365234f0f10aee7
1bd8bb5946e9533d57494d6468bd593b138d910d
refs/heads/master
2020-12-24T14:45:04.595752
2017-12-24T02:31:48
2017-12-24T02:31:48
10,205,715
1
0
null
null
null
null
UTF-8
C++
false
false
3,594
cc
/* Copyright (c) 2011 maidsafe.net limited All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the maidsafe.net limited nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "maidsafe/transport/nat_detection.h" #include "maidsafe/transport/transport.h" #include "maidsafe/transport/message_handler.h" #include "maidsafe/transport/nat_detection_rpcs.h" namespace args = std::placeholders; namespace maidsafe { namespace transport { NatDetection::NatDetection() : rpcs_(new NatDetectionRpcs()) {} void NatDetection::Detect( const std::vector<maidsafe::transport::Contact>& contacts, const bool& full, TransportPtr transport, MessageHandlerPtr message_handler, NatType* nat_type, Endpoint *rendezvous_endpoint) { boost::mutex mutex; boost::condition_variable cond_var; std::vector<maidsafe::transport::Contact> directly_connected_contacts; for (auto itr = contacts.begin(); itr != contacts.end(); ++itr) if ((*itr).IsDirectlyConnected()) directly_connected_contacts.push_back(*itr); boost::mutex::scoped_lock lock(mutex); rpcs_->NatDetection(directly_connected_contacts, transport, message_handler, full, std::bind(&NatDetection::DetectCallback, this, args::_1, args::_2, nat_type, transport, rendezvous_endpoint, &cond_var)); cond_var.timed_wait(lock, kDefaultInitialTimeout); } void NatDetection::DetectCallback(const int &nat_type, const TransportDetails &details, NatType *out_nat_type, TransportPtr transport, Endpoint *rendezvous_endpoint, boost::condition_variable *cond_var) { if (nat_type >= 0) { *out_nat_type = static_cast<NatType>(nat_type); transport->transport_details_.endpoint = details.endpoint; *rendezvous_endpoint = details.rendezvous_endpoint; if (nat_type == transport::kPortRestricted) transport->transport_details_.rendezvous_endpoint = details.rendezvous_endpoint; cond_var->notify_one(); } } } // namespace transport } // namespace maidsafe
[ "adrien.ecoffet@gmail.com" ]
adrien.ecoffet@gmail.com
706765faa7ea67a91e430adb59da85dda93e8619
b379561691847bfc91f4b8cf135568d33affde22
/NavigationDialog.h
445410117bd3b5639bf931d8373a8c61d33b8465
[]
no_license
cloud-jxy/test
44a8afaab50f8dd18c6cbd04a498be58a0653e09
8a1efd95ce1e1e2c3fe14f59f4d6a2491666d53d
refs/heads/master
2021-01-10T13:12:33.814373
2019-04-26T03:03:54
2019-04-26T03:03:54
51,414,452
0
1
null
null
null
null
GB18030
C++
false
false
740
h
#pragma once #include "afxcmn.h" class CAbovepanDialog; class CTestDlg; // NavigationDialog 对话框 class NavigationDialog : public CDialogEx { DECLARE_DYNAMIC(NavigationDialog) public: NavigationDialog(CWnd* pParent = NULL); // 标准构造函数 virtual ~NavigationDialog(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_NAVIGATION_DIALOG }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: virtual BOOL OnInitDialog(); CTestDlg *m_p_parent_dlg; afx_msg void OnClose(); afx_msg void OnBnClickedButtonCostom(); afx_msg void OnBnClickedButtonCar(); afx_msg void OnBnClickedButtonAbovePan(); CAbovepanDialog *m_abovepanDlg = NULL; };
[ "xueyun0430@icloud.com" ]
xueyun0430@icloud.com
65c01617c63cdd9b9f1f9bc97d0da37963c818c3
a81c07a5663d967c432a61d0b4a09de5187be87b
/chrome/browser/sync/wifi_configuration_sync_service_factory.cc
394b3eb9db94d0b348484d4cd2e50eb5e7ff6b6a
[ "BSD-3-Clause" ]
permissive
junxuezheng/chromium
c401dec07f19878501801c9e9205a703e8643031
381ce9d478b684e0df5d149f59350e3bc634dad3
refs/heads/master
2023-02-28T17:07:31.342118
2019-09-03T01:42:42
2019-09-03T01:42:42
205,967,014
2
0
BSD-3-Clause
2019-09-03T01:48:23
2019-09-03T01:48:23
null
UTF-8
C++
false
false
2,173
cc
// Copyright 2019 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/sync/wifi_configuration_sync_service_factory.h" #include "base/memory/singleton.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/model_type_store_service_factory.h" #include "chrome/common/channel_info.h" #include "chromeos/components/sync_wifi/pending_network_configuration_tracker_impl.h" #include "chromeos/components/sync_wifi/wifi_configuration_sync_service.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/sync/model/model_type_store_service.h" // static sync_wifi::WifiConfigurationSyncService* WifiConfigurationSyncServiceFactory::GetForProfile(Profile* profile) { return static_cast<sync_wifi::WifiConfigurationSyncService*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } // static WifiConfigurationSyncServiceFactory* WifiConfigurationSyncServiceFactory::GetInstance() { return base::Singleton<WifiConfigurationSyncServiceFactory>::get(); } WifiConfigurationSyncServiceFactory::WifiConfigurationSyncServiceFactory() : BrowserContextKeyedServiceFactory( "WifiConfigurationSyncService", BrowserContextDependencyManager::GetInstance()) { DependsOn(ModelTypeStoreServiceFactory::GetInstance()); } WifiConfigurationSyncServiceFactory::~WifiConfigurationSyncServiceFactory() = default; KeyedService* WifiConfigurationSyncServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { return new sync_wifi::WifiConfigurationSyncService( chrome::GetChannel(), ModelTypeStoreServiceFactory::GetForProfile( Profile::FromBrowserContext(context)) ->GetStoreFactory()); } void WifiConfigurationSyncServiceFactory::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { sync_wifi::PendingNetworkConfigurationTrackerImpl::RegisterProfilePrefs( registry); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
2207ccb2e9dad0ab3f2e03a7bfe5ead7fbc16511
0c4783b88f554dba58f6361a9f165122171691d6
/source/main.cpp
520ae112588bb56df12daaa8a948ce72db09da76
[]
no_license
j-jakubowski/SmartLock
828bceebf25714167558ee0ec894eb90e3a19338
b676f9cf869bc94b1d2d2e49014e30727618f824
refs/heads/main
2023-06-03T13:02:04.087106
2021-06-20T20:43:37
2021-06-20T20:43:37
378,736,944
0
0
null
null
null
null
UTF-8
C++
false
false
833
cpp
/* * Copyright (c) 2015, Freescale Semiconductor, Inc. * Copyright 2016-2020 NXP * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ extern "C"{ #include "pin_mux.h" #include "clock_config.h" #include "board.h" #include "fsl_debug_console.h" #include "FreeRTOS.h" #include "task.h" #include "audioThread.h" } void setupBoard(void) { BOARD_ConfigMPU(); BOARD_InitPins(); BOARD_BootClockRUN(); BOARD_InitDebugConsole(); USER_LED_OFF(); } int main(void) { setupBoard(); setupAudioThread(); if (xTaskCreate(audioThread, "AudioThread", configMINIMAL_STACK_SIZE + 100, NULL, tskIDLE_PRIORITY + 1, NULL)!= pdPASS) { PRINTF("Audio Thread creation failed"); while (1){} } vTaskStartScheduler(); while(1) { } }
[ "jakub.k.jakubowski@gmail.com" ]
jakub.k.jakubowski@gmail.com
edabb2262c53b82cfb03d02d19a2f5bc78a0f48d
0528bd51505688c65648f83375b7b4810e90bb44
/Level 4 GUI/Level 4/Level 4/HashFile/PhysicalFile.cpp
677659526288f4dfd18c4d52d98cb748dce22ab1
[]
no_license
fedidat/FMS-Project
b4445e6b41305c4de3417a7cb4ea4b50c86e80c8
82f3496be15b76f5a19ec08dbbf9cd0b6058de4c
refs/heads/master
2021-09-04T04:28:27.644285
2018-01-15T20:39:20
2018-01-15T20:39:20
113,072,448
0
0
null
null
null
null
UTF-8
C++
false
false
14,900
cpp
#include "stdafx.h" #include <iostream> #include "PhysicalFile.h" using namespace std; /************************************************************************ * FUNCTION * * PhysicalFile * * PARAMETERS * * none * * RETURN VALUE * * none * * MEANING * * Default constructor: creates an empty class for a future physical * * file. * * SEE ALSO * ************************************************************************/ PhysicalFile::PhysicalFile(void) { opened = false; //initialize the class's variables FileName = ""; } /************************************************************************ * FUNCTION * * PhysicalFile * * PARAMETERS * * fileName: string, the name of the file. * * workingDir: string, the directory of the file. * * code: integer, 1 if the file doesn't already exists, 2 otherwise. * * Gives a meaning to the fourth parameter. * * RETURN VALUE * * none * * MEANING * * Full constructor. Assigns values to the variables and calls * * the functions necessary to the creation or the opening of the * * file. * * SEE ALSO * * PhysicalFile::pcreate, PhysicalFile::popen. * ************************************************************************/ PhysicalFile::PhysicalFile(string fileName, string workingDir, int code) { FileName = fileName; //initialize the class's variables WorkingDir = workingDir; int sizeOrMode; switch(code) //depending on the code, we will now want to create or to open a file { case 1: sizeOrMode = 1000; pcreate(fileName, sizeOrMode, workingDir); break; case 2: sizeOrMode = 0; popen(fileName, sizeOrMode, workingDir); break; default: //should have used the default constructor if you didn't want to create or to open a file now throwErr("ERROR: Illegal operation code"); } } /************************************************************************ * FUNCTION * * PhysicalFile * * PARAMETERS * * fileName: string, the name of the file. * * workingDir: string, the directory of the file. * * code: integer, 1 if the file doesn't already exists, 2 otherwise. * * Gives a meaning to the fourth parameter. * * sizeOrMode: positive integer, if code 1, size of the file, and if * * code 2, I/O opening mode. * * RETURN VALUE * * none * * MEANING * * Full constructor. Assigns values to the variables and calls * * the functions necessary to the creation or the opening of the * * file. * * Same as the function without sizeOrMode provided, with this field * * provided by the user. * * SEE ALSO * * PhysicalFile::pcreate, PhysicalFile::popen. * ************************************************************************/ PhysicalFile::PhysicalFile(string fileName, string workingDir, int code, unsigned int sizeOrMode) { FileName = fileName; //initialize the class's variables WorkingDir = workingDir; switch(code) //depending on the code, we will now want to create or to open a file { case 1: pcreate(fileName, sizeOrMode, workingDir); break; case 2: popen(fileName, sizeOrMode, workingDir); break; default: throwErr("ERROR: Illegal operation code"); } } /************************************************************************ * FUNCTION * * ~PhysicalFile * * PARAMETERS * * none * * RETURN VALUE * * none * * MEANING * * Destructor. Closes the file if not previously done and * * the file has not been deleted. * * SEE ALSO * * PhysicalFile::pclose. * ************************************************************************/ PhysicalFile::~PhysicalFile(void) { if(opened == true) //if a file is still opened pclose(); //we close it } /************************************************************************ * FUNCTION * * pcreate * * PARAMETERS * * fileName: string, the name of the file. * * workingDir: string, the directory of the file. * * fileSize: positive integer, the size of the file in blocks. * * RETURN VALUE * * none * * MEANING * * Creates the file as a series of empty physical Blocks. * * SEE ALSO * * PhysicalFile::InitializeData, PhysicalFile::pclose. * ************************************************************************/ void PhysicalFile::pcreate(string fileName, unsigned int fileSize, string workingDir) { string filePath = workingDir + "\\" + fileName + ".hash"; //I find it more efficient to store the complete path than add it twice, but I may be wrong if(FileExists(filePath)) //if a file with the same name exists, it can't be created again before it is deleted throwErr("ERROR: The file could not be created"); else { Filefl.open(filePath.c_str(), ios::binary | ios::out); //opening the file for output will 'create' it opened = true; //initilizing opened and FileSize class variables FileSize = fileSize; InitializeData(); //initlize the data blocks by filling the file with binary zeros pclose(); //closing the file } } /************************************************************************ * FUNCTION * * pdelete * * PARAMETERS * * none * * RETURN VALUE * * none * * MEANING * * Deletes the file on the physical level: all unsaved data is lost. * * SEE ALSO * ************************************************************************/ void PhysicalFile::pdelete(void) { if(opened) //if the file is still opened, it cannot be deleted throwErr("ERROR: The file is still opened", true); else //if the file has been closed beforehand, it can be deleted { if(remove((WorkingDir + '\\' + FileName + ".hash").c_str()) != 0) //if the file could not be deleted for some reason throwErr("ERROR: Failed to delete the file", true); //display the errno error code, abort FileName = ""; //if it has been done, the file's name is "removed" } } /************************************************************************ * FUNCTION * * popen * * PARAMETERS * * fileName: string, the name of the file. * * mode: I/O opening mode: 0 for input, 1 for output, 2 for both. * * workingDir: string, the directory of the file. * * RETURN VALUE * * none * * MEANING * * Opens the file for input/output/both. * * SEE ALSO * * PhysicalFile::readFH * ************************************************************************/ void PhysicalFile::popen(string fileName, int mode, string workingDir) { Filefl.open((workingDir + "\\" + fileName + ".hash").c_str(), ios::in | ios::binary); //open in read-only mode if(!Filefl) //if the file did not open in read-only mode, display error and exception throwErr("ERROR: The file could not be opened", true); readFH(); if(mode == 0) { opened = true; CurrBlock.Nr = -1; } else if(mode == 1 || mode == 2) { Filefl.close(); Filefl.open((workingDir + "\\" + fileName + ".hash").c_str(), ios::in | ios::out | ios::binary); if(Filefl) { opened = true; CurrBlock.Nr = -1; } else throwErr("ERROR: The file could not be opened in output mode", true); } else throwErr("ERROR: Illegal open mode input"); FileName = fileName; //the file has successfully been opened, now initializing some variables openmode = mode; WorkingDir = workingDir; CurrBlock.Buffer = new PhysicalBlock(); } /************************************************************************ * FUNCTION * * pclose * * PARAMETERS * * none * * RETURN VALUE * * none * * MEANING * * Closes the file if it was not previously closed * * SEE ALSO * ************************************************************************/ void PhysicalFile::pclose(void) { if(opened) { Filefl.close(); opened = false; } } /************************************************************************ * FUNCTION * * writeBlock * * PARAMETERS * * none * * RETURN VALUE * * none * * MEANING * * Writes a block to the current block. * * SEE ALSO * ************************************************************************/ void PhysicalFile::writeBlock(void) { SeekToBlock(CurrBlock.Nr); Filefl.write(reinterpret_cast<char*>(CurrBlock.Buffer), sizeof(PhysicalBlock)); } /************************************************************************ * FUNCTION * * writeBlock * * PARAMETERS * * position: positive integer, the block's position. * * RETURN VALUE * * none * * MEANING * * Writes a block to the desired block number. * * SEE ALSO * * PhysicalFile::SeekToBlock. * ************************************************************************/ void PhysicalFile::writeBlock(unsigned int position) { SeekToBlock(position); Filefl.write(reinterpret_cast<char*>(CurrBlock.Buffer), sizeof(PhysicalBlock)); } /************************************************************************ * FUNCTION * * readBlock * * PARAMETERS * * none * * RETURN VALUE * * none * * MEANING * * Reads from the current block. * * SEE ALSO * * PhysicalFile::SeekToBlock. * ************************************************************************/ void PhysicalFile::readBlock(void) { SeekToBlock(CurrBlock.Nr); Filefl.read(reinterpret_cast<char*>(CurrBlock.Buffer), sizeof(PhysicalBlock)); } /************************************************************************ * FUNCTION * * readBlock * * PARAMETERS * * position: positive integer, the block's position. * * RETURN VALUE * * none * * MEANING * * Reads from the desired block. * * SEE ALSO * * PhysicalFile::SeekToBlock. * ************************************************************************/ void PhysicalFile::readBlock(unsigned int position) { SeekToBlock(position); Filefl.read(reinterpret_cast<char*>(CurrBlock.Buffer), sizeof(PhysicalBlock)); } /************************************************************************ * FUNCTION * * writeFH * * PARAMETERS * * none * * RETURN VALUE * * none * * MEANING * * Writes the metadata block at position 0. * * SEE ALSO * * PhysicalFile::SeekToBlock. * ************************************************************************/ void PhysicalFile::writeFH(void) { SeekToBlock(0); Filefl.write(reinterpret_cast<char*>(&FHBuffer), sizeof(PhysicalBlock)); } /************************************************************************ * FUNCTION * * readFH * * PARAMETERS * * none * * RETURN VALUE * * none * * MEANING * * Reads the metadata block at position 0. * * SEE ALSO * * PhysicalFile::SeekToBlock. * ************************************************************************/ void PhysicalFile::readFH(void) { SeekToBlock(0); Filefl.read(reinterpret_cast<char*>(&FHBuffer), sizeof(PhysicalBlock)); } /************************************************************************ * FUNCTION * * SeekToBlock * * PARAMETERS * * position: positive integer, the block's position. * * RETURN VALUE * * none * * MEANING * * Changes the position of the current block to the desired block, * * for future use of read/write block functions. * * SEE ALSO * * PhysicalFile::SeekToBlock. * ************************************************************************/ void PhysicalFile::SeekToBlock(unsigned int position) { if(position > FileSize) throwErr("ERROR: Block does not exist"); int ByteNumber = (position*BLOCK_LENGTH); Filefl.seekg(ByteNumber); Filefl.seekp(ByteNumber); CurrBlock.Nr = position; } /************************************************************************ * FUNCTION * * FileExists * * PARAMETERS * * filePath: string, represents the path to the file to be checked. * * RETURN VALUE * * bool: true if the file already exists, false otherwise. * * MEANING * * Checks if the file already exists, used by functions such as the * * pcreate. * * SEE ALSO * ************************************************************************/ bool PhysicalFile::FileExists(string filePath) { fstream FileOpen(filePath.c_str(), ios::binary | ios::in); if(FileOpen) { FileOpen.close(); return true; } FileOpen.close(); return false; } /************************************************************************ * FUNCTION * * InitializeData * * PARAMETERS * * none * * RETURN VALUE * * none * * MEANING * * Initializes all blocks in the file to "empty" blocks (their data is * * a string of zeros). * * SEE ALSO * * PhysicalFile::SeekToBlock, PhysicalFile::writeBlock. * ************************************************************************/ void PhysicalFile::InitializeData(void) { PhysicalBlock Empty; CurrBlock.Buffer = &Empty; CurrBlock.Nr=0; for(CurrBlock.Buffer->BlockNr=0 ; CurrBlock.Buffer->BlockNr < FileSize ; CurrBlock.Buffer->BlockNr++) { writeBlock(CurrBlock.Buffer->BlockNr); } CurrBlock.Nr=-1; }
[ "fedidat@gmail.com" ]
fedidat@gmail.com
666349115350b072c7abde203f0328c262b0bbb7
e51562372a36b4729033bf19a4daf7ca7e462e30
/gym-101775H-1 WrongAnswer.cpp
76feffc2fcf65baa1a277001f276d1a96b06b48f
[]
no_license
sl1296/acm-code
72cd755e5c63dfdf9d0202cb14a183ccff3d9576
50f6b9ea865e33d9af5882acd0f2a05c9252c1f8
refs/heads/master
2020-08-22T11:56:17.002467
2019-11-09T11:08:25
2019-11-09T11:08:25
216,388,381
0
0
null
null
null
null
UTF-8
C++
false
false
2,656
cpp
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; char s[1000010]; int type[1000010],le[1000010],fdn; int main(){ int t,x,y; scanf("%d",&t); for(int z=1;z<=t;++z){ scanf("%s%d%d",s,&x,&y); int len=strlen(s); fdn=0; int cyy=0,cfy=0,nyy=0,nfy=0; for(int i=0;i<len;++i){ if(s[i]=='?'){ s[i]=0; ++nyy; ++nfy; }else if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'){ s[i]=1; cfy=max(cfy,nfy); nfy=0; ++nyy; }else{ s[i]=2; cyy=max(cyy,nyy); nyy=0; ++nfy; } } cyy=max(cyy,nyy); cfy=max(cfy,nfy); // for(int i=0;i<len;++i){ // printf("%d ",s[i]); // } // printf("\n"); // printf("cyy=%d cfy=%d\n",cyy,cfy); int yy=0,fy=0; for(int i=0;i<len;++i){ le[fdn]=1; while(i+1<len && s[i+1]==s[i])++i,++le[fdn]; if(s[i]==1)yy=max(yy,le[fdn]); else if(s[i]==2)fy=max(fy,le[fdn]); type[fdn++]=s[i]; } if(yy>=x || fy>=y){ printf("Case #%d: DISLIKE\n",z); continue; } if(fdn==1 && type[0]==0){ if(x>1 && y>1)printf("Case #%d: SURPRISE\n",z); else printf("Case #%d: DISLIKE\n",z); } for(int i=0;i<fdn;++i){ if(type[i]==0){ if(i==0||i==fdn-1)type[i]=-1; else if(type[i-1]==type[i+1])type[i]=-1; else if(le[i]>1)type[i]=-1; } } bool ok=true; int cyc=0,cfc=0; for(int i=0;i<fdn;++i){ if(type[i]==1){ cyc+=le[i]; cfc=0; if(cyc>=x)ok=false; }else if(type[i]==2){ cfc+=le[i]; cyc=0; if(cfc>=y)ok=false; }else if(type[i]==-1){ cyc=cfc=0; }else{ if(type[i-1]==1){ if(cyc+1<x)cyc=cfc=0; else cyc=0,cfc=1; }else{ if(cfc+1<x)cyc=cfc=0; else cyc=1,cfc=0; } } } if(cyy<x && cfy<y && ok==true){ printf("Case #%d: LIKE\n",z); }else if((cyy>=x || cfy>=y) && ok==false){ printf("Case #%d: DISLIKE\n",z); }else{ printf("Case #%d: SURPRISE\n",z); } } return 0; }
[ "guocl0729@163.com" ]
guocl0729@163.com
4a265f9a05f38fd96e724940b04656fac925122c
0ac501eed80a52a4a32785bd62de307b8280cdd7
/DirectZobEngine/CameraManagerWrapper.cpp
7de06d222f19d689763f9d3533c69537593cc789
[]
no_license
BlenderCN-Org/directZob
bbeb3d7741c403ea679cc2eff3cbbb5e3cdee343
df39ebd6f027686a02ee510becf3f0dcf1be0f82
refs/heads/master
2020-08-06T09:56:19.149262
2019-09-26T11:22:53
2019-09-26T11:22:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,527
cpp
#ifdef _WINDLL #include "CameraManagerWrapper.h" namespace CLI { CameraManagerWrapper::CameraManagerWrapper():ManagedObject(DirectZob::GetInstance()->GetCameraManager(), false) { } array<System::String^>^ CameraManagerWrapper::GetCameraList() { const std::vector<std::string> data = m_Instance->GetCameraList(); int l = data.size(); array<System::String ^>^ arr = gcnew array<System::String ^>(l); for (int i = 0; i < l; i++) { arr[i] = gcnew System::String(data.at(i).c_str()); } return arr; } System::String^ CameraManagerWrapper::GetCurrentCamera() { return gcnew System::String(m_Instance->GetCurrentCamera()->GetName().c_str()); } ManagedVector3^ CameraManagerWrapper::GetCurrentCameraPosition() { ManagedVector3^ v = gcnew CLI::ManagedVector3(m_Instance->GetCurrentCamera()->GetPosition()); return v; } ManagedVector3^ CameraManagerWrapper::GetCurrentCameraTarget() { ManagedVector3^ v = gcnew CLI::ManagedVector3(m_Instance->GetCurrentCamera()->GetTarget()); return v; } void CameraManagerWrapper::RotateAroundAxis(float x, float y) { m_Instance->GetCurrentCamera()->RotateAroundAxis(x, y); } void CameraManagerWrapper::Move(float x, float y) { m_Instance->GetCurrentCamera()->Move(x, y); } void CameraManagerWrapper::Zoom(float z) { m_Instance->GetCurrentCamera()->Zoom(z); } void CameraManagerWrapper::SetCurrentCameraPosition(ManagedVector3^ p) { Vector3 v = p->ToVector3(); m_Instance->GetCurrentCamera()->SetPosition(&v); } } #endif //_WINDLL
[ "zeralph@gmail.com" ]
zeralph@gmail.com
5f9f1baf0f7e4e37c72c73731a0faa0d65613d5a
65a42cb047358e191e93da92ad87ef39b3a95bb5
/solid.cpp
3ed37be5771410e19b3d42b80247ec5e1f56f5e1
[]
no_license
marcus-elia/prime-city
c58a1848b6b7b076aba7833eb5add87678b87fef
c2676beab573129b9e853124d984001ac1e38bda
refs/heads/master
2022-12-03T16:00:18.079229
2020-08-02T13:16:28
2020-08-02T13:16:28
266,095,410
0
1
null
2020-06-30T22:18:01
2020-05-22T11:36:59
C++
UTF-8
C++
false
false
3,493
cpp
#include "solid.h" Solid::Solid() { xWidth = 1; yWidth = 1; zWidth = 1; lineColor = {1,1,1,1}; linesDrawn = Normal; initializeCorners(); } Solid::Solid(Point inputCenter, RGBAcolor inputColor, double inputXWidth, double inputYWidth, double inputZWidth, RGBAcolor inputLineColor, linesDrawnEnum inputLinesDrawn) { center = inputCenter; color = inputColor; xWidth = inputXWidth; yWidth = inputYWidth; zWidth = inputZWidth; lineColor = inputLineColor; linesDrawn = inputLinesDrawn; initializeCorners(); location = center; lookingAt = {0,0,0}; speed = 0; velocity = {0,0,0}; ownerCenter = center; } Solid::Solid(Point inputCenter, RGBAcolor inputColor, double inputXWidth, double inputYWidth, double inputZWidth, RGBAcolor inputLineColor, Point inputLocation, Point inputLookingAt, double inputSpeed, Point inputVelocity, Point inputOwnerCenter, linesDrawnEnum inputLinesDrawn) : MovableComponent(inputLocation, inputLookingAt, inputSpeed, inputVelocity, inputOwnerCenter) { center = inputCenter; color = inputColor; xWidth = inputXWidth; yWidth = inputYWidth; zWidth = inputZWidth; lineColor = inputLineColor; linesDrawn = inputLinesDrawn; initializeCorners(); } void Solid::initializeCorners() { } Point Solid::getCenter() const { return center; } RGBAcolor Solid::getColor() const { return color; } std::vector<Point> Solid::getCorners() const { return corners; } double Solid::getXWidth() const { return xWidth; } double Solid::getYWidth() const { return yWidth; } double Solid::getZWidth() const { return zWidth; } RGBAcolor Solid::getLineColor() const { return lineColor; } void Solid::setCenter(Point inputCenter) { center = inputCenter; } void Solid::setColor(RGBAcolor inputColor) { color = inputColor; } void Solid::setCorners(std::vector<Point> inputCorners) { corners = inputCorners; } void Solid::setXWidth(double inputXWidth) { xWidth = inputXWidth; } void Solid::setYWidth(double inputYWidth) { yWidth = inputYWidth; } void Solid::setZWidth(double inputZWidth) { zWidth = inputZWidth; } void Solid::setLineColor(RGBAcolor inputLineColor) { lineColor = inputLineColor; } void Solid::move(double deltaX, double deltaY, double deltaZ) { movePoint(center, deltaX, deltaY, deltaZ); movePoint(location, deltaX, deltaY, deltaZ); movePoint(lookingAt, deltaX, deltaY, deltaZ); for(Point &p : corners) { movePoint(p, deltaX, deltaY, deltaZ); } } void Solid::moveSelfAndOwner(double deltaX, double deltaY, double deltaZ) { move(deltaX, deltaY, deltaZ); movePoint(ownerCenter, deltaX, deltaY, deltaZ); } void Solid::rotate(double thetaX, double thetaY, double thetaZ) { for(Point &p : corners) { rotatePointAroundPoint(p, center, thetaX, thetaY, thetaZ); } } void Solid::rotateAroundOwner(double thetaX, double thetaY, double thetaZ) { rotatePointAroundPoint(center, ownerCenter, thetaX, thetaY, thetaZ); rotatePointAroundPoint(location, ownerCenter, thetaX, thetaY, thetaZ); rotatePointAroundPoint(lookingAt, ownerCenter, thetaX, thetaY, thetaZ); for(Point &p : corners) { rotatePointAroundPoint(p, ownerCenter, thetaX, thetaY, thetaZ); } //rotate(thetaX, thetaY, thetaZ); } void drawPoint(const Point &p) { glVertex3f(p.x, p.y, p.z); }
[ "mselia@uvm.edu" ]
mselia@uvm.edu
06068dbc8c3f837cdca491b8db68250eff3d9f35
671108efbc06a6876ddf3d49622ec2af9d2d82cf
/build-backend/ScoutPatternParser.cc
487417040f302de75cde49c84551041d9e2bc2de
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
chrispbradley/scalasca
d545e2ef7c5b22963b8a554ecb5c8ba63f648f66
0f2cfe259ca452cd7e4c0968cfcd9ee3ade9c769
refs/heads/master
2022-02-07T07:51:09.725785
2022-02-04T03:54:56
2022-02-04T03:54:56
68,554,738
0
0
null
2016-09-19T00:16:28
2016-09-19T00:16:27
null
UTF-8
C++
false
false
79,295
cc
/* A Bison parser, made by GNU Bison 3.0.4. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "3.0.4" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 0 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Copy the first part of user declarations. */ #line 1 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:339 */ /**************************************************************************** ** SCALASCA http://www.scalasca.org/ ** ***************************************************************************** ** Copyright (c) 1998-2021 ** ** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre ** ** ** ** Copyright (c) 2009-2014 ** ** German Research School for Simulation Sciences GmbH, ** ** Laboratory for Parallel Programming ** ** ** ** This software may be modified and distributed under the terms of ** ** a BSD-style license. See the COPYING file in the package base ** ** directory for details. ** ****************************************************************************/ #include <config.h> #include <algorithm> #include <cassert> #include <cctype> #include <cstdio> #include <cstdlib> #include <functional> #include <map> #include <sstream> #include <string> #include <vector> #include "Helper.h" #include "IndentStream.h" #include "Pattern.h" using namespace std; #define YYSTYPE std::string #define YYDEBUG 1 /*--- Constants -----------------------------------------------------------*/ const char* copyright = "/****************************************************************************\n" "** SCALASCA http://www.scalasca.org/ **\n" "*****************************************************************************\n" "** Copyright (c) 1998-2021 **\n" "** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre **\n" "** **\n" "** Copyright (c) 2009-2014 **\n" "** German Research School for Simulation Sciences GmbH, **\n" "** Laboratory for Parallel Programming **\n" "** **\n" "** Copyright (c) 2019-2021 **\n" "** RWTH Aachen University, IT Center **\n" "** **\n" "** This software may be modified and distributed under the terms of **\n" "** a BSD-style license. See the COPYING file in the package base **\n" "** directory for details. **\n" "****************************************************************************/\n" "\n\n"; /*--- Global variables ----------------------------------------------------*/ extern FILE* yyin; long lineno = 1; long depth = 0; string inpFilename; string incFilename; int incLine; int codeLine; string prolog; string prefix("Patterns_gen"); map< string,Pattern* > id2pattern; // pattern id |-> pattern vector< Pattern* > pattern; // pattern list Pattern* current; // current pattern string callbackgroup; // current callback group /*--- Function prototypes -------------------------------------------------*/ int main(int argc, char** argv); void write_header(); void write_impl(); void write_html(); string uppercase(const string& str); string preprocessText(const string& input, int& lineNumber); void yyerror(const string& message); extern int yylex(); extern void include_file(const string& filename); #line 185 "ScoutPatternParser.cc" /* yacc.c:339 */ # ifndef YY_NULLPTR # if defined __cplusplus && 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* In a future release of Bison, this section will be replaced by #include "y.tab.h". */ #ifndef YY_YY_SCOUTPATTERNPARSER_HH_INCLUDED # define YY_YY_SCOUTPATTERNPARSER_HH_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { STRING = 258, TEXT = 259, CALLBACKS = 260, CLASS = 261, CLEANUP = 262, CONDITION = 263, DATA = 264, DESCR = 265, DOCNAME = 266, DIAGNOSIS = 267, HIDDEN = 268, INCLUDE = 269, INFO = 270, INIT = 271, MODE = 272, NAME = 273, NODOCS = 274, PARENT = 275, PATTERN = 276, PROLOG = 277, STATICINIT = 278, TYPE = 279, UNIT = 280 }; #endif /* Tokens. */ #define STRING 258 #define TEXT 259 #define CALLBACKS 260 #define CLASS 261 #define CLEANUP 262 #define CONDITION 263 #define DATA 264 #define DESCR 265 #define DOCNAME 266 #define DIAGNOSIS 267 #define HIDDEN 268 #define INCLUDE 269 #define INFO 270 #define INIT 271 #define MODE 272 #define NAME 273 #define NODOCS 274 #define PARENT 275 #define PATTERN 276 #define PROLOG 277 #define STATICINIT 278 #define TYPE 279 #define UNIT 280 /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif extern YYSTYPE yylval; int yyparse (void); #endif /* !YY_YY_SCOUTPATTERNPARSER_HH_INCLUDED */ /* Copy the second part of user declarations. */ #line 286 "ScoutPatternParser.cc" /* yacc.c:358 */ #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE # if (defined __GNUC__ \ && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C # define YY_ATTRIBUTE(Spec) __attribute__(Spec) # else # define YY_ATTRIBUTE(Spec) /* empty */ # endif #endif #ifndef YY_ATTRIBUTE_PURE # define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) #endif #ifndef YY_ATTRIBUTE_UNUSED # define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) #endif #if !defined _Noreturn \ && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112) # if defined _MSC_VER && 1200 <= _MSC_VER # define _Noreturn __declspec (noreturn) # else # define _Noreturn YY_ATTRIBUTE ((__noreturn__)) # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif #if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 15 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 117 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 34 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 37 /* YYNRULES -- Number of rules. */ #define YYNRULES 61 /* YYNSTATES -- Number of states. */ #define YYNSTATES 118 /* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned by yylex, with out-of-bounds checking. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 280 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex, without out-of-bounds checking. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 31, 2, 2, 2, 2, 2, 29, 30, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 26, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 27, 2, 28, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 32, 2, 33, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 129, 129, 133, 134, 138, 139, 140, 144, 151, 164, 163, 212, 213, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 238, 250, 262, 269, 292, 310, 317, 324, 336, 348, 360, 372, 389, 401, 413, 425, 437, 450, 449, 455, 454, 462, 463, 467, 477, 485, 484, 515, 523, 527 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 0 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "STRING", "TEXT", "CALLBACKS", "CLASS", "CLEANUP", "CONDITION", "DATA", "DESCR", "DOCNAME", "DIAGNOSIS", "HIDDEN", "INCLUDE", "INFO", "INIT", "MODE", "NAME", "NODOCS", "PARENT", "PATTERN", "PROLOG", "STATICINIT", "TYPE", "UNIT", "'='", "'['", "']'", "'('", "')'", "'\"'", "'{'", "'}'", "$accept", "File", "Body", "BodyItem", "Include", "Prolog", "Pattern", "$@1", "PatternDef", "DefItem", "Name", "Classname", "Docname", "Parent", "Type", "Hidden", "NoDocs", "Info", "Description", "Diagnosis", "Unit", "Mode", "Condition", "Init", "StaticInit", "Cleanup", "Data", "Callbacks", "$@2", "$@3", "CbList", "CbItem", "String", "CodeBlock", "$@4", "TextBlock", "Text", YY_NULLPTR }; #endif # ifdef YYPRINT /* YYTOKNUM[NUM] -- (External) token number corresponding to the (internal) symbol number NUM (which must be that of a token). */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 61, 91, 93, 40, 41, 34, 123, 125 }; # endif #define YYPACT_NINF -100 #define yypact_value_is_default(Yystate) \ (!!((Yystate) == (-100))) #define YYTABLE_NINF -1 #define yytable_value_is_error(Yytable_value) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int8 yypact[] = { -11, -23, -23, -18, 16, -11, -100, -100, -100, -100, 24, -100, -100, -100, -100, -100, -100, 9, 17, 40, -100, 18, -100, 1, 76, -100, -100, 19, 20, 23, 25, 26, 27, 28, 29, -100, 30, 31, 32, 33, -100, 34, 35, 36, 37, 13, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -23, 39, -23, -18, -23, -18, 38, -23, 38, -23, -18, -23, -23, -23, -18, -23, -23, -100, -100, 42, 47, -100, -100, -100, -100, 40, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -23, 2, 41, -16, -100, 43, -100, 51, -100, -100, -18, -23, -100, 11, -100 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 0, 0, 0, 0, 0, 2, 3, 5, 7, 6, 0, 8, 10, 57, 9, 1, 4, 0, 0, 0, 56, 0, 61, 0, 0, 60, 58, 51, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12, 0, 0, 33, 47, 44, 48, 0, 40, 34, 41, 39, 45, 43, 32, 35, 46, 36, 42, 49, 0, 0, 0, 0, 54, 0, 59, 0, 52, 53, 0, 0, 55, 0, 50 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int8 yypgoto[] = { -100, -100, -100, 45, -100, -100, -100, -100, -100, 52, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -24, -99, -1, -66, -100, 44, 8 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { -1, 4, 5, 6, 7, 8, 9, 18, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 105, 66, 106, 107, 108, 14, 19, 91, 23 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_uint8 yytable[] = { 11, 12, 87, 1, 89, 25, 25, 112, 10, 95, 2, 3, 111, 99, 13, 10, 15, 112, 27, 28, 29, 30, 31, 32, 33, 34, 35, 17, 36, 37, 38, 39, 40, 41, 26, 109, 42, 43, 44, 117, 20, 82, 10, 21, 22, 24, 67, 115, 65, 68, 16, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 84, 85, 86, 110, 88, 113, 90, 92, 102, 94, 103, 96, 97, 98, 114, 100, 101, 27, 28, 29, 30, 31, 32, 33, 34, 35, 116, 36, 37, 38, 39, 40, 41, 83, 104, 42, 43, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93 }; static const yytype_int8 yycheck[] = { 1, 2, 68, 14, 70, 4, 4, 106, 31, 75, 21, 22, 28, 79, 32, 31, 0, 116, 5, 6, 7, 8, 9, 10, 11, 12, 13, 3, 15, 16, 17, 18, 19, 20, 33, 33, 23, 24, 25, 28, 31, 28, 31, 26, 4, 27, 26, 113, 29, 26, 5, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 65, 26, 67, 26, 69, 26, 32, 72, 30, 74, 27, 76, 77, 78, 27, 80, 81, 5, 6, 7, 8, 9, 10, 11, 12, 13, 114, 15, 16, 17, 18, 19, 20, 45, 90, 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 73 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 14, 21, 22, 35, 36, 37, 38, 39, 40, 31, 66, 66, 32, 67, 0, 37, 3, 41, 68, 31, 26, 4, 70, 27, 4, 33, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 23, 24, 25, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 29, 63, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 28, 43, 66, 26, 66, 67, 66, 67, 32, 69, 66, 69, 66, 67, 66, 66, 66, 67, 66, 66, 30, 27, 70, 62, 64, 65, 66, 33, 26, 28, 65, 26, 27, 67, 64, 28 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 34, 35, 36, 36, 37, 37, 37, 38, 39, 41, 40, 42, 42, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 62, 61, 63, 61, 64, 64, 65, 66, 68, 67, 69, 70, 70 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 1, 2, 1, 1, 1, 2, 2, 0, 7, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 9, 0, 6, 2, 1, 3, 3, 0, 4, 3, 2, 1 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* This macro is provided for backward compatibility. */ #ifndef YY_LOCATION_PRINT # define YY_LOCATION_PRINT(File, Loc) ((void) 0) #endif # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*----------------------------------------. | Print this symbol's value on YYOUTPUT. | `----------------------------------------*/ static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) { FILE *yyo = yyoutput; YYUSE (yyo); if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # endif YYUSE (yytype); } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) { YYFPRINTF (yyoutput, "%s %s (", yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); yy_symbol_value_print (yyoutput, yytype, yyvaluep); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule) { unsigned long int yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yystos[yyssp[yyi + 1 - yynrhs]], &(yyvsp[(yyi + 1) - (yynrhs)]) ); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, Rule); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ static YYSIZE_T yystrlen (const char *yystr) { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); YYSIZE_T yysize = yysize0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { YYSIZE_T yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) { YYUSE (yyvaluep); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YYUSE (yytype); YY_IGNORE_MAYBE_UNINITIALIZED_END } /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /*----------. | yyparse. | `----------*/ int yyparse (void) { int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 8: #line 145 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { include_file((yyvsp[0])); } #line 1447 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 9: #line 152 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!prolog.empty()) { prolog += "\n\n"; } prolog += (yyvsp[0]); } #line 1460 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 10: #line 164 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (id2pattern.find((yyvsp[0])) != id2pattern.end()) { yyerror("Pattern \"" + (yyvsp[0]) + "\" already defined!"); } current = new Pattern((yyvsp[0])); pattern.push_back(current); id2pattern.insert(make_pair((yyvsp[0]), current)); } #line 1475 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 11: #line 175 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { bool error = true; string msg = "Incomplete pattern definition!\n"; switch (current->is_valid()) { case DEF_NAME: msg += "Missing NAME definition."; break; case DEF_CLASS: msg += "Missing CLASS definition."; break; case DEF_INFO: msg += "Missing INFO definition."; break; case DEF_UNIT: msg += "Missing UNIT definition."; break; case DEF_MODE: msg += "Missing MODE definition."; break; default: error = false; break; } if (error) { yyerror(msg); } } #line 1514 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 32: #line 239 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->get_name().empty()) { yyerror("Only one NAME definition allowed!"); } current->set_name((yyvsp[0])); } #line 1527 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 33: #line 251 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->get_classname().empty()) { yyerror("Only one CLASS definition allowed!"); } current->set_classname((yyvsp[0])); } #line 1540 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 34: #line 263 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { current->set_docname((yyvsp[0])); } #line 1548 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 35: #line 270 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (current->get_parent() != "NONE") { yyerror("Only one PARENT definition allowed!"); } map< string, Pattern* >::iterator it = id2pattern.find((yyvsp[0])); if (it == id2pattern.end()) { yyerror("Unknown pattern \"" + (yyvsp[0]) + "\"!"); } if (it->second == current) { yyerror("A pattern cannot be its own parent!"); } current->set_parent((yyvsp[0])); } #line 1572 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 36: #line 293 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if ( ((yyvsp[0]) != "MPI") && ((yyvsp[0]) != "MPIDEP") && ((yyvsp[0]) != "MPI_RMA") && ((yyvsp[0]) != "OMP") && ((yyvsp[0]) != "OMPDEP") && ((yyvsp[0]) != "PTHREAD") && ((yyvsp[0]) != "Generic")) { yyerror("Unknown pattern type \"" + (yyvsp[0]) + "\""); } current->set_type((yyvsp[0])); } #line 1591 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 37: #line 311 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { current->set_hidden(); } #line 1599 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 38: #line 318 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { current->set_nodocs(); } #line 1607 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 39: #line 325 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->get_info().empty()) { yyerror("Only one INFO definition allowed!"); } current->set_info((yyvsp[0])); } #line 1620 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 40: #line 337 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->get_descr().empty()) { yyerror("Only one DESCR definition allowed!"); } current->set_descr((yyvsp[0])); } #line 1633 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 41: #line 349 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->get_diagnosis().empty()) { yyerror("Only one DIAGNOSIS definition allowed!"); } current->set_diagnosis((yyvsp[0])); } #line 1646 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 42: #line 361 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->get_unit().empty()) { yyerror("Only one UNIT definition allowed!"); } current->set_unit((yyvsp[0])); } #line 1659 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 43: #line 373 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->get_mode().empty()) { yyerror("Only one MODE definition allowed!"); } if ( ((yyvsp[0]) != "inclusive") && ((yyvsp[0]) != "exclusive")) { yyerror("Unknown pattern mode \"" + (yyvsp[0]) + "\""); } current->set_mode((yyvsp[0])); } #line 1677 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 44: #line 390 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->get_condition().empty()) { yyerror("Only one CONDITION definition allowed!"); } current->set_condition((yyvsp[0])); } #line 1690 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 45: #line 402 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->get_init().empty()) { yyerror("Only one INIT definition allowed!"); } current->set_init((yyvsp[0])); } #line 1703 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 46: #line 414 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->get_staticinit().empty()) { yyerror("Only one STATICINIT definition allowed!"); } current->set_staticinit((yyvsp[0])); } #line 1716 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 47: #line 426 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->get_cleanup().empty()) { yyerror("Only one CLEANUP definition allowed!"); } current->set_cleanup((yyvsp[0])); } #line 1729 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 48: #line 438 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->get_data().empty()) { yyerror("Only one DATA definition allowed!"); } current->set_data((yyvsp[0])); } #line 1742 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 49: #line 450 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { callbackgroup = (yyvsp[-1]); } #line 1750 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 51: #line 455 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { callbackgroup = ""; } #line 1758 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 55: #line 468 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { if (!current->add_callback(callbackgroup, (yyvsp[-2]), (yyvsp[0]))) { yyerror("Callback \"" + (yyvsp[-2]) + "\" already defined!"); } } #line 1769 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 56: #line 478 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { (yyval) = (yyvsp[-1]); } #line 1777 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 57: #line 485 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { codeLine = lineno; } #line 1785 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 58: #line 489 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { string codeText = preprocessText((yyvsp[-1]), codeLine); // Account for the extra blank line added after the // line directive codeLine--; if (codeLine <= 0) { yyerror("Code block in first line unsupported!"); } stringstream lineDirective; lineDirective << "#line " << codeLine << " \"" << (incFilename.empty() ? inpFilename : incFilename) << "\"\n" << '\n'; (yyval) = lineDirective.str() + codeText; } #line 1813 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 59: #line 516 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { int dummy = 0; (yyval) = preprocessText((yyvsp[-1]), dummy); } #line 1822 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 60: #line 524 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { (yyval) = (yyvsp[-1]) + (yyvsp[0]); } #line 1830 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; case 61: #line 528 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1646 */ { (yyval) = (yyvsp[0]); } #line 1838 "ScoutPatternParser.cc" /* yacc.c:1646 */ break; #line 1842 "ScoutPatternParser.cc" /* yacc.c:1646 */ default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; } #line 534 "../../build-backend/../src/scout/generator/ScoutPatternParser.yy" /* yacc.c:1906 */ // -------------------------------------------------------------------------- // // gen_pattern <description file> // // -------------------------------------------------------------------------- int main(int argc, char** argv) { /* Check command line arguments */ if (argc != 2) { fprintf(stderr, "Usage: gen_patterns <description file>\n"); exit(EXIT_FAILURE); } /* Store input filename */ inpFilename = argv[1]; /* Open input file */ yyin = fopen(inpFilename.c_str(), "r"); if (!yyin) { fprintf(stderr, "Could not open file \"%s\".\n", inpFilename.c_str()); exit(EXIT_FAILURE); } /* Parse input file */ yyparse(); /* Close input file */ fclose(yyin); /* Write output */ write_header(); write_impl(); write_html(); /* Clean up */ vector< Pattern* >::iterator it = pattern.begin(); while (it != pattern.end()) { delete *it; ++it; } return EXIT_SUCCESS; } void write_header() { /* Open header file */ string filename = prefix + ".h"; FILE* fp = fopen(filename.c_str(), "w"); if (!fp) { fprintf(stderr, "Could not open output file \"%s\".\n", filename.c_str()); exit(EXIT_FAILURE); } /* Temporary strings */ string prefix_upper = uppercase(prefix); /* Write copyright notice */ fprintf(fp, "%s", copyright); /* Open include guard */ fprintf(fp, "#ifndef SCOUT_%s_H\n", prefix_upper.c_str()); fprintf(fp, "#define SCOUT_%s_H\n", prefix_upper.c_str()); fprintf(fp, "\n\n"); /* Open namespace */ fprintf(fp, "namespace scout\n" "{\n"); /* Determine format string for pattern constants */ string::size_type length = 0; vector< Pattern* >::const_iterator it = pattern.begin(); while (it != pattern.end()) { length = max(length, (*it)->get_id().length()); ++it; } ostringstream fmt; fmt << "const long PAT_%-" << length << "s = %d;\n"; /* Write pattern constants */ int num = -1; fprintf(fp, "%s\n\n", separatorComment(0, CPP_STYLE, "Constants").c_str()); fprintf(fp, fmt.str().c_str(), "NONE", num++); it = pattern.begin(); while (it != pattern.end()) { fprintf(fp, fmt.str().c_str(), (*it)->get_id().c_str(), num++); ++it; } fprintf(fp, "\n\n"); /* Write forward declarations */ fprintf(fp, "%s\n" "\n" "class AnalyzeTask;\n" "\n\n", separatorComment(0, CPP_STYLE, "Forward declarations").c_str()); /* Write function prototypes */ fprintf(fp, "%s\n" "\n" "void\n" "create_patterns(AnalyzeTask* analyzer);\n", separatorComment(0, CPP_STYLE, "Pattern registration").c_str()); /* Close namespace */ fprintf(fp, "} // namespace scout\n" "\n\n"); /* Close include guard */ fprintf(fp, "#endif // !SCOUT_%s_H\n", prefix_upper.c_str()); /* Close file */ fclose(fp); } void write_impl() { /* Open implementation file */ string filename = prefix + ".cpp"; FILE* fp = fopen(filename.c_str(), "w"); if (!fp) { fprintf(stderr, "Could not open output file \"%s\".\n", filename.c_str()); exit(EXIT_FAILURE); } /* Write copyright notice */ int indent = 0; IndentStream(fp, indent) << copyright; /* Write common includes */ IndentStream(fp, indent) << "#include <config.h>\n" << '\n' << "#include \"Patterns_gen.h\"\n" << '\n' << "#include <inttypes.h>\n" << '\n' << "#include <cassert>\n" << '\n' << "#include <pearl/CallbackManager.h>\n" << "#include <pearl/Callpath.h>\n" << "#include <pearl/GlobalDefs.h>\n" << '\n' << "#include \"AnalyzeTask.h\"\n" << "#include \"CbData.h\"\n" << "#include \"MpiPattern.h\"\n" << '\n' << "#ifdef _OPENMP\n"; indent++; IndentStream(fp, indent) << "#include \"OmpPattern.h\"\n" << "#include \"PthreadPattern.h\"\n"; indent--; IndentStream(fp, indent) << "#endif // _OPENMP\n" << '\n'; /* Write "using" directives */ IndentStream(fp, indent) << "using namespace std;\n" << "using namespace pearl;\n" << "using namespace scout;\n" << '\n' << '\n'; /* Write prolog */ IndentStream(fp, indent) << prolog << '\n' << '\n' << '\n'; /* Write class implementation */ vector< Pattern* >::const_iterator it = pattern.begin(); while (it != pattern.end()) { (*it)->write_impl(fp, indent); ++it; } /* Write function implementation */ IndentStream(fp, indent) << separatorComment(indent, CPP_STYLE, "Pattern registration") << '\n' << '\n' << "void\n" << "scout::create_patterns(AnalyzeTask* analyzer)\n" << "{\n"; indent++; it = pattern.begin(); while (it != pattern.end()) { if ((*it)->skip_impl()) { ++it; continue; } const struct guard { const char *type, *begin, *end; } guards[] = { { "MPI", "#if defined(_MPI)\n", "#endif // _MPI\n" }, { "MPIDEP", "#if defined(_MPI)\n", "#endif // _MPI\n" }, { "MPI_RMA", "#if defined(_MPI) && defined(HAS_MPI2_1SIDED)\n", "#endif // _MPI && HAS_MPI2_1SIDED\n" }, { "MPI_RMADEP", "#if defined(_MPI) && defined(HAS_MPI2_1SIDED)\n", "#endif // _MPI && HAS_MPI2_1SIDED\n" }, { "OMP", "#if defined(_OPENMP)\n", "#endif // _OPENMP\n" }, { "OMPDEP", "#if defined(_OPENMP)\n", "#endif // _OPENMP\n" }, { "PTHREAD", "#if defined(_OPENMP)\n", "#endif // _OPENMP\n" }, { "ARMCI", "#if defined(HAS_ARMCI)\n", "#endif // HAS_ARMCI\n" }, { "ARMCIDEP", "#if defined(HAS_ARMCI)\n", "#endif // HAS_ARMCI\n" }, { 0, 0, 0 } }; const struct guard* g; for (g = guards; g->type && ((*it)->get_type() != g->type); ++g) { } if (g->begin) { IndentStream(fp, indent) << g->begin; indent++; } const bool isConditional = !(*it)->get_condition().empty(); if (isConditional) { IndentStream(fp, indent) << "if (" << (*it)->get_condition() << ")\n" << "{\n"; indent++; } IndentStream(fp, indent) << "analyzer->addPattern(new " << (*it)->get_classname() << "());\n"; if (isConditional) { indent--; IndentStream(fp, indent) << "}\n"; } if (g->end) { indent--; IndentStream(fp, indent) << g->end; } ++it; } indent--; IndentStream(fp, indent) << "}\n"; /* Close file */ fclose(fp); } void write_html() { /* Open documentation file */ string filename = prefix + ".html"; FILE* fp = fopen(filename.c_str(), "w"); if (!fp) { fprintf(stderr, "Could not open output file \"%s\".\n", filename.c_str()); exit(EXIT_FAILURE); } /* Write file header */ fprintf(fp, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" "<html>\n" "<head>\n" "<title>Performance properties</title>\n" "</head>\n" "<body>\n"); /* Write page header */ fprintf(fp, "<h2>Performance properties</h2>\n"); /* Write class documentation */ bool isFirst = true; vector< Pattern* >::const_iterator it = pattern.begin(); while (it != pattern.end()) { (*it)->write_html(fp, isFirst); isFirst = false; ++it; } /* Close file */ fclose(fp); } void yyerror(const string& message) { if (!incFilename.empty()) { fprintf(stderr, "In included file \"%s\":\n ", incFilename.c_str()); } fprintf(stderr, "Line %ld: %s\n", lineno, message.c_str()); exit(EXIT_FAILURE); } struct fo_toupper : public std::unary_function< int, int > { int operator()(int x) const { return std::toupper(x); } }; string uppercase(const string& str) { string result(str); transform(str.begin(), str.end(), result.begin(), fo_toupper()); return result; } string preprocessText(const string& input, int& lineNumber) { const string::size_type inputLength = input.length(); string result; string::size_type baseIndent = string::npos; string::size_type beginPos = 0; do { // Determine character index right after end of line string::size_type endPos = input.find('\n', beginPos); if (endPos == string::npos) { endPos = inputLength; } else { endPos++; } const string::size_type lineLength = endPos - beginPos; string line(input, beginPos, lineLength); // Try to determine base indentation (implicit assumption: first // non-blank line of block is properly indented) if (baseIndent == string::npos) { baseIndent = line.find_first_not_of(" \t\n\r\f\v"); // Drop leading blank lines; requires adjustment of line number // for '#line' directive if (baseIndent == string::npos) { lineNumber++; beginPos += lineLength; continue; } } // Strip off leading indentation, keeping lines with less spaces intact string::size_type textIndent = line.find_first_not_of(" \t"); line.erase(0, min(textIndent, baseIndent)); result += line; beginPos += lineLength; } while (beginPos < inputLength); // Trim trailing whitespaces beginPos = result.find_last_not_of(" \t\n\r\f\v"); if (beginPos != string::npos) { beginPos++; if (beginPos < result.length()) { result.erase(beginPos); } } return result; }
[ "c.bradley@auckland.ac.nz" ]
c.bradley@auckland.ac.nz
90e3418b90699c493d757740f4f9b812b2f7688b
8845ca9f50c7e92859cf2328267e311889983bb7
/test/mesh_output_test.cpp
144c56ed8c16c884298c3d04d588d5273d38d792
[ "MIT" ]
permissive
jjh13/sisl
16c9cd05b67a5d3b9724e615923787c222bc79ad
e4c276e0661729e9f4cfff4828f1ed31401601cd
refs/heads/master
2021-01-22T23:53:45.750948
2017-11-24T22:54:04
2017-11-24T22:54:04
108,057,152
2
0
null
null
null
null
UTF-8
C++
false
false
3,934
cpp
#define CATCH_CONFIG_MAIN #include <catch/catch.hpp> #include <sisl/sisl.hpp> #include <sisl/utility/ply_mesh.hpp> #include <sisl/utility/iso_surface.hpp> #include <sisl/test/function/marschner_lobb.hpp> #include <sisl/test/function/test_window.hpp> #include <iostream> using namespace sisl; using namespace sisl::utility; /** \breif Test to see if we can output a simple cube model. */ TEST_CASE("Mesh output test", "Mesh output test"){ ply_mesh ply; ply.add_triangle(sisl::vertex3(1,1,1,1,1,1), sisl::vertex3(1,1,-1,1,1,-1), sisl::vertex3(1,-1,-1,1,-1,-1)); ply.add_triangle(sisl::vertex3(1,1,1,1,1,1), sisl::vertex3(1,-1,1,1,-1,1), sisl::vertex3(1,-1,-1,1,-1,-1)); ply.add_triangle(sisl::vertex3(1,1,1,1,1,1), sisl::vertex3(-1,1,1,-1,1,1), sisl::vertex3(1,-1,1,1,-1,1)); ply.add_triangle( sisl::vertex3(-1,-1,1,-1,-1,1), sisl::vertex3(-1,1,1,-1,1,1), sisl::vertex3(1,-1,1,1,-1,1)); ply.add_triangle(sisl::vertex3(1,1,1,1,1,1), sisl::vertex3(1,1,-1,1,1,-1), sisl::vertex3(-1,1,1,-1,1,1)); ply.add_triangle(sisl::vertex3(-1,1,-1,-1,1,-1), sisl::vertex3(-1,1,1,-1,1,1), sisl::vertex3(1,1,-1,1,1,-1)); ply.add_triangle(sisl::vertex3(-1,1,1,1,1,1), sisl::vertex3(-1,1,-1,1,1,-1), sisl::vertex3(-1,-1,-1,1,-1,-1)); ply.add_triangle(sisl::vertex3(-1,1,1,1,1,1), sisl::vertex3(-1,-1,1,1,-1,1), sisl::vertex3(-1,-1,-1,1,-1,-1)); ply.add_triangle(sisl::vertex3(1,1,-1,1,1,1), sisl::vertex3(-1,1,-1,-1,1,1), sisl::vertex3(1,-1,-1,1,-1,1)); ply.add_triangle( sisl::vertex3(-1,-1,-1,-1,-1,1), sisl::vertex3(-1,1,-1,-1,1,1), sisl::vertex3(1,-1,-1,1,-1,1)); ply.add_triangle(sisl::vertex3(1,-1,1,1,1,1), sisl::vertex3(1,-1,-1,1,1,-1), sisl::vertex3(-1,-1,1,-1,1,1)); ply.add_triangle(sisl::vertex3(-1,-1,-1,-1,1,-1), sisl::vertex3(-1,-1,1,-1,1,1), sisl::vertex3(1,-1,-1,1,1,-1)); ply.remove_duplicate_vertices(); // Ensure that we have no duplicate verts and faces REQUIRE(ply.count_vertices() == 8); REQUIRE(ply.count_faces() == 12); if(!ply.write("ply_tests_1.ply")) { FAIL("Couldn't write the PLY file!\n"); } } /** \breif Test to see if we can march the marschner lobb function. */ TEST_CASE("marschner_lobb_march", "March the marschner_lobb test function") { sisl::test::marschner_lobb ml(0.25, 6); sisl::utility::isosurface mc; vector origin(3), extent(3); // Setup the volume over which MC will run origin << -1,-1,-1; extent << 2,2,2; try { mc.march_function( &ml, 0.5, 0.05, origin, extent ); }catch(char const* c){ std::cout << c << std::endl; FAIL("Couldn't March ml function."); } REQUIRE(mc.write_surface("ml_marched.ply")); } /** \breif Test to see if we can march the test window function. */ TEST_CASE("hamm_march", "March the windowed test function") { sisl::test::test_window hamm(0.25, 2, 6); sisl::utility::isosurface mc; vector origin(3), extent(3); // Setup the volume over which MC will run origin << -1,-1,-1; extent << 2,2,2; try { mc.march_function( &hamm, 0.4, 0.01, origin, extent ); }catch(char const* c){ std::cout << c << std::endl; FAIL("Couldn't March?"); } REQUIRE(mc.write_surface("hamm_marched.ply")); }
[ "joshua.horacsek@ucalgary.ca" ]
joshua.horacsek@ucalgary.ca
8472d2750a5777f0146f1404e94c95dfffb6b310
39f6b10471a35f0d491f56d52b40fafe8c46a6c8
/main.cpp
ee7c4a7ed1abb96dd8530405ef87f5f3312f62c2
[ "MIT" ]
permissive
patxitron/BattleyeRconToolLinux
62161cc39cb5c0efd72ee1dbd080a9438994bb6f
95d88ab1d1a340cd412611756b95bbf3fcefe8bf
refs/heads/master
2020-03-26T07:59:00.218247
2015-03-05T15:28:44
2015-03-05T15:28:44
29,855,930
3
0
null
null
null
null
UTF-8
C++
false
false
1,321
cpp
/** * @file main.cpp * * * @date 24/11/2014 * @uthor patxi */ #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <boost/asio.hpp> #include "a3s.h" using std::cout; using std::cin; using std::endl; using std::string; using std::getline; int main(int argc, char* argv[]) { string host; uint16_t port = 0; string passwd; if(argc > 1) { host = string(argv[1]); if(argc > 2) { port = static_cast<uint16_t>(strtoul(argv[2], nullptr, 10)); } } while(host.empty()) { cout << "Please enter the name or IP addres of the server:" << endl; getline(cin, host); } while(port == 0) { cout << "Please enter the port of the server:" << endl; string p; getline(cin, p); port = static_cast<uint16_t>(strtoul(p.c_str(), nullptr, 10)); } while(passwd.empty()) { cout << "Please enter the password:" << endl; getline(cin, passwd); } boost::asio::io_service io_service; patxi::a3s server( io_service ,port ,host ,[](char const* data, std::size_t length) { string msg(data, length); cout << msg << endl; } ,[&server](bool logged) { if(logged) { cout << "Successfully logged in." << endl; server.consoleInput(); } else { cout << "Failed to log in" << endl; } } ); server.login(passwd); io_service.run(); return 0; }
[ "fjlazur@fensomsystem.com" ]
fjlazur@fensomsystem.com
698d904a9b001b0dccece33cc9de93b74d29f968
edfa90a4ab7af5556a75b13f920a37541351161f
/ChartWidget1.cpp
0476d173baacacd2c8c1be2aeaf1c38ec900c465
[]
no_license
mejwaller/numanal
031146dd1b66b5491275827ebb90909a9da5a1de
7a03610b16230e995b7424482cd167ceaf14b0f7
refs/heads/master
2020-04-06T03:54:02.438307
2014-10-16T21:20:30
2014-10-16T21:20:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,041
cpp
#include "ChartWidget1.hpp" #include <math.h> #include <qpainter.h> #include <qpixmap.h> #include <iostream> using namespace std; ChartWidget1::ChartWidget1(QWidget *parent, const char *name, WFlags f) :QWidget(parent,name,f),buffer(0),maxx(100.0),minx(0.0),maxy(100.0),miny(0.0),numxticks(1),numyticks(1),scale(100000.0) { setBackgroundMode( QWidget::PaletteBase ); } ChartWidget1::~ChartWidget1() { if(buffer) { delete buffer; } } void ChartWidget1::paintEvent(QPaintEvent *) { if (buffer && width() == buffer->width() && height() == buffer->height()) { bitBlt(this,0,0,buffer); } else { draw(); } } void ChartWidget1::draw() { if(buffer) { delete buffer; } buffer = new QPixmap(width(),height()); buffer->fill(); QPainter bufferpaint(buffer); draw(&bufferpaint); bitBlt(this,0,0,buffer); } void ChartWidget1::draw(QPainter *paint) { QRect v; //lets leave 10% margin either side... float scalefac = 0.8; paint->save(); //we want to draw so that the graph origin is 10% in eitehr side, //so we want coords to go from minx - 10% of width (10% of width = 0.1*maxx-minx) to maxx + 10% of width //so window width = maxx-minx*1.2,height = maxy-miny*1.2 //and similarly for height (mutliplying by scale - but I assume paint->scale can do that?: paint->setWindow(scale*(minx-0.1*(maxx-minx)),scale*(miny-0.1*(maxy-miny)),scale*((maxx-minx)*1.2),scale*((maxy-miny)*1.2)); QWMatrix mat1; /*paint->*/mat1.scale(1,-1); /*paint->*/mat1.translate(0,-scale*(maxy-miny)); paint->setWorldMatrix(mat1); //Get the viewport and set it up /*v = paint->viewport(); int d = QMIN( v.width(), v.height() ); paint->setViewport( v.left() + (v.width()-d)/2, v.top() + (v.height()-d)/2, d, d ); v = paint->viewport(); */ paint->drawLine(scale*minx,scale*miny,scale*minx,scale*maxy);//y axis paint->drawLine(scale*minx,scale*miny,scale*maxx,scale*miny);//xaxis //now draw ticks: for(unsigned int i = 0; i< numyticks;i++) { paint->drawLine(scale*minx,(i+1)*scale*(maxy-miny)/numyticks,-scale*(maxx-minx)*0.01,(i+1)*scale*(maxy-miny)/numyticks); } for(unsigned int j = 0; j<numxticks;j++) { paint->drawLine((j+1)*scale*(maxx-minx)/numxticks,scale*miny,(j+1)*scale*(maxx-minx)/numxticks,-scale*(maxy-miny)*0.01); } drawSeries(paint); //paint->drawText(minx,miny,"(minx,miny)"); //paint->drawText(maxx,maxy,"(maxx,maxy)"); paint->restore(); } void ChartWidget1::addPoints(const vector<float>& x, const vector<float>& y, const string& name) { Plottable PointPlot(x,y,name); series.push_back(PointPlot); } void ChartWidget1::addLine(const vector<float>& x, const vector<float>& y, const string& name) { Plottable LinePlot(x,y,name,true); series.push_back(LinePlot); } void ChartWidget1::drawSeries(QPainter *paint) { vector<float> x,y; if(!series.empty()) { paint->setPen(QPen(black,0)); for(int i = 0; i<series.size(); i++) { x = series[i].xData(); y = series[i].yData(); if(series[i].lineSeries()) { for(unsigned int j = 0; j < x.size()-1; j++) { paint->drawLine(x[j]*scale,y[j]*scale,x[j+1]*scale,y[j+1]*scale); } } else { for(unsigned int j = 0; j < x.size(); j++) { //paint->drawPoint(x[j]*scale,y[j]*scale); //paint->drawEllipse(x[j]*scale,y[j]*scale,scale/100,scale/100); //paint->setPen(QPen(red,50)); paint->drawEllipse(x[j]*scale-(scale/100.0)/2.0,y[j]*scale-(scale/100.0)/2.0,scale/100,scale/100); } } } } }
[ "martin@debian.polytope.org" ]
martin@debian.polytope.org
c760d8e8230470a0442cfe36494840ec8df69eaa
a24aa4ff4b1bc10d99e08dae1c15ef52a1c4c539
/Nov.11前版本/tftest_ws/src/point_cloud_calc/src/main.cpp
7c9b7563bb91740c6fac1444abb6626395e71a6c
[]
no_license
wuchenxi1996/TunnelProject
413c0e362aa9609baf536a316c2f0cdd15cbe089
ab9c33a2db22786cd8a600c1388ceeac0f27d9b0
refs/heads/main
2023-02-01T17:44:12.846800
2020-12-15T08:13:55
2020-12-15T08:13:55
314,565,319
0
0
null
null
null
null
UTF-8
C++
false
false
1,215
cpp
#include <stdlib.h> #include <ros/ros.h> #include "calc_header.h" #include <math.h> #include <malloc.h> #include <boost/thread/thread.hpp> #include <message_filters/subscriber.h> #include <message_filters/time_synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> float x = 0.0; float y = 0.0; float z = 0.0; using namespace message_filters; static volatile int keepRunning = 1; void sig_handler(int sig) { if (sig == SIGINT) { keepRunning = 0; } } int main(int argc, char** argv) { ros::init(argc, argv, "PointCloudConvert"); ros::NodeHandle node; tf::StampedTransform tf; Convert* convertObject = new Convert(); //node.getParam("time", convertObject->rotation_time) //signal(SIGINT, sig_handler); message_filters::Subscriber<sensor_msgs::LaserScan> scan_(node,"/scan",100); message_filters::Subscriber<sensor_msgs::Imu> imu_sub_(node,"/ekf",100); typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::LaserScan, sensor_msgs::Imu> syncPolicy; message_filters::Synchronizer<syncPolicy> sync(syncPolicy(20), scan_, imu_sub_); sync.registerCallback(boost::bind(&callback, _1, _2,convertObject)); ros::spin(); //convertObject->finish(); return 0; }
[ "wuchx96@outlook.com" ]
wuchx96@outlook.com
7ea66d3f75141c048e78ff3285d0700f18d69546
48b2075725ff4a8036a2b4a25b9e70769aa559e0
/eval_ws/install/cf_messages/include/cf_messages/srv/detail/land__type_support.cpp
cb071b1de65349cbe1ee471462ebc39cf546a9cc
[]
no_license
ruimscarvalho98/QoSTesting
c47c30d8f39becce57889ed874a5429d9ff111bb
0a24106fdb3e9372a2eb216d33e0fa97f77e8de7
refs/heads/main
2023-05-09T17:42:18.727357
2021-06-04T16:57:08
2021-06-04T16:57:08
373,885,652
0
0
null
null
null
null
UTF-8
C++
false
false
11,683
cpp
// generated from rosidl_typesupport_introspection_cpp/resource/idl__type_support.cpp.em // with input from cf_messages:srv/Land.idl // generated code does not contain a copyright notice #include "array" #include "cstddef" #include "string" #include "vector" #include "rosidl_runtime_c/message_type_support_struct.h" #include "rosidl_typesupport_cpp/message_type_support.hpp" #include "rosidl_typesupport_interface/macros.h" #include "cf_messages/srv/detail/land__struct.hpp" #include "rosidl_typesupport_introspection_cpp/field_types.hpp" #include "rosidl_typesupport_introspection_cpp/identifier.hpp" #include "rosidl_typesupport_introspection_cpp/message_introspection.hpp" #include "rosidl_typesupport_introspection_cpp/message_type_support_decl.hpp" #include "rosidl_typesupport_introspection_cpp/visibility_control.h" namespace cf_messages { namespace srv { namespace rosidl_typesupport_introspection_cpp { void Land_Request_init_function( void * message_memory, rosidl_runtime_cpp::MessageInitialization _init) { new (message_memory) cf_messages::srv::Land_Request(_init); } void Land_Request_fini_function(void * message_memory) { auto typed_message = static_cast<cf_messages::srv::Land_Request *>(message_memory); typed_message->~Land_Request(); } static const ::rosidl_typesupport_introspection_cpp::MessageMember Land_Request_message_member_array[2] = { { "height", // name ::rosidl_typesupport_introspection_cpp::ROS_TYPE_FLOAT, // type 0, // upper bound of string nullptr, // members of sub message false, // is array 0, // array size false, // is upper bound offsetof(cf_messages::srv::Land_Request, height), // bytes offset in struct nullptr, // default value nullptr, // size() function pointer nullptr, // get_const(index) function pointer nullptr, // get(index) function pointer nullptr // resize(index) function pointer }, { "duration", // name ::rosidl_typesupport_introspection_cpp::ROS_TYPE_FLOAT, // type 0, // upper bound of string nullptr, // members of sub message false, // is array 0, // array size false, // is upper bound offsetof(cf_messages::srv::Land_Request, duration), // bytes offset in struct nullptr, // default value nullptr, // size() function pointer nullptr, // get_const(index) function pointer nullptr, // get(index) function pointer nullptr // resize(index) function pointer } }; static const ::rosidl_typesupport_introspection_cpp::MessageMembers Land_Request_message_members = { "cf_messages::srv", // message namespace "Land_Request", // message name 2, // number of fields sizeof(cf_messages::srv::Land_Request), Land_Request_message_member_array, // message members Land_Request_init_function, // function to initialize message memory (memory has to be allocated) Land_Request_fini_function // function to terminate message instance (will not free memory) }; static const rosidl_message_type_support_t Land_Request_message_type_support_handle = { ::rosidl_typesupport_introspection_cpp::typesupport_identifier, &Land_Request_message_members, get_message_typesupport_handle_function, }; } // namespace rosidl_typesupport_introspection_cpp } // namespace srv } // namespace cf_messages namespace rosidl_typesupport_introspection_cpp { template<> ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC const rosidl_message_type_support_t * get_message_type_support_handle<cf_messages::srv::Land_Request>() { return &::cf_messages::srv::rosidl_typesupport_introspection_cpp::Land_Request_message_type_support_handle; } } // namespace rosidl_typesupport_introspection_cpp #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC const rosidl_message_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_cpp, cf_messages, srv, Land_Request)() { return &::cf_messages::srv::rosidl_typesupport_introspection_cpp::Land_Request_message_type_support_handle; } #ifdef __cplusplus } #endif // already included above // #include "array" // already included above // #include "cstddef" // already included above // #include "string" // already included above // #include "vector" // already included above // #include "rosidl_runtime_c/message_type_support_struct.h" // already included above // #include "rosidl_typesupport_cpp/message_type_support.hpp" // already included above // #include "rosidl_typesupport_interface/macros.h" // already included above // #include "cf_messages/srv/detail/land__struct.hpp" // already included above // #include "rosidl_typesupport_introspection_cpp/field_types.hpp" // already included above // #include "rosidl_typesupport_introspection_cpp/identifier.hpp" // already included above // #include "rosidl_typesupport_introspection_cpp/message_introspection.hpp" // already included above // #include "rosidl_typesupport_introspection_cpp/message_type_support_decl.hpp" // already included above // #include "rosidl_typesupport_introspection_cpp/visibility_control.h" namespace cf_messages { namespace srv { namespace rosidl_typesupport_introspection_cpp { void Land_Response_init_function( void * message_memory, rosidl_runtime_cpp::MessageInitialization _init) { new (message_memory) cf_messages::srv::Land_Response(_init); } void Land_Response_fini_function(void * message_memory) { auto typed_message = static_cast<cf_messages::srv::Land_Response *>(message_memory); typed_message->~Land_Response(); } static const ::rosidl_typesupport_introspection_cpp::MessageMember Land_Response_message_member_array[1] = { { "ret", // name ::rosidl_typesupport_introspection_cpp::ROS_TYPE_INT8, // type 0, // upper bound of string nullptr, // members of sub message false, // is array 0, // array size false, // is upper bound offsetof(cf_messages::srv::Land_Response, ret), // bytes offset in struct nullptr, // default value nullptr, // size() function pointer nullptr, // get_const(index) function pointer nullptr, // get(index) function pointer nullptr // resize(index) function pointer } }; static const ::rosidl_typesupport_introspection_cpp::MessageMembers Land_Response_message_members = { "cf_messages::srv", // message namespace "Land_Response", // message name 1, // number of fields sizeof(cf_messages::srv::Land_Response), Land_Response_message_member_array, // message members Land_Response_init_function, // function to initialize message memory (memory has to be allocated) Land_Response_fini_function // function to terminate message instance (will not free memory) }; static const rosidl_message_type_support_t Land_Response_message_type_support_handle = { ::rosidl_typesupport_introspection_cpp::typesupport_identifier, &Land_Response_message_members, get_message_typesupport_handle_function, }; } // namespace rosidl_typesupport_introspection_cpp } // namespace srv } // namespace cf_messages namespace rosidl_typesupport_introspection_cpp { template<> ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC const rosidl_message_type_support_t * get_message_type_support_handle<cf_messages::srv::Land_Response>() { return &::cf_messages::srv::rosidl_typesupport_introspection_cpp::Land_Response_message_type_support_handle; } } // namespace rosidl_typesupport_introspection_cpp #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC const rosidl_message_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_cpp, cf_messages, srv, Land_Response)() { return &::cf_messages::srv::rosidl_typesupport_introspection_cpp::Land_Response_message_type_support_handle; } #ifdef __cplusplus } #endif #include "rosidl_runtime_c/service_type_support_struct.h" // already included above // #include "rosidl_typesupport_cpp/message_type_support.hpp" #include "rosidl_typesupport_cpp/service_type_support.hpp" // already included above // #include "rosidl_typesupport_interface/macros.h" // already included above // #include "rosidl_typesupport_introspection_cpp/visibility_control.h" // already included above // #include "cf_messages/srv/detail/land__struct.hpp" // already included above // #include "rosidl_typesupport_introspection_cpp/identifier.hpp" // already included above // #include "rosidl_typesupport_introspection_cpp/message_type_support_decl.hpp" #include "rosidl_typesupport_introspection_cpp/service_introspection.hpp" #include "rosidl_typesupport_introspection_cpp/service_type_support_decl.hpp" namespace cf_messages { namespace srv { namespace rosidl_typesupport_introspection_cpp { // this is intentionally not const to allow initialization later to prevent an initialization race static ::rosidl_typesupport_introspection_cpp::ServiceMembers Land_service_members = { "cf_messages::srv", // service namespace "Land", // service name // these two fields are initialized below on the first access // see get_service_type_support_handle<cf_messages::srv::Land>() nullptr, // request message nullptr // response message }; static const rosidl_service_type_support_t Land_service_type_support_handle = { ::rosidl_typesupport_introspection_cpp::typesupport_identifier, &Land_service_members, get_service_typesupport_handle_function, }; } // namespace rosidl_typesupport_introspection_cpp } // namespace srv } // namespace cf_messages namespace rosidl_typesupport_introspection_cpp { template<> ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC const rosidl_service_type_support_t * get_service_type_support_handle<cf_messages::srv::Land>() { // get a handle to the value to be returned auto service_type_support = &::cf_messages::srv::rosidl_typesupport_introspection_cpp::Land_service_type_support_handle; // get a non-const and properly typed version of the data void * auto service_members = const_cast<::rosidl_typesupport_introspection_cpp::ServiceMembers *>( static_cast<const ::rosidl_typesupport_introspection_cpp::ServiceMembers *>( service_type_support->data)); // make sure that both the request_members_ and the response_members_ are initialized // if they are not, initialize them if ( service_members->request_members_ == nullptr || service_members->response_members_ == nullptr) { // initialize the request_members_ with the static function from the external library service_members->request_members_ = static_cast< const ::rosidl_typesupport_introspection_cpp::MessageMembers * >( ::rosidl_typesupport_introspection_cpp::get_message_type_support_handle< ::cf_messages::srv::Land_Request >()->data ); // initialize the response_members_ with the static function from the external library service_members->response_members_ = static_cast< const ::rosidl_typesupport_introspection_cpp::MessageMembers * >( ::rosidl_typesupport_introspection_cpp::get_message_type_support_handle< ::cf_messages::srv::Land_Response >()->data ); } // finally return the properly initialized service_type_support handle return service_type_support; } } // namespace rosidl_typesupport_introspection_cpp #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC const rosidl_service_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_introspection_cpp, cf_messages, srv, Land)() { return ::rosidl_typesupport_introspection_cpp::get_service_type_support_handle<cf_messages::srv::Land>(); } #ifdef __cplusplus } #endif
[ "ruimsc98@gmail.com" ]
ruimsc98@gmail.com
2f74e33bb65b360a32ef1b9174e8aa0533e19ef2
c636136096c92ddb07ce97d3960bf0289d70b57a
/Medusa/MedusaCore/CoreLib/CoreLib.h
70ee1542451194da9d5de5e45a983b1794acc71a
[ "MIT" ]
permissive
johndpope/Medusa
6a5a08e0c3f216dcab3b23db2f7bcf4d05845bce
22aa6719a001330fea51a6822fec01150eb8aabc
refs/heads/master
2020-12-30T20:51:14.718429
2015-12-15T12:31:22
2015-12-15T12:31:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,739
h
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #pragma once #include <list> #include <queue> #include <stack> #include <map> #include <string> #include <string.h> #include <sstream> #include <cstdarg> #include <cassert> #include <ctime> #include <typeinfo> #include <math.h> #include <assert.h> #include <stdio.h> #include <ios> #include <stdarg.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <fstream> #include <memory> #include <stdint.h> #include <initializer_list> #include <functional> #include <atomic> #include <utility> #include <stdint.h> #include <cmath> #include <cstddef> // for std::ptrdiff_t #include <cstdio> #include <algorithm> #include <limits> #include <stdexcept> #include <cctype> #include <cerrno> #include <climits> //curl #ifndef HAVE_CONFIG_H #define HAVE_CONFIG_H #endif #ifndef CURL_STATICLIB #define CURL_STATICLIB #endif #ifndef BUILDING_LIBCURL #define BUILDING_LIBCURL #endif #if _SECURE_SCL # include <iterator> #endif #ifdef MEDUSA_WINDOWS #include "CoreLib/win/CoreLib_win.h" #elif MEDUSA_IOS #include "CoreLib/ios/CoreLib_ios.h" #elif MEDUSA_MAC #elif MEDUSA_ANDROID #include "CoreLib/android/CoreLib_android.h" #elif MEDUSA_LINUX #include "CoreLib/linux/CoreLib_linux.h" #else #endif #ifdef MEDUSA_VFP #include "CoreLib/Common/vfp/matrix_impl.h" #endif #ifdef MEDUSA_NEON #include "CoreLib/Common/neon/math_neon.h" #include "CoreLib/Common/neon/neon_matrix_impl.h" #endif #ifdef MEDUSA_SCRIPT class CScriptBuilder; class asIScriptModule; class asIScriptContext; class asIScriptEngine; class asIScriptObject; struct asSMessageInfo; #endif
[ "fjz13@live.cn" ]
fjz13@live.cn
7348f8ed60c44c2dd2de01e84bcac7cae26166d4
c013714b28ab69d3946ee68f00ce47215c058f4f
/UtolsoVacsora/FluidParticles/blocks/msaFluid/samples/msaFluidParticles/include/ParticleSystem.h
8817cd08ce3a2b19237c572910c229763f422cb8
[]
no_license
gaborpapp/apps
f0195bfd41c30a6f7ab1430bbc0ffda35fbc4ed5
82d06ec9009f81440abc34f996da5ba64583750c
refs/heads/master
2020-06-02T07:59:23.172058
2014-09-17T16:11:27
2014-09-17T16:11:27
1,826,410
3
0
null
null
null
null
UTF-8
C++
false
false
786
h
/* * ParticleSystem.h * * Created by Mehmet Akten on 02/05/2009. * Copyright 2009 MSA Visuals Ltd.. All rights reserved. * */ #pragma once #include "Particle.h" #include "cinder/Vector.h" #define MAX_PARTICLES 50000 class ParticleSystem { public: float posArray[MAX_PARTICLES * 2 * 2]; float colArray[MAX_PARTICLES * 3 * 2]; ci::Vec2i windowSize; ci::Vec2f invWindowSize; const ciMsaFluidSolver *solver; int curIndex; Particle particles[MAX_PARTICLES]; ParticleSystem(); void setFluidSolver( const ciMsaFluidSolver *aSolver ) { solver = aSolver; } void updateAndDraw( bool drawingFluid ); void addParticles( const ci::Vec2f &pos, int count ); void addParticle( const ci::Vec2f &pos ); void setWindowSize( ci::Vec2i winSize ); };
[ "gabor.papp@gmail.com" ]
gabor.papp@gmail.com
31f168a5c000bb1213b328415baba8ff488f83b3
1f40abf77c33ebb9f276f34421ad98e198427186
/tools/output/stubs/Map/SM3/Frustum_generated.cpp
d99c576656cf5c825b0e52e039711a9503dca33a
[]
no_license
fzn7/rts
ff0f1f17bc01fe247ea9e6b761738f390ece112e
b63d3f8a72329ace0058fa821f8dd9a2ece1300d
refs/heads/master
2021-09-04T14:09:26.159157
2018-01-19T09:25:56
2018-01-19T09:25:56
103,816,815
0
2
null
2018-05-22T10:37:40
2017-09-17T09:17:14
C++
UTF-8
C++
false
false
3,925
cpp
#include <iostream> /* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ #include "Frustum.h" #include "Rendering/GL/myGL.h" #undef far // avoid collision with windef.h void Frustum::InversePlanes() { std::vector<Plane>::iterator p; for (p = planes.begin(); p != planes.end(); ++p) { p->Inverse(); } } // find the box vertices to compare against the plane static void BoxPlaneVerts(const Vector3& min, const Vector3& max, const Vector3& plane, Vector3& close, Vector3& far) { if (plane.x > 0) { close.x = min.x; far.x = max.x; } else { close.x = max.x; far.x = min.x; } if (plane.y > 0) { close.y = min.y; far.y = max.y; } else { close.y = max.y; far.y = min.y; } if (plane.z > 0) { close.z = min.z; far.z = max.z; } else { close.z = max.z; far.z = min.z; } } void Frustum::CalcCameraPlanes(Vector3* cbase, Vector3* cright, Vector3* cup, Vector3* cfront, float tanHalfFov, float aspect) { planes.resize(5); planes[0].SetVec(*cfront); planes[0].CalcDist(*cbase + *cfront); float m = 200.0f; base = *cbase + *cfront * m; up = *cup, right = *cright; up *= tanHalfFov * m; right *= tanHalfFov * m * aspect; front = *cfront; pos[0] = base + right + up; // rightup pos[1] = base + right - up; // rightdown pos[2] = base - right - up; // leftdown pos[3] = base - right + up; // leftup base = *cbase; planes[1].MakePlane(base, pos[2], pos[3]); // left planes[2].MakePlane(base, pos[3], pos[0]); // up planes[3].MakePlane(base, pos[0], pos[1]); // right planes[4].MakePlane(base, pos[1], pos[2]); // down right.ANormalize(); up.ANormalize(); front.ANormalize(); } void Frustum::Draw() { if (base.x == 0.0f) return; glDisable(GL_CULL_FACE); /* if (keys[SDLK_t]) { glBegin(GL_LINES); glColor3ub (255,0,0); glVertex3fv((float*)&base); glVertex3fv((float*)&(base+front*100)); glEnd(); glBegin(GL_LINES); glColor3ub (0,255,0); glVertex3fv((float*)&base); glVertex3fv((float*)&(base+right*100)); glEnd(); glBegin(GL_LINES); glColor3ub (0,0,255); glVertex3fv((float*)&base); glVertex3fv((float*)&(base+up*100)); glEnd(); }else{*/ glBegin(GL_LINES); for (int a = 0; a < 4; a++) { glVertex3f(base.x, base.y, base.z); glVertex3f(pos[a].x, pos[a].y, pos[a].z); } glEnd(); glBegin(GL_LINE_LOOP); for (int a = 0; a < 4; a++) { glVertex3fv((float*)&pos[a]); } glEnd(); //} glColor3ub(255, 255, 255); } Frustum::VisType Frustum::IsBoxVisible(const Vector3& min, const Vector3& max) { bool full = true; Vector3 c, f; std::vector<Plane>::iterator p; for (p = planes.begin(); p != planes.end(); ++p) { BoxPlaneVerts(min, max, p->GetVector(), c, f); const float dc = p->Dist(&c); const float df = p->Dist(&f); if (dc < 0.0f || df < 0.0f) full = false; if (dc < 0.0f && df < 0.0f) return Outside; } return full ? Inside : Partial; } Frustum::VisType Frustum::IsPointVisible(const Vector3& pt) { std::vector<Plane>::const_iterator p; for (p = planes.begin(); p != planes.end(); ++p) { float d = p->Dist(&pt); if (d < 0.0f) return Outside; } return Inside; }
[ "plotnikov@teamidea.ru" ]
plotnikov@teamidea.ru
b7d1ad5378efa30a63b2f6f2b75b7fee8e89f820
aba3a373a2dcacdb781d892ca9f83dfc0bc2b36d
/src/include/ast/CallExprAST.hpp
e136373fe20454d63cf9ce89d8b5c2a83e146b13
[]
no_license
pdet/kaleidoscope
42101354b95e49a1a280404a3117c597865fce59
6a20fb0da3639e89897ed8e1ef11182c1d161115
refs/heads/master
2020-06-01T03:33:36.993434
2019-06-17T20:02:14
2019-06-17T20:02:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
471
hpp
#pragma once #include "ast/ExprAST.hpp" #include "llvm/IR/IRBuilder.h" #include "logger/logger.hpp" //Holds most recent prototype for each function // Expression class for functionc calls. class CallExprAST: public ExprAST { std::string Callee; std::vector<std::unique_ptr<ExprAST>> Args; public: CallExprAST (const std::string &Callee, std::vector<std::unique_ptr<ExprAST>> Args): Callee(Callee), Args(std::move(Args)){} llvm::Value *codegen() override; };
[ "pedroholanda@gmail.com" ]
pedroholanda@gmail.com
11c12a1bbdc935fdf607d3f3134010f3a60c186f
18474fa4d01374ea573b5b3abd154af93cb68039
/src/hashtable_block.h
30b30486b152902b719b7b94623e6b3ebf1ab2a5
[]
no_license
andersjo/hanstholm
1159389e54c5cd570585f68db58ffb8f6eac3c4d
847981966670bddab4904bd813b4e757008e45bc
refs/heads/master
2021-01-13T01:31:31.450565
2015-11-27T00:10:57
2015-11-27T00:10:57
31,328,578
1
0
null
null
null
null
UTF-8
C++
false
false
1,914
h
#ifndef HASHTABLE_BLOCK_H #define HASHTABLE_BLOCK_H #include <stddef.h> #include <stdint.h> #include <vector> #include <list> #include "hash.h" //---------------------------------------------- // HashTable // // Maps pointer-sized integers to pointer-sized integers. // Uses open addressing with linear probing. // In the m_cells array, key = 0 is reserved to indicate an unused cell. // Actual value for key 0 (if any) is stored in m_zeroCell. // The hash table automatically doubles in size when it becomes 75% full. // The hash table never shrinks in size, even after Clear(), unless you explicitly call Compact(). //---------------------------------------------- /* struct Cell_ { size_t key; size_t value; }; */ struct Cell { using value_type = float; size_t key; value_type * value; }; class HashTableBlock { public: HashTableBlock() = default; HashTableBlock(size_t initial_size, size_t num_values_per_key); // Basic operations Cell::value_type *lookup(size_t key); Cell::value_type *insert(size_t key); // Keys temporarily made public std::vector<size_t> keys; private: inline size_t hash_key(size_t key) { return (integerHash(key)) & (keys.size() - 1); } Cell::value_type *insert_at(size_t key, size_t index); std::vector<Cell::value_type > values; size_t inserts_before_resize; size_t aligned_value_block_size; void resize(size_t desiredSize); }; /* inline uint32_t upper_power_of_two(uint32_t v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } */ /* // from code.google.com/p/smhasher/wiki/MurmurHash3 inline uint32_t integerHash(uint32_t h) { h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } */ // from code.google.com/p/smhasher/wiki/MurmurHash3 #endif
[ "anders@johannsen.com" ]
anders@johannsen.com