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
15b871b27996e637d5fa792a4ac8bb320b8b7fb4
39306ad5e889c8b152d5ce9c32450f061b7cd78c
/litecov.cpp
575a87f6f2adcafbfbd011bccf9da0161dcc16a6
[ "Apache-2.0" ]
permissive
ExpLife0011/TinyInst
80a0b2c4559be94a8d37f3b1c0815035f4e88b18
e5ec6cc67bb511ce26aea8dfa5d81e0d5b06de2e
refs/heads/master
2022-12-12T04:50:03.166327
2020-08-21T09:06:42
2020-08-21T09:06:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,843
cpp
/* Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https ://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. */ #define _CRT_SECURE_NO_WARNINGS #include "common.h" #include "litecov.h" // mov byte ptr [rip+offset], 1 // note: does not clobber flags static unsigned char MOV_ADDR_1[] = { 0xC6, 0x05, 0xAA, 0xAA, 0xAA, 0x0A, 0x01 }; // same size as instrumentation // used for clearing the instrumentation // if the user wants to ignore specific pieces of coverage // 7-byte nop taken from // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/x86/include/asm/nops.h // thanks @tehjh static unsigned char NOP7[] = { 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00 }; ModuleCovData::ModuleCovData() { ClearInstrumentationData(); } // does not clear collected coverage and ignore coverage void ModuleCovData::ClearInstrumentationData() { coverage_buffer_remote = NULL; coverage_buffer_size = 0; coverage_buffer_next = 0; has_remote_coverage = false; buf_to_coverage.clear(); coverage_to_inst.clear(); } void LiteCov::Init(int argc, char **argv) { TinyInst::Init(argc, argv); coverage_type = COVTYPE_BB; char *option = GetOption("-covtype", argc, argv); if (option) { if (strcmp(option, "bb") == 0) coverage_type = COVTYPE_BB; else if (strcmp(option, "edge") == 0) coverage_type = COVTYPE_EDGE; else FATAL("Unknown coverage type"); } for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *module = *iter; module->client_data = new ModuleCovData(); } } void LiteCov::OnModuleInstrumented(ModuleInfo *module) { ModuleCovData *data = (ModuleCovData *)module->client_data; data->ClearInstrumentationData(); data->coverage_buffer_size = COVERAGE_SIZE; if (!data->coverage_buffer_size) { data->coverage_buffer_size = module->code_size; } // map as readonly initially // this causes an exception the first time coverage is written to the buffer // this enables us to quickly determine if we had new coverage or not data->coverage_buffer_remote = (unsigned char *)RemoteAllocateNear((uint64_t)module->instrumented_code_remote, (uint64_t)module->instrumented_code_remote + module->instrumented_code_size, data->coverage_buffer_size, READONLY); if (!data->coverage_buffer_remote) { FATAL("Could not allocate coverage buffer"); } } void LiteCov::OnModuleUninstrumented(ModuleInfo *module) { ModuleCovData *data = (ModuleCovData *)module->client_data; CollectCoverage(data); if (data->coverage_buffer_remote) { RemoteFree(data->coverage_buffer_remote, data->coverage_buffer_size); } data->ClearInstrumentationData(); } // just replaces the inserted instructions with NOPs void LiteCov::ClearCoverageInstrumentation( ModuleInfo *module, uint64_t coverage_code) { ModuleCovData *data = (ModuleCovData *)module->client_data; auto iter = data->coverage_to_inst.find(coverage_code); if (iter == data->coverage_to_inst.end()) return; size_t code_offset = iter->second; WriteCodeAtOffset(module, code_offset, NOP7, sizeof(NOP7)); // need to commit since this isn't a part of normal instrumentation process CommitCode(module, code_offset, sizeof(NOP7)); data->coverage_to_inst.erase(iter); } void LiteCov::EmitCoverageInstrumentation( ModuleInfo *module, uint64_t coverage_code) { ModuleCovData *data = (ModuleCovData *)module->client_data; // don't instrument if we are ignoring this bit of coverage if (data->ignore_coverage.find(coverage_code) != data->ignore_coverage.end()) return; if (data->coverage_buffer_next == data->coverage_buffer_size) { WARN("Coverage buffer full\n"); return; } if (data->coverage_to_inst.find(coverage_code) != data->coverage_to_inst.end()) { WARN("Edge %llx already exists", coverage_code); } data->buf_to_coverage[data->coverage_buffer_next] = coverage_code; data->coverage_to_inst[coverage_code] = module->instrumented_code_allocated; ////////////////////////////////////////////////// // mov [coverage_buffer + coverage_buffer_next], 1 ////////////////////////////////////////////////// WriteCode(module, MOV_ADDR_1, sizeof(MOV_ADDR_1)); size_t bit_address = (size_t)data->coverage_buffer_remote + data->coverage_buffer_next; size_t mov_address = GetCurrentInstrumentedAddress(module); data->coverage_buffer_next++; // fix the mov address/displacement if (child_ptr_size == 8) { *(int32_t *)(module->instrumented_code_local + module->instrumented_code_allocated - 5) = (int32_t)(bit_address - mov_address); } else { *(uint32_t *)(module->instrumented_code_local + module->instrumented_code_allocated - 5) = (uint32_t)bit_address; } } void LiteCov::InstrumentBasicBlock(ModuleInfo *module, size_t bb_address) { if (coverage_type != COVTYPE_BB) return; uint64_t coverage_code = GetBBCode(module, bb_address); EmitCoverageInstrumentation(module, coverage_code); } void LiteCov::InstrumentEdge( ModuleInfo *previous_module, ModuleInfo *next_module, size_t previous_address, size_t next_address) { if (coverage_type != COVTYPE_EDGE) return; // don't do anything on cross-module edges if (previous_module != next_module) return; uint64_t coverage_code = GetEdgeCode(previous_module, previous_address, next_address); EmitCoverageInstrumentation(previous_module, coverage_code); } // basic block code is just offset from the start of the module uint64_t LiteCov::GetBBCode(ModuleInfo *module, size_t bb_address) { return ((uint64_t)bb_address - (uint64_t)module->min_address); } // edge code has previous offset in higher 32 bits // and next offset in the lower 32 bits // note that source address can be 0 if we don't know it // (module entries, indirect jumps using global jumptable) uint64_t LiteCov::GetEdgeCode( ModuleInfo *module, size_t edge_address1, size_t edge_address2) { uint64_t offset1 = 0; if (edge_address1) offset1 = ((uint64_t)edge_address1 - (uint64_t)module->min_address); uint64_t offset2 = 0; if (edge_address2) offset2 = ((uint64_t)edge_address2 - (uint64_t)module->min_address); return((offset1 << 32) + (offset2 & 0xFFFFFFFF)); } void LiteCov::OnModuleEntered(ModuleInfo *module, size_t entry_address) { if (coverage_type == COVTYPE_BB) return; // if we are in edge coverage mode, record module entries as edges // we don't know the source address (it's in another module) // so treat it as zero ModuleCovData *data = (ModuleCovData *)module->client_data; uint64_t coverage_code = GetEdgeCode(module, 0, entry_address); if (data->ignore_coverage.find(coverage_code) != data->ignore_coverage.end()) return; data->collected_coverage.insert(coverage_code); } // checks if address is in any of our remote coverage buffers ModuleCovData *LiteCov::GetDataByRemoteAddress(size_t address) { for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *module = *iter; ModuleCovData *data = (ModuleCovData *)module->client_data; if (!data->coverage_buffer_remote) continue; if ((address >= (size_t)data->coverage_buffer_remote) && (address < ((size_t)data->coverage_buffer_remote + data->coverage_buffer_size))) { return data; } } return NULL; } // catches writing to the coverage buffer for the first time void LiteCov::HandleBufferWriteException(ModuleCovData *data) { RemoteProtect(data->coverage_buffer_remote, data->coverage_buffer_size, READWRITE); data->has_remote_coverage = true; } bool LiteCov::OnException(Exception *exception_record) { if ((exception_record->type == ACCESS_VIOLATION) && (exception_record->maybe_write_violation)) { ModuleCovData *data = GetDataByRemoteAddress((size_t)exception_record->access_address); if (data) { HandleBufferWriteException(data); return true; } } return TinyInst::OnException(exception_record); } void LiteCov::ClearRemoteBuffer(ModuleCovData *data) { if (!data->coverage_buffer_remote) return; if (!data->has_remote_coverage) return; unsigned char *buf = (unsigned char *)malloc(data->coverage_buffer_next); memset(buf, 0, data->coverage_buffer_next); RemoteWrite(data->coverage_buffer_remote, buf, data->coverage_buffer_next); RemoteProtect(data->coverage_buffer_remote, data->coverage_buffer_size, READONLY); data->has_remote_coverage = false; free(buf); } void LiteCov::ClearCoverage(ModuleCovData *data) { data->collected_coverage.clear(); ClearRemoteBuffer(data); } void LiteCov::ClearCoverage() { for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *module = *iter; ModuleCovData *data = (ModuleCovData *)module->client_data; ClearCoverage(data); } } // fetches and decodes coverage from the remote buffer void LiteCov::CollectCoverage(ModuleCovData *data) { if (!data->has_remote_coverage) return; unsigned char *buf = (unsigned char *)malloc(data->coverage_buffer_next); RemoteRead(data->coverage_buffer_remote, buf, data->coverage_buffer_next); for (size_t i = 0; i < data->coverage_buffer_next; i++) { if (buf[i]) { uint64_t coverage_code = data->buf_to_coverage[i]; data->collected_coverage.insert(coverage_code); } } free(buf); ClearRemoteBuffer(data); } void LiteCov::CollectCoverage() { for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *module = *iter; ModuleCovData *data = (ModuleCovData *)module->client_data; CollectCoverage(data); } } void LiteCov::GetCoverage(Coverage &coverage, bool clear_coverage) { CollectCoverage(); for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *module = *iter; ModuleCovData *data = (ModuleCovData *)module->client_data; if (data->collected_coverage.empty()) continue; // check if that module is already in the coverage list // (if the client calls with non-empty initial coverage) ModuleCoverage *module_coverage = GetModuleCoverage(coverage, module->module_name); if (module_coverage) { module_coverage->offsets.insert( data->collected_coverage.begin(), data->collected_coverage.end()); } else { coverage.push_back({ module->module_name, data->collected_coverage }); } } if (clear_coverage) ClearCoverage(); } // sets (new) coverage to ignore void LiteCov::IgnoreCoverage(Coverage &coverage) { for (auto iter = coverage.begin(); iter != coverage.end(); iter++) { ModuleInfo *module = GetModuleByName(iter->module_name); if (!module) continue; ModuleCovData *data = (ModuleCovData *)module->client_data; // remember the offsets so they don't get instrumented later data->ignore_coverage.insert(iter->offsets.begin(), iter->offsets.end()); if (!module->instrumented) continue; // if we already have instrumentation in place for some of the offsets // remove it here for (auto code_iter = iter->offsets.begin(); code_iter != iter->offsets.end(); code_iter++) { ClearCoverageInstrumentation(module, *code_iter); } } } // quickly checks if we have new coverage bool LiteCov::HasNewCoverage() { for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *module = *iter; ModuleCovData *data = (ModuleCovData *)module->client_data; if (!data->collected_coverage.empty()) return true; if (data->has_remote_coverage) return true; } return false; } void LiteCov::OnProcessExit() { TinyInst::OnProcessExit(); CollectCoverage(); }
[ "ifratric@google.com" ]
ifratric@google.com
aa0d66116587e5aacef27284211d4db04fd9f0c8
fb92dd12322f2fcdfeb96df2cca8c6737ba60c6f
/GameEngine/GameEngine/AnimMan.h
c656f3d2a53ff2ccb31f5f6b94ccb81424da645a
[]
no_license
hemalpatel2990/GameEngine
f016dd37538abf01e213b66a148d1316f2899a44
570d08014474f3f719b24e7a174b621b48906745
refs/heads/master
2020-05-26T20:16:13.954501
2019-05-24T05:56:29
2019-05-24T05:56:29
188,360,106
1
0
null
null
null
null
UTF-8
C++
false
false
741
h
#ifndef ANIM_MAN_H #define ANIM_MAN_H #include "Trace.h" #include "GameObject.h" #include "Game.h" #include "ShaderObject.h" #include "TextureManager.h" #include "InputMan.h" #include "CameraMan.h" #include "GameObjectMan.h" #include "Timer.h" #include "Anim.h" #include "FrameBucket.h" class AnimMan { public: static void Update(); static void SetHead(Frame_Bucket *); static Frame_Bucket * GetHead(); static void SetBone(GameObject *); static GameObject * GetBone(); private: AnimMan(); static AnimMan *privGetInstance(); Frame_Bucket *pFirstBone; GameObject *pFBone; bool privPlus = false; bool privMinus = false; bool privNext = false; bool privPlay = false; bool isPlaying = true; float fastForward = 0.1f; }; #endif
[ "1mike.po007@gmail.com" ]
1mike.po007@gmail.com
9909ca7c9a1cd8b1364c3cbf77e4cad76796fa2c
52519bf3723f6ed38858198321e798988b964e31
/src/rocketchatrestapi-qt5/autotests/getthreadsjobtest.cpp
863d8f005f3e65f9870fca4c86248730ca7b6213
[]
no_license
jcelerier/ruqola
d5625ad0d048a6546900018e70af250a724ebd64
4de6bacb63cc7a7a71b4b4e50cdce0076a6288e1
refs/heads/master
2022-02-20T15:37:19.362724
2019-07-20T07:19:34
2019-07-20T07:19:34
197,894,956
0
0
null
2019-07-20T07:21:36
2019-07-20T07:21:36
null
UTF-8
C++
false
false
2,788
cpp
/* Copyright (c) 2019 Montel Laurent <montel@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "getthreadsjobtest.h" #include "chat/getthreadsjob.h" #include "restapimethod.h" #include <QTest> QTEST_GUILESS_MAIN(GetThreadsJobTest) using namespace RocketChatRestApi; GetThreadsJobTest::GetThreadsJobTest(QObject *parent) : QObject(parent) { } void GetThreadsJobTest::shouldHaveDefaultValue() { GetThreadsJob job; QVERIFY(!job.restApiMethod()); QVERIFY(!job.networkAccessManager()); QVERIFY(!job.start()); QVERIFY(job.roomId().isEmpty()); QVERIFY(job.requireHttpAuthentication()); QVERIFY(!job.restApiLogger()); QVERIFY(job.hasQueryParameterSupport()); } void GetThreadsJobTest::shouldGenerateRequest() { GetThreadsJob job; RestApiMethod *method = new RestApiMethod; method->setServerUrl(QStringLiteral("http://www.kde.org")); job.setRestApiMethod(method); const QString roomId = QStringLiteral("bla"); job.setRoomId(roomId); const QNetworkRequest request = job.request(); QCOMPARE(request.url(), QUrl(QStringLiteral("http://www.kde.org/api/v1/chat.getThreadsList?rid=%1").arg(roomId))); delete method; } void GetThreadsJobTest::shouldNotStarting() { GetThreadsJob job; RestApiMethod *method = new RestApiMethod; method->setServerUrl(QStringLiteral("http://www.kde.org")); job.setRestApiMethod(method); QNetworkAccessManager *mNetworkAccessManager = new QNetworkAccessManager; job.setNetworkAccessManager(mNetworkAccessManager); QVERIFY(!job.canStart()); const QString auth = QStringLiteral("foo"); const QString userId = QStringLiteral("foo"); job.setAuthToken(auth); QVERIFY(!job.canStart()); job.setUserId(userId); QVERIFY(!job.canStart()); const QString roomId = QStringLiteral("foo1"); job.setRoomId(roomId); QVERIFY(job.canStart()); delete method; delete mNetworkAccessManager; }
[ "montel@kde.org" ]
montel@kde.org
d4782624c9fc6b739782ba6b7a5e16cb2f3fc2e6
ddf988b5a89017cfa449ac55b0f8315696352789
/c++_primer_ex/ex9_7.cc
262f4135b7a7a10fe9a3e02981b5486feb7409db
[]
no_license
cheerayhuang/Garner
6fe7dfb1c12799dcb5b3eb809bce8a4119ba0f05
fafccc9d53adab1403c3884a09b46e5e9c2910e7
refs/heads/master
2022-12-20T20:46:40.954396
2022-12-12T03:38:43
2022-12-12T03:38:43
5,774,039
1
0
null
null
null
null
UTF-8
C++
false
false
906
cc
/************************************************************************** * * Copyright (c) 2014 Nibirutech, Inc. All Rights Reserved * www.Nibirutech.com * * @file: ex9_7.cc * @author: Huang Qiyu * @email: huangqiyu@chukong-inc.com * @date: 10-23-2014 16:41:13 * @version $Revision$ * **************************************************************************/ #include <vector> #include <iostream> using namespace std; class A { public: int a; public: A(int, int) {} A(initializer_list<int> il) { a = *il.begin();} }; int main() { vector<int> vec(8); cout << vec.size() << endl; int k = 10; vector<int>::reference i = k; vector<int>::const_reference ci = k; //ci = 10; typedef decltype((k)) reference; reference rk = k; cout << i << endl; A classA{4, 5}; cout << classA.a << endl; return 0; }
[ "cheeray.huang@gmail.com" ]
cheeray.huang@gmail.com
1736459330d8f5476cf020df2c8b21232f49477a
6c778b46e083c561c26191b379559356adef9923
/TripleX.cpp
dec30101f3edbf385bb5c60d758132bfb9ef935e
[]
no_license
mazenswar/TripleX
dcbefcf0fa31a1f4c0a2927017dc5fa7fd323886
0c13789a18800a9b33c48c3f5748796a2d3cf72e
refs/heads/main
2023-04-15T21:31:34.951860
2021-05-03T17:03:35
2021-05-03T17:03:35
363,996,791
0
0
null
null
null
null
UTF-8
C++
false
false
1,907
cpp
#include <iostream> #include <ctime> void PrintIntroduction(int Diffculty) { if (Diffculty == 1) { std::cout << "\n You are a secret agent breaking into a secure server room... \n"; std::cout << "\n Enter the correct code to continue \n"; } } bool PlayGame(int Difficulty) { PrintIntroduction(Difficulty); const int CodeA = rand() % Difficulty + Difficulty; const int CodeB = rand() % Difficulty + Difficulty; const int CodeC = rand() % Difficulty + Difficulty; const int CodeSum = CodeA + CodeB + CodeC; const int CodeProduct = CodeA * CodeB * CodeC; // std::cout << std::endl; std::cout << "\n There are three numbers in the code" << std::endl; std::cout << "\n The code adds up to: " << CodeSum << std::endl; std::cout << "\n The product is: " << CodeProduct << std::endl; std::cout << "\n Enter your guess MOFO, what are the three numbers?" << std::endl; // int PlayerGuess; int GuessA, GuessB, GuessC; std::cin >> GuessA; std::cin >> GuessB; std::cin >> GuessC; int GuessSum = GuessA + GuessB + GuessC; int GuessProduct = GuessA * GuessB * GuessC; std::cout << "\n \n You entered: " << GuessA << GuessB << GuessC; if (GuessSum == CodeSum && CodeProduct == GuessProduct) { std::cout << "\n \n Well done agent, you have extracted a file, keep going!" << std::endl; return true; } else { std::cout << "\n \n You entered the wrong code! Careful agent! Try again!" << std::endl; return false; } } int main() { srand(time(NULL)); int const MaxDifficulty = 5; int Difficulty = 1; while (Difficulty <= MaxDifficulty) { bool bLevelComplete = PlayGame(Difficulty); std::cin.clear(); std::cin.ignore(); if (bLevelComplete) { ++Difficulty; } } return 0; }
[ "mazenswar@protonmail.com" ]
mazenswar@protonmail.com
6534acbfc9db7fdc535f2af76fbe84073f7347da
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_3200.cpp
70342ad592b634468878b3ea4be3eac4308d389a
[]
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
188
cpp
(forceOverwrite) { remove(outName); } else { fprintf ( stderr, "%s: Output file %s already exists.\n", progName, outName ); setExit(1); return; }
[ "993273596@qq.com" ]
993273596@qq.com
80e9ee34bd196b1289aad96810ecc48765ef61ae
f19896ff3a1016d4ae63db6e9345cfcc4d0a2967
/Topics/Topic/Data Structures and Alogrithms (Topic)/Leetcode(Website)/697(Degree of an array).cpp
5ff91b2be1e45c17d8c0cfa7355438928aab3c9e
[]
no_license
Akshay199456/100DaysOfCode
079800b77a44abe560866cf4750dfc6c7fe01a59
b4ed8a6793c17bcb71c56686d98fcd683af64841
refs/heads/master
2023-08-08T07:59:02.723675
2023-08-01T03:44:15
2023-08-01T03:44:15
226,718,143
3
0
null
null
null
null
UTF-8
C++
false
false
3,288
cpp
/* -------------------------Question: Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. Example 1: Input: nums = [1,2,2,3,1] Output: 2 Explanation: The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So return 2. Example 2: Input: nums = [1,2,2,3,1,4,2] Output: 6 Explanation: The degree is 3 because the element 2 is repeated 3 times. So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6. Constraints: nums.length will be between 1 and 50,000. nums[i] will be an integer between 0 and 49,999. */ /* ------------------------- My Approaches: 1. using maps to register first seen and last seen state We can use maops to register the count, first seen state ans last seen state of any element. Once we do that, we can go through the array again to find the elements that have the same count as the degree and use the firstseenstate and lastseenstate to determine the lenght. We can keep track of the min length as we are going along. Time complexity: O(n) Space complexity: O(n) */ /* ------------------------- Other approaches: */ // My Approaches(1) class Solution { public: int fillMaps(vector<int> nums, unordered_map<int,int> & countMap, unordered_map<int,int> & firstSeenMap,unordered_map<int,int> & lastSeenMap){ // fills the maps and returns the degree of the array int maxCount = 0; for(int i=0; i<nums.size(); i++){ int value = 0; // filling countMap and degree // if element doesn't exist in countMap, insert it if(countMap.find(nums[i]) == countMap.end()) value = 1; else value = countMap[nums[i]] + 1; countMap[nums[i]] = value; maxCount = max(maxCount, value); // filling firstSeenMap and lastSeenMap if(firstSeenMap.find(nums[i]) == firstSeenMap.end()) firstSeenMap[nums[i]] = i; lastSeenMap[nums[i]] = i; } return maxCount; } int getMinLength(vector<int> nums, unordered_map<int,int> countMap, unordered_map<int,int> firstSeenMap,unordered_map<int,int> lastSeenMap, int degree){ int minLength = INT_MAX; for(int i=0; i<nums.size(); i++){ if(countMap[nums[i]] == degree) minLength = min(minLength, lastSeenMap[nums[i]] - firstSeenMap[nums[i]] + 1); } return minLength; } int findShortestSubArray(vector<int>& nums) { unordered_map<int,int> countMap, firstSeenMap, lastSeenMap; // get degree of array int degree = fillMaps(nums, countMap, firstSeenMap, lastSeenMap); // from firstSeen, lastSeen and count maps, find elements that have the same count and minimize the length return getMinLength(nums, countMap, firstSeenMap, lastSeenMap, degree); } };
[ "akshay.kum94@gmail.com" ]
akshay.kum94@gmail.com
08a7f2e8a5884ed2ac4c32bc8debb00e7d4ff7bf
ea378f7f0a3a8a3ebf2a0b9097a31fab4b2a15ae
/C-plus-plus/quxuesuanfa_chapter3_3.cpp
cd510108971ed3e669f218401782a3bca42a850c
[]
no_license
RoseVamboo/Algorithms
f1b75ffb4455357beb3c2ab5a005fbb80429d51e
7214da2180a63c54e0af6c6101e5b5368c8948e8
refs/heads/master
2020-04-04T22:58:53.266536
2018-11-06T07:33:54
2018-11-06T07:33:54
156,342,830
0
0
null
null
null
null
GB18030
C++
false
false
965
cpp
#include <iostream> using namespace std; void Merge(int s[], int low, int middle, int high){ int *B = new int[high - low + 1]; int i = low, j = middle+1,k=0; while (i<=middle&&j<=high){ if (s[i] < s[j]){ B[k++] = s[i++]; } else{ B[k++] = s[j++]; } } while (i <= middle)B[k++] = s[i++]; while (j <= high)B[k++] = s[j++]; for (i = low, k = 0; i <= high; i++, k++){ s[i] = B[k]; } } void MergeSort(int low,int high,int s[]){ if (low < high){ int middle = (low + high) / 2; MergeSort(low, middle, s); MergeSort(middle + 1, high, s); Merge(s, low, middle, high); } } int main_chapter3_3(){ int n, A[100]; cout << "请输入数列中元素的个数n:" << endl; cin >> n; cout << "请依次输入数列中的元素:" << endl; for (int i = 0; i < n; i++) cin >> A[i]; MergeSort(0, n - 1, A); cout << "合并排序结果" << endl; for (int i = 0; i < n; i++) cout << A[i] << " "; cout << endl; system("pause"); return 0; }
[ "zourose123@126.com" ]
zourose123@126.com
94875b7f62f29972f777a1d409943c851f232174
f65df82bcd2741b9974a50b78da87852f9552492
/src/stdafx.h
2c38f46fa704490b8aa88549424e10b4e72b0879
[ "MIT" ]
permissive
alexezh/trv
9ecd0a12560dc137c998cf4f0359e024ff77053c
1dd97096ed9f60ffb64c4e44e2e309e9c5002224
refs/heads/master
2021-01-10T19:54:07.103746
2017-04-23T14:41:24
2017-04-23T14:41:24
7,505,645
0
0
null
null
null
null
UTF-8
C++
false
false
2,085
h
// Copyright (c) 2013 Alexandre Grigorovitch (alexezh@gmail.com). // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #pragma once #ifndef STRICT #define STRICT #endif #define _CRT_SECURE_NO_WARNINGS 1 #define _ATL_APARTMENT_THREADED #define _ATL_NO_AUTOMATIC_NAMESPACE #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit // turns off ATL's hiding of some common and often safely ignored warning messages #define _ATL_ALL_WARNINGS #include <atlbase.h> #include <atlcom.h> #include <atlwin.h> #include <atltypes.h> #include <atlctl.h> #include <atlhost.h> #include <atlstr.h> #include <atlcoll.h> //#include <atlrx.h> #include <Richedit.h> #include <shellapi.h> #include <ShObjIdl.h> #include <ShlObj.h> #include <KnownFolders.h> #include <string> #include <vector> #include <map> #include <set> #include <queue> #include <unordered_map> #include <list> #include <sstream> #include <memory> #include <fstream> #include <functional> #include <assert.h> #include <mutex> #include "include/v8.h" using namespace ATL;
[ "alexezh@gmail.com" ]
alexezh@gmail.com
b364f96d95d3765de45a8252d2ee32bcdf107e39
d87495a64800b98ffba47c73518c6e243da04d84
/source/unshare.cpp
a0154bc63888d26eb0f3989b30a7eb8e8cb41d73
[ "ISC", "MIT", "BSD-3-Clause", "BSD-2-Clause" ]
permissive
synety-jdebp/nosh
6a7c106201789a7c73a84ede0954e7351b31ea42
010be9e4e8628007b42bc46ee18cb1e9dc6881ff
refs/heads/master
2021-05-10T12:45:32.993528
2018-02-15T17:59:14
2018-02-15T17:59:14
118,451,036
0
0
null
null
null
null
UTF-8
C++
false
false
2,561
cpp
/* COPYING ****************************************************************** For copyright and licensing terms, see the file named COPYING. // ************************************************************************** */ #include <vector> #include <cstdio> #include <cstdlib> #include <cerrno> #include <cstring> #include <unistd.h> #include "utils.h" #include "popt.h" #if !defined(__LINUX__) && !defined(__linux__) static inline int unshare ( int ) { return 0 ; } #endif /* Main function ************************************************************ // ************************************************************************** */ void unshare ( const char * & next_prog, std::vector<const char *> & args, ProcessEnvironment & /*envs*/ ) { const char * prog(basename_of(args[0])); bool network(false), mount(false), ipc(false), uts(false), process(false), user(false); try { popt::bool_definition network_option('n', "network", "Unshare the network namespace.", network); popt::bool_definition uts_option('u', "uts", "Unshare the UTS namespace.", uts); popt::bool_definition mount_option('m', "mount", "Unshare the mount namespace.", mount); popt::bool_definition ipc_option('i', "ipc", "Unshare the IPC namespace.", ipc); popt::bool_definition process_option('p', "process", "Unshare the process ID namespace.", process); popt::bool_definition user_option('u', "user", "Unshare the user ID namespace.", user); popt::definition * top_table[] = { &network_option, &mount_option, &ipc_option, &uts_option, &process_option, &user_option }; popt::top_table_definition main_option(sizeof top_table/sizeof *top_table, top_table, "Main options", "prog"); std::vector<const char *> new_args; popt::arg_processor<const char **> p(args.data() + 1, args.data() + args.size(), prog, main_option, new_args); p.process(true /* strictly options before arguments */); args = new_args; next_prog = arg0_of(args); if (p.stopped()) throw EXIT_SUCCESS; } catch (const popt::error & e) { std::fprintf(stderr, "%s: FATAL: %s: %s\n", prog, e.arg, e.msg); throw EXIT_FAILURE; } const int flags ( #if defined(__LINUX__) || defined(__linux__) (mount ? CLONE_NEWNS : 0) | (network ? CLONE_NEWNET : 0) | (ipc ? CLONE_NEWIPC : 0) | (uts ? CLONE_NEWUTS : 0) | (process ? CLONE_NEWPID : 0) | (user ? CLONE_NEWUSER : 0) | #endif 0 ); const pid_t rc(unshare(flags)); if (-1 == rc) { const int error(errno); std::fprintf(stderr, "%s: FATAL: %s\n", prog, std::strerror(error)); throw EXIT_FAILURE; } }
[ "jonathan.de.boyne.pollard@synety.com" ]
jonathan.de.boyne.pollard@synety.com
cd5edc4fb9cb01a4f3df2bdc5e0b4e8dad9b0673
3edd3da6213c96cf342dc842e8b43fe2358c960d
/abc/abc073/a/main.cpp
2360685c7cd6f42530861570709d58d88db518aa
[]
no_license
tic40/atcoder
7c5d12cc147741d90a1f5f52ceddd708b103bace
3c8ff68fe73e101baa2aff955bed077cae893e52
refs/heads/main
2023-08-30T20:10:32.191136
2023-08-30T00:58:07
2023-08-30T00:58:07
179,283,303
0
0
null
null
null
null
UTF-8
C++
false
false
617
cpp
#include <bits/stdc++.h> using namespace std; #define REP(i, n) for(int i = 0; i < n; i++) #define COUT(x) cout<<(x)<<endl #define dump(x) cout << #x << " = " << (x) << endl; using ll = long long; using P = pair<int,int>; using Graph = vector<vector<int>>; using M = map<int,int>; using PQ = priority_queue<int>; using PQG = priority_queue<int, vector<int>, greater<int>>; const int INF = 1e9; const int MOD = 1e9+7; const ll LINF = 1e18; int main() { int n; cin >> n; while(n > 0) { if (n % 10 == 9) { cout << "Yes" << endl; return 0; } n/=10; } cout << "No" << endl; return 0; }
[ "ccpzjoh@gmail.com" ]
ccpzjoh@gmail.com
96a8f3faa4302a396584b901e269c148d36061c5
0f283e48dca3fd98114cf4d6df5f810d17d2edc5
/dll.UsefulFunctions/aaplus/AAKepler.h
29eff07a57934117024ff0b74c21c7ff40992a1d
[]
no_license
erakli/NES_satellite_motion
85971f303e20d3dd16fd425d2c64a6e628b8786f
0ec68f48db68a5cf2a54cbcfff96f56c8bf6a2ec
refs/heads/master
2021-01-10T12:39:03.232134
2016-01-29T10:33:15
2016-01-29T10:33:15
44,527,740
0
0
null
2015-11-15T23:51:48
2015-10-19T10:36:11
C++
UTF-8
C++
false
false
1,290
h
/* Module : AAKEPLER.H Purpose: Implementation for the algorithms which solve Kepler's equation Created: PJN / 29-12-2003 Copyright (c) 2003 - 2015 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) All rights reserved. Copyright / Usage Details: You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) when your product is released in binary form. You are allowed to modify the source code in any way you want except you cannot modify the copyright details at the top of each module. If you want to distribute source code with your application, then you are only allowed to distribute versions released by the author. This is to maintain a single distribution point for the source code. */ /////////////////////// Macros / Defines ////////////////////////////////////// #if _MSC_VER > 1000 #pragma once #endif //#if _MSC_VER > 1000 #ifndef __AAKEPLER_H__ #define __AAKEPLER_H__ #ifndef AAPLUS_EXT_CLASS #define AAPLUS_EXT_CLASS #endif //#ifndef AAPLUS_EXT_CLASS /////////////////////// Classes /////////////////////////////////////////////// class AAPLUS_EXT_CLASS CAAKepler { public: //Static methods static double Calculate(double M, double e, int nIterations = 53); }; #endif //#ifndef __AAKEPLER_H__
[ "erakli00@yandex.com" ]
erakli00@yandex.com
fbb98ceadd8138f217c8c0e2c9eb85f597fe8319
cd396e0cf8ca525394702994bec7c66bcbad3c91
/Chapter1_1/MainChapter1_7.cpp
d7cd228869a84cfe33969944a281c9a827fde707
[]
no_license
BlockJJam/MyCppStudy
c46794402be1186b60264724989c9a11b73ad1aa
4d42683da7b2596df2a697283c1c1cd3141e71c6
refs/heads/master
2020-09-05T22:39:57.974222
2019-11-22T06:19:06
2019-11-22T06:19:06
220,233,812
0
0
null
null
null
null
UHC
C++
false
false
627
cpp
/* <지역범위> 밑의 x의 선언이 3번 이루어졌는데 ( int x=1, x=2, x(0) ) -> 각각의 영역이 {}를 써서 다르기 때문에 가능하다 cout을 써서 x의 메모리 주소를 확인해보자 => 즉, 지역변수는 영역을 벗어났을 때 사용할 수 없게 된다 */ #include <iostream> using namespace std; int main() { int x(0); //객체지향에서 가능한 표현 x=0 ; x가 인스턴스를 갖는다 { //영역 boundary표현 int x = 1; cout << x << " " << &x << endl; } { int x = 2; cout << x << " " << &x << endl; } cout << x << " " << &x << endl; return 0; }
[ "blockjjam99@gmail.com" ]
blockjjam99@gmail.com
7c48634b6fa6e9015100b3562a65bbbda61d75bc
a26ef769b3de60c3325c6f5c8ab833265e7f44c3
/MapTool/MapTool/GameMain.h
f158de348ee2d540d020da456953746126fb28b2
[]
no_license
kimi28/SchoolProject
6f11e77a792e2a98d3f6d927637bbbca84f975cc
dc51b1ca476700b0df9c3050a4a1f0066f2127f8
refs/heads/master
2021-01-20T09:17:11.743780
2018-04-26T02:27:35
2018-04-26T02:27:35
90,233,859
0
0
null
null
null
null
UTF-8
C++
false
false
1,396
h
#pragma once #include "DxWindow.h" class Sprite; class Rect; class Animation; #define TILESIZE 32 #define TILEX 20 #define TILEY 20 #define TILESIZEX TILEX *TILESIZE #define TILESIZEY TILEY *TILESIZE #define SAMPLETILEX 20 #define SAMPLETILEY 8 enum TERRAIN { TR_CEMENT, TR_GROUND, TR_GRASS, TR_WATER, TR_END }; enum OBJECT { OBJ_BLOCK1, OBJ_BLOCK2, OBJ_BLOCK3, OBJ_TANK1, OBJ_TANK2, OBJ_FLAG1, OBJ_FLAG2, OBJ_NONE }; enum POS { POS_FALG1, POS_FALG2, POS_TANK1, POS_TANK2 }; struct tagTile { Animation* animation; TERRAIN terrain; OBJECT obj; int terrainFrameX; int terrainFrameY; int objFrameX; int objFrameY; }; struct tagSampleTile { Rect* rcTile; int terrainFrameX; int terrainFrameY; }; struct tagCurrentTile { int x; int y; }; class GameMain : public DxWindow { public: GameMain(HINSTANCE hInstance, LPCWSTR className, LPCSTR lpCmdLine, int nCmdShow); ~GameMain(); void Initialize(); void Destroy(); void Update(); void Render(); void MapToolSetup(); void SetMap(); void Save(); void Load(); TERRAIN TerrainSelect(int frameX, int frameY); OBJECT ObjSelect(int frameX, int frameY); void SetCtrSelect(int num) { ctrSelect = num; } private: Sprite* sprite; int ctrSelect; tagCurrentTile currentTile; tagTile tiles[TILEX * TILEY]; tagSampleTile sampleTiles[SAMPLETILEX * SAMPLETILEY]; int pos[2]; D3DVIEWPORT9 viewport; };
[ "kimhaidong28@gmail.com" ]
kimhaidong28@gmail.com
ad2d45f4d55bd51f7a1b2cb05d1c2c76d65db8b6
7ec7ded86996b0e857baa174640e59db35487665
/combined/using_client/mainwindow.hpp
8d3e565063740f4f2f9571784b85fdb79f7c816b
[]
no_license
vcato/mvc_example
a5efc6cab505181666cee755f28249938701a71f
70fc74996a25f4e13f462b7f8b8cf56057af41f2
refs/heads/master
2020-05-04T14:07:02.690111
2019-04-30T18:27:28
2019-04-30T18:27:28
179,185,319
0
0
null
null
null
null
UTF-8
C++
false
false
1,387
hpp
#ifndef MAINWINDOW_HPP_ #define MAINWINDOW_HPP_ #include <memory> #include "applicationdata.hpp" #include "optionswindow.hpp" class MainWindow { public: MainWindow(); ~MainWindow(); void setApplicationDataPtr(ApplicationData *); void open(); protected: ApplicationData &_applicationData(); protected: // Controller methods void controllerOnOpenOptionsPressed(); void controllerOnOptionsWindowOptionsChanged(); private: // View interface virtual void viewOpenWindow() = 0; virtual bool viewOptionsWindowExists() const = 0; virtual void viewCreateOptionsWindow() = 0; virtual OptionsWindow &viewOptionsWindow() = 0; virtual void viewRedraw3D() = 0; private: class OptionsWindowClient : public OptionsWindow::Client { public: OptionsWindowClient(MainWindow &main_window) : _main_window(main_window) { } void onOptionsChanged() override { _main_window.controllerOnOptionsWindowOptionsChanged(); } Options &options() override { return _main_window._applicationData().options; } private: MainWindow &_main_window; }; OptionsWindowClient _options_window_client; ApplicationData *_application_data_ptr = nullptr; void _controllerOpenOptionsWindow(); }; #endif /* MAINWINDOW_HPP_ */
[ "vaughn@giantstudios.com" ]
vaughn@giantstudios.com
4e10927b073ec5d682aa025a844c8dbc9568b4c4
6d258d9abc888d6c4640b77afa23355f9bafb5a0
/curlpp/examples/ex24_debug_fucntion.cpp
832427ebc64df7fdb056ebab2f4c47055f6f8e53
[]
no_license
ohwada/MAC_cpp_Samples
e281130c8fd339ec327d4fad6d8cdf4e9bab4edc
74699e40343f13464d64cf5eb3e965140a6b31a2
refs/heads/master
2023-02-05T00:50:47.447668
2023-01-28T05:09:34
2023-01-28T05:09:34
237,116,830
15
1
null
null
null
null
UTF-8
C++
false
false
3,630
cpp
/** * curlpp sample * 2020-07-01 K.OHWADA */ // Example 24: Binded method functor for DebugFunction example. // https://github.com/jpbarrette/curlpp/blob/master/examples/example24.cpp /* * Copyright (c) <2002-2005> <Jean-Philippe Barrette-LaPierre> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files * (curlpp), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include <string> #include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> #include <curlpp/Exception.hpp> #include <curlpp/Infos.hpp> #include <cstdlib> /** * struct MethodClass */ struct MethodClass { private: MethodClass(); public: MethodClass(std::ostream * stream) : mStream(stream) , writeRound(0) {} // Helper Class for reading result from remote host size_t debug(curlpp::Easy *handle, curl_infotype type, char* ptr, size_t size) { ++writeRound; curlpp::options::Url url; handle->getOpt(url); // Calculate the real size of the incoming buffer //std::cerr << "write round: " << writeRound << ", url: " << url.getValue() << ", type: " << type << std::endl; std::cerr << "debug: "; mStream->write(ptr, size); // return the real size of the buffer... return size; }; // Public member vars std::ostream * mStream; unsigned writeRound; }; using namespace std; /** * main */ int main(int argc, char *argv[]) { string url("http://example.com"); if(argc == 2) { url = argv[1]; } else { cerr << argv[0] << ": Usage: " << " url " << endl; } try { curlpp::Cleanup cleaner; curlpp::Easy request; MethodClass mObject( &std::cerr ); // Set the debug callback to enable cURL // to write result in a stream using namespace std::placeholders; curlpp::options::DebugFunction * test = new curlpp::options::DebugFunction(std::bind(&MethodClass::debug, &mObject, &request, _1, _2, _3)); request.setOpt(test); // Setting the URL to retrive. request.setOpt(new curlpp::options::Url(url)); request.setOpt(new curlpp::options::Verbose(true)); request.perform(); return EXIT_SUCCESS; } catch ( curlpp::LogicError & e ) { cout << e.what() << endl; } catch ( curlpp::RuntimeError & e ) { cout << e.what() << endl; } return EXIT_FAILURE; } // debug: Trying 2606:2800:220:1:248:1893:25c8:1946... // debug: Connection #0 to host example.com left intact
[ "ml.ohwada@gmail.com" ]
ml.ohwada@gmail.com
4be93054b6986fbce08231fa8e902c2fca5b55ef
571673736994bc6d5d28f46202e732283a4dfab0
/xorm/reflect/reflector.hpp
e6d3934bb6333e4768b73d2f4d2ab60001c09c32
[]
no_license
zhaoyaogit/xorm
a0818c2a591c82ed6d099f04f136646066ca8084
8ab88c90b03d7a429e26c3244c06651af292c41b
refs/heads/master
2023-01-03T18:32:17.986147
2020-11-03T07:32:41
2020-11-03T07:32:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,166
hpp
#pragma once #include <array> #include <tuple> #include <string> namespace reflector { #define place_holder 120,119,118,117,116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,100,99,98,97,96,95,94,93,92,91,90,89,88,87,86,85,84,83,82,81,80,79,78,77,76,75,74,73,72,71,70,69,68,67,66,65,64,63,62,61,60,59,58,57,56,55,54,53,52,51,50,49,48,47,46,45,44,43,42,41,40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 #define expand_marco(...) __VA_ARGS__ #define concat_a_b_(a,b) a##b #define concat_a_b(a,b) concat_a_b_(a,b) #ifdef _MSC_VER #define inner_var(...) unused,__VA_ARGS__ #define get_count_(_0,_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,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,_57,_58,_59,_60,_61,_62,_63,_64,_65,_66,_67,_68,_69,_70,_71,_72,_73,_74,_75,_76,_77,_78,_79,_80,_81,_82,_83,_84,_85,_86,_87,_88,_89,_90,_91,_92,_93,_94,_95,_96,_97,_98,_99,_100,_101,_102,_103,_104,_105,_106,_107,_108,_109,_110,_111,_112,_113,_114,_115,_116,_117,_118,_119,_120,count,...) count #define get_count_help(...) expand_marco(get_count_(__VA_ARGS__)) #define get_count(...) get_count_help(inner_var(__VA_ARGS__),place_holder) #else // _NOT_MSC_VER #define get_count_(_0,_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,_26,_27,_28,_29,_30,_31,_32,_33,_34,_35,_36,_37,_38,_39,_40,_41,_42,_43,_44,_45,_46,_47,_48,_49,_50,_51,_52,_53,_54,_55,_56,_57,_58,_59,_60,_61,_62,_63,_64,_65,_66,_67,_68,_69,_70,_71,_72,_73,_74,_75,_76,_77,_78,_79,_80,_81,_82,_83,_84,_85,_86,_87,_88,_89,_90,_91,_92,_93,_94,_95,_96,_97,_98,_99,_100,_101,_102,_103,_104,_105,_106,_107,_108,_109,_110,_111,_112,_113,_114,_115,_116,_117,_118,_119,_120,count,...) count #define get_count_help(...) get_count_(__VA_ARGS__) #define get_count(...) get_count_help(0,## __VA_ARGS__,place_holder) #endif #define For_1(method,ClassName,element,...) method(ClassName,element) #define For_2(method,ClassName,element,...) method(ClassName,element),expand_marco(For_1(method,ClassName,__VA_ARGS__)) #define For_3(method,ClassName,element,...) method(ClassName,element),expand_marco(For_2(method,ClassName,__VA_ARGS__)) #define For_4(method,ClassName,element,...) method(ClassName,element),expand_marco(For_3(method,ClassName,__VA_ARGS__)) #define For_5(method,ClassName,element,...) method(ClassName,element),expand_marco(For_4(method,ClassName,__VA_ARGS__)) #define For_6(method,ClassName,element,...) method(ClassName,element),expand_marco(For_5(method,ClassName,__VA_ARGS__)) #define For_7(method,ClassName,element,...) method(ClassName,element),expand_marco(For_6(method,ClassName,__VA_ARGS__)) #define For_8(method,ClassName,element,...) method(ClassName,element),expand_marco(For_7(method,ClassName,__VA_ARGS__)) #define For_9(method,ClassName,element,...) method(ClassName,element),expand_marco(For_8(method,ClassName,__VA_ARGS__)) #define For_10(method,ClassName,element,...) method(ClassName,element),expand_marco(For_9(method,ClassName,__VA_ARGS__)) #define For_11(method,ClassName,element,...) method(ClassName,element),expand_marco(For_10(method,ClassName,__VA_ARGS__)) #define For_12(method,ClassName,element,...) method(ClassName,element),expand_marco(For_11(method,ClassName,__VA_ARGS__)) #define For_13(method,ClassName,element,...) method(ClassName,element),expand_marco(For_12(method,ClassName,__VA_ARGS__)) #define For_14(method,ClassName,element,...) method(ClassName,element),expand_marco(For_13(method,ClassName,__VA_ARGS__)) #define For_15(method,ClassName,element,...) method(ClassName,element),expand_marco(For_14(method,ClassName,__VA_ARGS__)) #define For_16(method,ClassName,element,...) method(ClassName,element),expand_marco(For_15(method,ClassName,__VA_ARGS__)) #define For_17(method,ClassName,element,...) method(ClassName,element),expand_marco(For_16(method,ClassName,__VA_ARGS__)) #define For_18(method,ClassName,element,...) method(ClassName,element),expand_marco(For_17(method,ClassName,__VA_ARGS__)) #define For_19(method,ClassName,element,...) method(ClassName,element),expand_marco(For_18(method,ClassName,__VA_ARGS__)) #define For_20(method,ClassName,element,...) method(ClassName,element),expand_marco(For_19(method,ClassName,__VA_ARGS__)) #define For_21(method,ClassName,element,...) method(ClassName,element),expand_marco(For_20(method,ClassName,__VA_ARGS__)) #define For_22(method,ClassName,element,...) method(ClassName,element),expand_marco(For_21(method,ClassName,__VA_ARGS__)) #define For_23(method,ClassName,element,...) method(ClassName,element),expand_marco(For_22(method,ClassName,__VA_ARGS__)) #define For_24(method,ClassName,element,...) method(ClassName,element),expand_marco(For_23(method,ClassName,__VA_ARGS__)) #define For_25(method,ClassName,element,...) method(ClassName,element),expand_marco(For_24(method,ClassName,__VA_ARGS__)) #define For_26(method,ClassName,element,...) method(ClassName,element),expand_marco(For_25(method,ClassName,__VA_ARGS__)) #define For_27(method,ClassName,element,...) method(ClassName,element),expand_marco(For_26(method,ClassName,__VA_ARGS__)) #define For_28(method,ClassName,element,...) method(ClassName,element),expand_marco(For_27(method,ClassName,__VA_ARGS__)) #define For_29(method,ClassName,element,...) method(ClassName,element),expand_marco(For_28(method,ClassName,__VA_ARGS__)) #define For_30(method,ClassName,element,...) method(ClassName,element),expand_marco(For_29(method,ClassName,__VA_ARGS__)) #define For_31(method,ClassName,element,...) method(ClassName,element),expand_marco(For_30(method,ClassName,__VA_ARGS__)) #define For_32(method,ClassName,element,...) method(ClassName,element),expand_marco(For_31(method,ClassName,__VA_ARGS__)) #define For_33(method,ClassName,element,...) method(ClassName,element),expand_marco(For_32(method,ClassName,__VA_ARGS__)) #define For_34(method,ClassName,element,...) method(ClassName,element),expand_marco(For_33(method,ClassName,__VA_ARGS__)) #define For_35(method,ClassName,element,...) method(ClassName,element),expand_marco(For_34(method,ClassName,__VA_ARGS__)) #define For_36(method,ClassName,element,...) method(ClassName,element),expand_marco(For_35(method,ClassName,__VA_ARGS__)) #define For_37(method,ClassName,element,...) method(ClassName,element),expand_marco(For_36(method,ClassName,__VA_ARGS__)) #define For_38(method,ClassName,element,...) method(ClassName,element),expand_marco(For_37(method,ClassName,__VA_ARGS__)) #define For_39(method,ClassName,element,...) method(ClassName,element),expand_marco(For_38(method,ClassName,__VA_ARGS__)) #define For_40(method,ClassName,element,...) method(ClassName,element),expand_marco(For_39(method,ClassName,__VA_ARGS__)) #define For_41(method,ClassName,element,...) method(ClassName,element),expand_marco(For_40(method,ClassName,__VA_ARGS__)) #define For_42(method,ClassName,element,...) method(ClassName,element),expand_marco(For_41(method,ClassName,__VA_ARGS__)) #define For_43(method,ClassName,element,...) method(ClassName,element),expand_marco(For_42(method,ClassName,__VA_ARGS__)) #define For_44(method,ClassName,element,...) method(ClassName,element),expand_marco(For_43(method,ClassName,__VA_ARGS__)) #define For_45(method,ClassName,element,...) method(ClassName,element),expand_marco(For_44(method,ClassName,__VA_ARGS__)) #define For_46(method,ClassName,element,...) method(ClassName,element),expand_marco(For_45(method,ClassName,__VA_ARGS__)) #define For_47(method,ClassName,element,...) method(ClassName,element),expand_marco(For_46(method,ClassName,__VA_ARGS__)) #define For_48(method,ClassName,element,...) method(ClassName,element),expand_marco(For_47(method,ClassName,__VA_ARGS__)) #define For_49(method,ClassName,element,...) method(ClassName,element),expand_marco(For_48(method,ClassName,__VA_ARGS__)) #define For_50(method,ClassName,element,...) method(ClassName,element),expand_marco(For_49(method,ClassName,__VA_ARGS__)) #define For_51(method,ClassName,element,...) method(ClassName,element),expand_marco(For_50(method,ClassName,__VA_ARGS__)) #define For_52(method,ClassName,element,...) method(ClassName,element),expand_marco(For_51(method,ClassName,__VA_ARGS__)) #define For_53(method,ClassName,element,...) method(ClassName,element),expand_marco(For_52(method,ClassName,__VA_ARGS__)) #define For_54(method,ClassName,element,...) method(ClassName,element),expand_marco(For_53(method,ClassName,__VA_ARGS__)) #define For_55(method,ClassName,element,...) method(ClassName,element),expand_marco(For_54(method,ClassName,__VA_ARGS__)) #define For_56(method,ClassName,element,...) method(ClassName,element),expand_marco(For_55(method,ClassName,__VA_ARGS__)) #define For_57(method,ClassName,element,...) method(ClassName,element),expand_marco(For_56(method,ClassName,__VA_ARGS__)) #define For_58(method,ClassName,element,...) method(ClassName,element),expand_marco(For_57(method,ClassName,__VA_ARGS__)) #define For_59(method,ClassName,element,...) method(ClassName,element),expand_marco(For_58(method,ClassName,__VA_ARGS__)) #define For_60(method,ClassName,element,...) method(ClassName,element),expand_marco(For_59(method,ClassName,__VA_ARGS__)) #define For_61(method,ClassName,element,...) method(ClassName,element),expand_marco(For_60(method,ClassName,__VA_ARGS__)) #define For_62(method,ClassName,element,...) method(ClassName,element),expand_marco(For_61(method,ClassName,__VA_ARGS__)) #define For_63(method,ClassName,element,...) method(ClassName,element),expand_marco(For_62(method,ClassName,__VA_ARGS__)) #define For_64(method,ClassName,element,...) method(ClassName,element),expand_marco(For_63(method,ClassName,__VA_ARGS__)) #define For_65(method,ClassName,element,...) method(ClassName,element),expand_marco(For_64(method,ClassName,__VA_ARGS__)) #define For_66(method,ClassName,element,...) method(ClassName,element),expand_marco(For_65(method,ClassName,__VA_ARGS__)) #define For_67(method,ClassName,element,...) method(ClassName,element),expand_marco(For_66(method,ClassName,__VA_ARGS__)) #define For_68(method,ClassName,element,...) method(ClassName,element),expand_marco(For_67(method,ClassName,__VA_ARGS__)) #define For_69(method,ClassName,element,...) method(ClassName,element),expand_marco(For_68(method,ClassName,__VA_ARGS__)) #define For_70(method,ClassName,element,...) method(ClassName,element),expand_marco(For_69(method,ClassName,__VA_ARGS__)) #define For_71(method,ClassName,element,...) method(ClassName,element),expand_marco(For_70(method,ClassName,__VA_ARGS__)) #define For_72(method,ClassName,element,...) method(ClassName,element),expand_marco(For_71(method,ClassName,__VA_ARGS__)) #define For_73(method,ClassName,element,...) method(ClassName,element),expand_marco(For_72(method,ClassName,__VA_ARGS__)) #define For_74(method,ClassName,element,...) method(ClassName,element),expand_marco(For_73(method,ClassName,__VA_ARGS__)) #define For_75(method,ClassName,element,...) method(ClassName,element),expand_marco(For_74(method,ClassName,__VA_ARGS__)) #define For_76(method,ClassName,element,...) method(ClassName,element),expand_marco(For_75(method,ClassName,__VA_ARGS__)) #define For_77(method,ClassName,element,...) method(ClassName,element),expand_marco(For_76(method,ClassName,__VA_ARGS__)) #define For_78(method,ClassName,element,...) method(ClassName,element),expand_marco(For_77(method,ClassName,__VA_ARGS__)) #define For_79(method,ClassName,element,...) method(ClassName,element),expand_marco(For_78(method,ClassName,__VA_ARGS__)) #define For_80(method,ClassName,element,...) method(ClassName,element),expand_marco(For_79(method,ClassName,__VA_ARGS__)) #define For_81(method,ClassName,element,...) method(ClassName,element),expand_marco(For_80(method,ClassName,__VA_ARGS__)) #define For_82(method,ClassName,element,...) method(ClassName,element),expand_marco(For_81(method,ClassName,__VA_ARGS__)) #define For_83(method,ClassName,element,...) method(ClassName,element),expand_marco(For_82(method,ClassName,__VA_ARGS__)) #define For_84(method,ClassName,element,...) method(ClassName,element),expand_marco(For_83(method,ClassName,__VA_ARGS__)) #define For_85(method,ClassName,element,...) method(ClassName,element),expand_marco(For_84(method,ClassName,__VA_ARGS__)) #define For_86(method,ClassName,element,...) method(ClassName,element),expand_marco(For_85(method,ClassName,__VA_ARGS__)) #define For_87(method,ClassName,element,...) method(ClassName,element),expand_marco(For_86(method,ClassName,__VA_ARGS__)) #define For_88(method,ClassName,element,...) method(ClassName,element),expand_marco(For_87(method,ClassName,__VA_ARGS__)) #define For_89(method,ClassName,element,...) method(ClassName,element),expand_marco(For_88(method,ClassName,__VA_ARGS__)) #define For_90(method,ClassName,element,...) method(ClassName,element),expand_marco(For_89(method,ClassName,__VA_ARGS__)) #define For_91(method,ClassName,element,...) method(ClassName,element),expand_marco(For_90(method,ClassName,__VA_ARGS__)) #define For_92(method,ClassName,element,...) method(ClassName,element),expand_marco(For_91(method,ClassName,__VA_ARGS__)) #define For_93(method,ClassName,element,...) method(ClassName,element),expand_marco(For_92(method,ClassName,__VA_ARGS__)) #define For_94(method,ClassName,element,...) method(ClassName,element),expand_marco(For_93(method,ClassName,__VA_ARGS__)) #define For_95(method,ClassName,element,...) method(ClassName,element),expand_marco(For_94(method,ClassName,__VA_ARGS__)) #define For_96(method,ClassName,element,...) method(ClassName,element),expand_marco(For_95(method,ClassName,__VA_ARGS__)) #define For_97(method,ClassName,element,...) method(ClassName,element),expand_marco(For_96(method,ClassName,__VA_ARGS__)) #define For_98(method,ClassName,element,...) method(ClassName,element),expand_marco(For_97(method,ClassName,__VA_ARGS__)) #define For_99(method,ClassName,element,...) method(ClassName,element),expand_marco(For_98(method,ClassName,__VA_ARGS__)) #define For_100(method,ClassName,element,...) method(ClassName,element),expand_marco(For_99(method,ClassName,__VA_ARGS__)) #define For_101(method,ClassName,element,...) method(ClassName,element),expand_marco(For_100(method,ClassName,__VA_ARGS__)) #define For_102(method,ClassName,element,...) method(ClassName,element),expand_marco(For_101(method,ClassName,__VA_ARGS__)) #define For_103(method,ClassName,element,...) method(ClassName,element),expand_marco(For_102(method,ClassName,__VA_ARGS__)) #define For_104(method,ClassName,element,...) method(ClassName,element),expand_marco(For_103(method,ClassName,__VA_ARGS__)) #define For_105(method,ClassName,element,...) method(ClassName,element),expand_marco(For_104(method,ClassName,__VA_ARGS__)) #define For_106(method,ClassName,element,...) method(ClassName,element),expand_marco(For_105(method,ClassName,__VA_ARGS__)) #define For_107(method,ClassName,element,...) method(ClassName,element),expand_marco(For_106(method,ClassName,__VA_ARGS__)) #define For_108(method,ClassName,element,...) method(ClassName,element),expand_marco(For_107(method,ClassName,__VA_ARGS__)) #define For_109(method,ClassName,element,...) method(ClassName,element),expand_marco(For_108(method,ClassName,__VA_ARGS__)) #define For_110(method,ClassName,element,...) method(ClassName,element),expand_marco(For_109(method,ClassName,__VA_ARGS__)) #define For_111(method,ClassName,element,...) method(ClassName,element),expand_marco(For_110(method,ClassName,__VA_ARGS__)) #define For_112(method,ClassName,element,...) method(ClassName,element),expand_marco(For_111(method,ClassName,__VA_ARGS__)) #define For_113(method,ClassName,element,...) method(ClassName,element),expand_marco(For_112(method,ClassName,__VA_ARGS__)) #define For_114(method,ClassName,element,...) method(ClassName,element),expand_marco(For_113(method,ClassName,__VA_ARGS__)) #define For_115(method,ClassName,element,...) method(ClassName,element),expand_marco(For_114(method,ClassName,__VA_ARGS__)) #define For_116(method,ClassName,element,...) method(ClassName,element),expand_marco(For_115(method,ClassName,__VA_ARGS__)) #define For_117(method,ClassName,element,...) method(ClassName,element),expand_marco(For_116(method,ClassName,__VA_ARGS__)) #define For_118(method,ClassName,element,...) method(ClassName,element),expand_marco(For_117(method,ClassName,__VA_ARGS__)) #define For_119(method,ClassName,element,...) method(ClassName,element),expand_marco(For_118(method,ClassName,__VA_ARGS__)) #define For_120(method,ClassName,element,...) method(ClassName,element),expand_marco(For_119(method,ClassName,__VA_ARGS__)) #define For_121(method,ClassName,element,...) method(ClassName,element),expand_marco(For_120(method,ClassName,__VA_ARGS__)) #define For_122(method,ClassName,element,...) method(ClassName,element),expand_marco(For_121(method,ClassName,__VA_ARGS__)) #define For_123(method,ClassName,element,...) method(ClassName,element),expand_marco(For_122(method,ClassName,__VA_ARGS__)) #define For_124(method,ClassName,element,...) method(ClassName,element),expand_marco(For_123(method,ClassName,__VA_ARGS__)) #define For_125(method,ClassName,element,...) method(ClassName,element),expand_marco(For_124(method,ClassName,__VA_ARGS__)) #define address_macro(Class,Element) &Class::Element #define element_name_macro(Class,Element) #Element #define GENERATOR_META(N,ClassName,...) \ static std::array<char const*,N> ClassName##_element_name_arr = { expand_marco(concat_a_b(For_,N)(element_name_macro,ClassName,__VA_ARGS__)) }; \ struct ClassName##_meta_info \ { \ auto get_element_names()-> std::array<char const*,N> \ { \ return ClassName##_element_name_arr; \ } \ auto get_element_meta_protype()->decltype(std::make_tuple(expand_marco(concat_a_b(For_,N)(address_macro,ClassName,__VA_ARGS__)))) \ { \ return std::make_tuple(expand_marco(concat_a_b(For_,N)(address_macro,ClassName,__VA_ARGS__))); \ } \ std::string get_class_name() \ { \ return #ClassName ; \ } \ constexpr std::size_t element_size() { return N; } \ }; \ auto meta_info_reflect(ClassName const& t)->ClassName##_meta_info \ { \ return ClassName##_meta_info{}; \ } #define REFLECTION(ClassName,...) GENERATOR_META(get_count(__VA_ARGS__),ClassName,__VA_ARGS__) template<typename...Args> using void_t = void; template<typename T, typename U = void> struct is_reflect_class :std::false_type { }; template<typename T> struct is_reflect_class<T, void_t<decltype(meta_info_reflect(std::declval<T>()))>> :std::true_type { }; template<std::size_t N, std::size_t Size> struct each_ { template<typename name_tuple, typename protype_tuple, typename T, typename Function> static void each(name_tuple&& tuple0, protype_tuple&& tuple1, T&& t, Function&& callback) { callback(std::forward<T>(t), std::get<N>(tuple0), std::get<N>(tuple1)); each_<N + 1, Size>::template each(std::forward<name_tuple>(tuple0), std::forward<protype_tuple>(tuple1), std::forward<T>(t), std::forward<Function>(callback)); } }; template<std::size_t Size> struct each_<Size, Size> { template<typename name_tuple, typename protype_tuple, typename T, typename Function> static void each(name_tuple&& tuple0, protype_tuple&& tuple1, T&& t, Function&& callback) { } }; template<std::size_t N, std::size_t Size> struct each_1 { template<typename name_tuple, typename protype_tuple, typename T, typename Function> static void each(name_tuple&& tuple0, protype_tuple&& tuple1, std::string const& name, T&& t, Function&& callback) { if (name == std::get<N>(tuple0)) { callback(std::forward<T>(t), std::get<N>(tuple0), std::get<N>(tuple1)); } each_1<N + 1, Size>::template each(std::forward<name_tuple>(tuple0), std::forward<protype_tuple>(tuple1), name, std::forward<T>(t), std::forward<Function>(callback)); } }; template<std::size_t Size> struct each_1<Size, Size> { template<typename name_tuple, typename protype_tuple, typename T, typename Function> static void each(name_tuple&& tuple0, protype_tuple&& tuple1, std::string const& name, T&& t, Function&& callback) { } }; template<typename T, typename Function> typename std::enable_if<is_reflect_class<typename std::remove_reference<T>::type>::value>::type each_object(T&& t, Function&& callback) { using class_type = typename std::remove_reference<T>::type; using meta_info_type = decltype(meta_info_reflect(std::declval<class_type>())); auto meta = meta_info_type{}; each_<0, meta.element_size()>::template each(meta.get_element_names(), meta.get_element_meta_protype(), std::forward<T>(t), std::forward<Function>(callback)); } template<typename T, typename Function> typename std::enable_if<is_reflect_class<typename std::remove_reference<T>::type>::value>::type find_protype(std::string const& name, T&& t, Function&& callback) { using class_type = typename std::remove_reference<T>::type; using meta_info_type = decltype(meta_info_reflect(std::declval<class_type>())); auto meta = meta_info_type{}; each_1<0, meta.element_size()>::template each(meta.get_element_names(), meta.get_element_meta_protype(), name, std::forward<T>(t), std::forward<Function>(callback)); } }
[ "970252187@qq.com" ]
970252187@qq.com
f9e00790b3a2aaa21a16cf929ff43cd0f3a9fd44
92e67b30497ffd29d3400e88aa553bbd12518fe9
/assignment2/part6/Re=110/26.7/p
f0bba3cf63165be8cb4b669f50f929e4fa40c472
[]
no_license
henryrossiter/OpenFOAM
8b89de8feb4d4c7f9ad4894b2ef550508792ce5c
c54b80dbf0548b34760b4fdc0dc4fb2facfdf657
refs/heads/master
2022-11-18T10:05:15.963117
2020-06-28T15:24:54
2020-06-28T15:24:54
241,991,470
0
0
null
null
null
null
UTF-8
C++
false
false
22,087
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "26.7"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 2000 ( -0.00194526 -0.000344096 0.000823125 0.00228653 0.0039987 0.00588858 0.00790021 0.00999343 0.0121414 0.0143461 -0.000901217 0.000795528 0.00197855 0.0034013 0.00503059 0.0068136 0.0087031 0.0106589 0.012651 0.0146771 0.000168334 0.00190023 0.00308613 0.00445917 0.00599182 0.00764754 0.00939036 0.011184 0.0129977 0.0148212 0.0012532 0.00296088 0.00413663 0.00545413 0.00688265 0.00839741 0.00997391 0.0115828 0.0131963 0.0147934 0.00233381 0.00396558 0.00511976 0.00637949 0.00770304 0.0090712 0.0104687 0.0118742 0.0132659 0.0146097 0.0033861 0.0049042 0.00602887 0.00723215 0.0084555 0.00967932 0.0108935 0.0120833 0.0132321 0.014278 0.00438325 0.00576888 0.00686078 0.00801231 0.00914458 0.0102332 0.0112691 0.012241 0.0131321 0.013797 0.00529597 0.00655183 0.00761276 0.00872024 0.00977347 0.010741 0.0116125 0.0123795 0.0130175 0.013187 0.00609407 0.0072445 0.00828015 0.00935291 0.0103401 0.0112029 0.0119298 0.0125204 0.0129328 0.0124852 0.00675104 0.0078379 0.00885584 0.00990202 0.0108346 0.0116088 0.0122153 0.0126731 0.0129399 0.0120587 0.0196239 0.0282472 0.0352902 0.0418935 0.0473154 0.052052 0.0552598 0.0586931 0.0590028 0.0610059 0.0195329 0.0274472 0.0340306 0.0402393 0.0453774 0.0499331 0.0530441 0.0563062 0.0568162 0.0585292 0.0192003 0.0264915 0.0326801 0.0385462 0.0434496 0.047857 0.0508615 0.0540334 0.054665 0.0561591 0.0186511 0.025409 0.0312519 0.0368232 0.0415408 0.0458149 0.0487376 0.0518575 0.0525231 0.0539135 0.0179367 0.0242621 0.0297736 0.0350938 0.0396587 0.0438094 0.0466763 0.049756 0.0504329 0.0517959 0.0171139 0.0230558 0.0282308 0.0333617 0.0378035 0.0418449 0.0446663 0.0476988 0.0483961 0.0497744 0.0162899 0.02185 0.0266837 0.0316672 0.0359886 0.039929 0.0427115 0.0457021 0.0464533 0.047856 0.0154872 0.0204943 0.0250532 0.0299695 0.0341985 0.0380579 0.0407979 0.0437158 0.0445318 0.0459941 0.0149772 0.0192362 0.0235415 0.0283426 0.032459 0.0362436 0.0389613 0.0418197 0.0427248 0.0442276 0.0139837 0.0174776 0.0217848 0.0265887 0.0306942 0.0344423 0.0371206 0.0398296 0.0408456 0.0424576 0.0171946 0.0164794 0.0191658 0.0229886 0.0267456 0.0303189 0.0332122 0.0358725 0.0371771 0.0385261 0.0114565 0.011237 0.0142413 0.0178441 0.0213519 0.0246133 0.0273451 0.0296802 0.0308637 0.0318699 0.00451286 0.00563797 0.00931808 0.0130557 0.0164382 0.0193975 0.0217718 0.0237742 0.0247933 0.0256536 -0.00163028 0.000457991 0.00464926 0.00865353 0.0119345 0.0145219 0.0163808 0.0178686 0.0186483 0.0194267 -0.00582946 -0.00370739 0.000382911 0.00449106 0.00771432 0.01006 0.0115448 0.0126303 0.0131165 0.0137873 -0.00815517 -0.00627712 -0.00253184 0.00128914 0.00421622 0.00621765 0.00726002 0.0078827 0.00826163 0.00887504 -0.00855396 -0.00727911 -0.0041859 -0.000818565 0.00168447 0.00322263 0.00376243 0.00371337 0.00381062 0.00471359 -0.00691905 -0.00634651 -0.00413885 -0.00180848 9.84083e-05 0.00120676 0.001576 0.000442796 0.000629314 0.00142105 -0.00450876 -0.00416586 -0.00302805 -0.00165594 -0.000570341 -0.000108421 -0.000397698 -0.00142711 -0.00162127 -0.000804442 -0.00120097 -0.00123168 -0.00112365 -0.000660647 -0.000342383 -0.000298828 -0.000693459 -0.00148223 -0.00181371 -0.00114516 0.0118698 0.00827837 0.00253712 -0.00273927 -0.00628553 -0.00815888 -0.00796271 -0.00643413 -0.00380286 -0.000572815 0.0110175 0.00692298 0.00112471 -0.00388812 -0.00699366 -0.00848301 -0.00798347 -0.00634249 -0.00360987 -0.000568316 0.0102283 0.00540093 -0.000372356 -0.00509283 -0.00777954 -0.00887088 -0.00804738 -0.00624586 -0.00341456 -0.000611632 0.00916062 0.00375175 -0.00187974 -0.00626331 -0.00852316 -0.00922399 -0.00808939 -0.00614765 -0.00327516 -0.000651303 0.00777746 0.00199561 -0.00341385 -0.00742891 -0.00924559 -0.00955187 -0.00812766 -0.00605141 -0.00314024 -0.000688236 0.00610803 0.000195423 -0.0049077 -0.00853973 -0.00991994 -0.00984623 -0.00815797 -0.00595184 -0.0030179 -0.000721646 0.00431684 -0.00152493 -0.00625381 -0.00951552 -0.0104953 -0.0100803 -0.00816612 -0.00584635 -0.0029121 -0.000748805 0.00266579 -0.00300541 -0.00734069 -0.0102779 -0.0109221 -0.0102283 -0.00813941 -0.00573338 -0.00282482 -0.000771561 0.00140292 -0.00410123 -0.00808211 -0.010771 -0.0111617 -0.0102709 -0.00806615 -0.00560536 -0.00274598 -0.000789217 0.000668297 -0.00473842 -0.00843564 -0.01097 -0.0111953 -0.0101958 -0.00793672 -0.00547117 -0.00268153 -0.000780275 0.000465508 -0.00493183 -0.0084146 -0.0108752 -0.0110274 -0.00999089 -0.0077504 -0.00531406 -0.00263182 -0.000746177 0.000716543 -0.00471273 -0.0080708 -0.0105123 -0.0106759 -0.00966879 -0.00753321 -0.00514229 -0.00258171 -0.000721603 0.00134519 -0.00416983 -0.00746008 -0.00993363 -0.0101705 -0.00924858 -0.00724357 -0.00496237 -0.00253373 -0.000711531 0.00225215 -0.00338985 -0.00665485 -0.00919249 -0.00955245 -0.00875521 -0.00694157 -0.00477761 -0.00248504 -0.000708915 0.0033466 -0.00244483 -0.00572572 -0.00834114 -0.00886418 -0.00821456 -0.00657522 -0.0045832 -0.00242472 -0.000708362 0.0045517 -0.00139311 -0.00473185 -0.00742727 -0.00814141 -0.00765356 -0.00621354 -0.00438416 -0.00242519 -0.00070759 0.0057974 -0.000282458 -0.00371888 -0.00648857 -0.00741068 -0.00709101 -0.00585877 -0.00417005 -0.00234691 -0.000702278 0.0070657 0.000884677 -0.00269754 -0.00554369 -0.00668897 -0.0065407 -0.00551349 -0.00397265 -0.00227545 -0.000692709 0.00844488 0.00220267 -0.00162856 -0.00458363 -0.00597605 -0.00601008 -0.005183 -0.00378486 -0.0022043 -0.000679658 0.00955018 0.00351942 -0.000596372 -0.00363719 -0.00525109 -0.00546108 -0.00483454 -0.00358373 -0.00212127 -0.000659234 0.00956391 0.00546809 0.00138761 -0.00153937 -0.00341931 -0.00400316 -0.00379998 -0.00293876 -0.00182585 -0.000581553 0.0102237 0.00661691 0.00307305 0.000507664 -0.00129327 -0.00211999 -0.0023375 -0.00191751 -0.00121319 -0.000338639 0.0120714 0.00849618 0.00501568 0.00250106 0.000590643 -0.00048787 -0.00102488 -0.00093025 -0.000549378 -3.24531e-05 0.0142294 0.0105502 0.00702303 0.00442368 0.00232147 0.000980156 0.000166718 1.64262e-05 0.000173423 0.00036543 0.0166642 0.0127293 0.00904169 0.00625209 0.00390117 0.00229491 0.00125334 0.00094626 0.000963294 0.00084803 0.0193397 0.0150188 0.0110465 0.00797138 0.00533244 0.00347749 0.00225909 0.00186373 0.00181197 0.00140202 0.0221742 0.0173233 0.0129726 0.00956384 0.00665275 0.0045766 0.00322893 0.00278007 0.00268168 0.00196498 0.0247618 0.0192944 0.0147672 0.0110529 0.00789577 0.00562473 0.00418388 0.0036531 0.00338555 0.00227307 0.0271208 0.0219205 0.0167582 0.0124122 0.0089578 0.00654838 0.00502965 0.00425739 0.00355767 0.00204576 0.0298487 0.0223085 0.016848 0.0126634 0.00944682 0.00713285 0.00557812 0.00451478 0.00338397 0.00163119 0.0123515 0.013212 0.0149318 0.0169968 0.0195987 0.0224744 0.0254887 0.0290279 0.0302284 0.0360041 0.0133059 0.0145474 0.0163807 0.0185499 0.0213245 0.0243424 0.0275117 0.0310883 0.0325781 0.0373686 0.0140045 0.0156614 0.0177906 0.0203081 0.0234196 0.026721 0.0301569 0.0336928 0.0358178 0.0380737 0.014705 0.0165966 0.018969 0.0218498 0.0252948 0.0289023 0.0326153 0.0362697 0.0388436 0.0396588 0.0154422 0.0175617 0.0201339 0.0233103 0.0270156 0.0308729 0.0348148 0.0386577 0.0415372 0.0421895 0.0161582 0.0185946 0.0214204 0.0248752 0.0288005 0.0328599 0.0369818 0.040993 0.044122 0.0452172 0.0168322 0.0196564 0.0228167 0.026584 0.030744 0.0350081 0.0393021 0.0434562 0.0468007 0.0483859 0.0174761 0.0207328 0.0242823 0.0283977 0.0328286 0.0373311 0.0418266 0.0461337 0.0496633 0.0515734 0.0181026 0.021834 0.0258028 0.0302844 0.0350147 0.0397896 0.0445261 0.0490207 0.0527208 0.0548064 0.018718 0.0229696 0.0273778 0.0322347 0.0372823 0.0423505 0.0473586 0.0520761 0.0559527 0.0581464 0.0193268 0.0241412 0.0290027 0.0342455 0.0396257 0.045001 0.050303 0.0552703 0.0593434 0.0616361 0.0199251 0.0253329 0.0306612 0.0363042 0.0420353 0.047733 0.0533505 0.0585878 0.0628835 0.0652869 0.0204969 0.0265046 0.0323273 0.0383856 0.0444949 0.0505444 0.0565114 0.0620438 0.0665776 0.069102 0.0210117 0.027613 0.0339698 0.0404619 0.0469877 0.0534232 0.0597861 0.065649 0.0704262 0.0730787 0.0214185 0.0286329 0.0355603 0.0425068 0.0495215 0.056392 0.0631675 0.0693879 0.0744338 0.0772226 0.0216466 0.0295493 0.0370547 0.044554 0.0520468 0.0593794 0.0665986 0.0732178 0.07858 0.0815258 0.0215864 0.030424 0.0384734 0.0465291 0.0545274 0.0623714 0.0700901 0.077162 0.0828825 0.0860093 0.0212674 0.0311024 0.0397006 0.0483278 0.0568674 0.0652675 0.0735407 0.0811397 0.0872962 0.090657 0.0207551 0.031645 0.0408005 0.0500283 0.0591477 0.068153 0.0770316 0.0852149 0.0918569 0.0955116 0.0195174 0.0315854 0.0413382 0.0511675 0.0608839 0.0705376 0.0801164 0.089064 0.0964101 0.100525 0.0195579 0.0336851 0.0446889 0.0557544 0.0667478 0.0778265 0.088906 0.0994484 0.108212 0.113346 0.0301715 0.0437994 0.0551443 0.0678259 0.0807024 0.0940476 0.107661 0.120815 0.131831 0.13815 0.0426455 0.0563018 0.0684726 0.0830259 0.0979701 0.113866 0.130409 0.146455 0.159931 0.167755 0.0549364 0.0690688 0.0831687 0.100184 0.11773 0.136857 0.156861 0.176207 0.192439 0.201718 0.0666425 0.0819889 0.0988965 0.118737 0.139372 0.1625 0.18651 0.209778 0.228973 0.240053 0.078386 0.0956732 0.11583 0.138581 0.16289 0.190748 0.219325 0.247061 0.269166 0.281503 0.0903535 0.110212 0.133409 0.159091 0.187791 0.22082 0.254386 0.286694 0.311264 0.32561 0.102893 0.125219 0.151119 0.180112 0.213716 0.251777 0.290604 0.327437 0.354053 0.36711 0.11333 0.137571 0.16552 0.197677 0.235559 0.277554 0.321063 0.361955 0.390643 0.405338 0.121363 0.146526 0.175873 0.210445 0.25112 0.295906 0.343571 0.389552 0.42256 0.423051 0.0134798 0.0226499 0.0337862 0.0458567 0.0572172 0.0688246 0.0796201 0.0914916 0.100837 0.108443 0.0112466 0.0211235 0.0320602 0.0439704 0.0550528 0.0664653 0.0768593 0.0885627 0.0974428 0.104524 0.00973044 0.020698 0.031959 0.0438701 0.0547066 0.0657968 0.0758927 0.0873386 0.0957326 0.10219 0.00796329 0.0194922 0.0310581 0.0430768 0.0538293 0.064702 0.0745355 0.0856352 0.0936332 0.0996785 0.0060573 0.0177681 0.0295839 0.0415861 0.0522741 0.0629764 0.0725346 0.0832051 0.0908279 0.096608 0.00418224 0.0159924 0.0280652 0.0400023 0.0505982 0.0611158 0.0703877 0.080596 0.087815 0.0933536 0.0023983 0.0143034 0.0265948 0.0385794 0.0491206 0.0594722 0.0684881 0.0783004 0.0851169 0.0904086 0.00076207 0.0126917 0.0251702 0.0372846 0.0478718 0.0581167 0.0669509 0.0764929 0.0829718 0.0880436 -0.000653231 0.0111741 0.0238527 0.036062 0.0468093 0.0570023 0.0657665 0.0751241 0.0813904 0.0862813 -0.00177452 0.00978765 0.022709 0.0349955 0.0458811 0.0560812 0.0649274 0.0740858 0.0803066 0.0850197 -0.0025404 0.00856322 0.0217928 0.0341291 0.0451216 0.0553981 0.0643567 0.0733737 0.0796579 0.0841648 -0.00294409 0.00751 0.0211112 0.0334479 0.0445668 0.0549686 0.0640337 0.0730094 0.0793826 0.0837209 -0.00302209 0.00664484 0.0206562 0.0329254 0.0442344 0.0547896 0.0639782 0.0730123 0.0794766 0.0837125 -0.002788 0.00603786 0.0204337 0.0325664 0.0441348 0.0548475 0.0642 0.0733766 0.0799414 0.0841463 -0.00239611 0.00578026 0.0204419 0.0324107 0.0442874 0.0551453 0.0647231 0.0741161 0.0807938 0.0850098 -0.00171417 0.00594222 0.020644 0.0324902 0.0446756 0.0556662 0.065529 0.0751922 0.0820105 0.0862826 -0.000733511 0.00645588 0.0210014 0.0328612 0.0453137 0.0564574 0.0666674 0.0766277 0.0836121 0.0879518 0.000205193 0.00746178 0.0214251 0.0334592 0.0460949 0.0574359 0.0680363 0.0783211 0.0855446 0.0900088 0.00113516 0.00888859 0.0220446 0.0344053 0.0471395 0.0587303 0.0697399 0.0803506 0.0878538 0.0924533 0.00179069 0.0101798 0.0222526 0.0350302 0.0478666 0.0598079 0.0712918 0.0823656 0.090366 0.0952799 0.00622301 0.0173009 0.0273333 0.0398472 0.0523985 0.0648629 0.0772363 0.0890136 0.0979059 0.103153 0.0256855 0.035183 0.044807 0.0572783 0.069571 0.0826002 0.0956661 0.107972 0.117292 0.122424 0.0433074 0.0544745 0.066055 0.0796239 0.0932332 0.107938 0.122014 0.134855 0.14395 0.148205 0.0585308 0.0714815 0.0853567 0.10086 0.117196 0.134825 0.151437 0.166452 0.176532 0.180451 0.0710827 0.0853826 0.101025 0.118575 0.137769 0.158495 0.178721 0.197743 0.21119 0.216935 0.0812062 0.096256 0.113244 0.132679 0.154371 0.178047 0.202737 0.227517 0.247601 0.258698 0.0880598 0.103896 0.121979 0.143139 0.167118 0.194037 0.224316 0.256965 0.287575 0.310559 0.0941599 0.110424 0.129498 0.152248 0.178569 0.209332 0.246566 0.290421 0.338022 0.383515 0.0960971 0.112816 0.132945 0.157228 0.186392 0.222379 0.26871 0.327609 0.400169 0.483521 0.100337 0.119037 0.141065 0.167836 0.201163 0.243938 0.300739 0.377555 0.48316 0.616828 0.00680954 0.0222026 0.0370579 0.0508406 0.0624993 0.0726964 0.0791262 0.0852904 0.087326 0.090256 0.0087083 0.0237533 0.0372527 0.0499411 0.0606959 0.0703174 0.0762167 0.082131 0.0841032 0.0870468 0.0114407 0.0271803 0.039837 0.0512853 0.060742 0.069167 0.0742498 0.0795471 0.0811805 0.0845667 0.0132408 0.0287756 0.040845 0.0515647 0.0601288 0.0676585 0.0721703 0.0769512 0.0781755 0.0817023 0.0147191 0.0292243 0.0404063 0.0505564 0.0585641 0.0655514 0.0697505 0.0742126 0.0750894 0.0784026 0.0161662 0.0295083 0.0396391 0.0491216 0.0566304 0.0631899 0.0671752 0.0714259 0.072048 0.0750051 0.0174269 0.0297405 0.0389603 0.0477442 0.0547289 0.0608521 0.0646295 0.0687041 0.0691412 0.0717859 0.0183914 0.0297356 0.0382649 0.0464206 0.0529128 0.0585982 0.0621713 0.0660979 0.0663919 0.068832 0.019066 0.0294339 0.0374268 0.0450264 0.0511083 0.0563814 0.059795 0.063593 0.0637895 0.0661029 0.0194714 0.0289055 0.0364316 0.0434973 0.0492359 0.0542138 0.0574889 0.0611428 0.0613245 0.063517 0.00725218 0.00832432 0.00933208 0.0103552 0.0112383 0.0119343 0.0124408 0.0128081 0.0131941 0.0133783 0.00759841 0.00870325 0.00970543 0.0107015 0.0115296 0.0121386 0.0125254 0.0127215 0.0128106 0.0126757 0.00779865 0.00898682 0.00998127 0.0109377 0.0116941 0.0121966 0.0124397 0.0124363 0.0122002 0.011647 0.00788285 0.00919588 0.010174 0.0110711 0.011731 0.0121029 0.0121856 0.0119925 0.0115253 0.0107243 0.00789862 0.00935713 0.0103046 0.0111163 0.0116482 0.0118593 0.0117609 0.0113781 0.0107313 0.00980718 0.00790295 0.00950057 0.0103977 0.011094 0.0114631 0.0114808 0.0111778 0.0105967 0.00978663 0.00878715 0.00795608 0.00965764 0.0104808 0.0110315 0.011207 0.0110053 0.0104803 0.00969423 0.00872184 0.00763369 0.00811767 0.00986156 0.0105862 0.0109672 0.0109305 0.0104996 0.00975192 0.00876728 0.00763823 0.00643203 0.00844177 0.0101473 0.0107521 0.0109513 0.0107015 0.0100535 0.00910487 0.00794826 0.00668324 0.00535241 0.00896137 0.0105447 0.011018 0.0110382 0.0105937 0.00976036 0.00865104 0.00736499 0.00599702 0.00456793 0.00967634 0.0110712 0.0114179 0.0112772 0.0106698 0.00969364 0.00847125 0.00710196 0.00566808 0.00418481 0.0106666 0.0117825 0.011998 0.0117114 0.0109714 0.00989085 0.0085976 0.00718413 0.00571856 0.00422234 0.0119179 0.0126829 0.0127671 0.0123499 0.0115037 0.0103467 0.00901463 0.00758562 0.00611782 0.00464378 0.0134007 0.0137643 0.0137159 0.0131755 0.0122353 0.0110273 0.00967205 0.00824485 0.00679744 0.00537007 0.0150706 0.0150006 0.014813 0.0141487 0.0131205 0.0118667 0.0104981 0.0090834 0.00767347 0.00630898 0.0168642 0.0163454 0.0160065 0.0152118 0.0140942 0.0127952 0.0114167 0.0100206 0.00866041 0.00737014 0.0186999 0.0177347 0.0172319 0.0162989 0.0150889 0.0137442 0.0123576 0.010984 0.00967985 0.00846789 0.0204863 0.0190931 0.018419 0.0173444 0.0160426 0.0146544 0.0132635 0.0119144 0.0106652 0.00954549 0.0221277 0.0203415 0.0194987 0.01829 0.0169054 0.0154813 0.0140896 0.0127562 0.0115309 0.0104882 0.0235305 0.0214032 0.0204088 0.0190887 0.0176455 0.0162058 0.0148232 0.0134926 0.0122544 0.0112951 0.0246122 0.0222102 0.0210952 0.0197023 0.0182443 0.016841 0.0155409 0.0143354 0.0132872 0.0127106 0.025309 0.0227053 0.0215105 0.0200907 0.0186625 0.0173328 0.0161396 0.015068 0.0141632 0.0136686 0.02556 0.0228442 0.0216201 0.0202221 0.0188646 0.0176381 0.0165677 0.0156325 0.01485 0.0143863 0.0253362 0.0226043 0.0214054 0.0200781 0.018831 0.0177381 0.0168134 0.016033 0.0153949 0.0150095 0.0246369 0.0219837 0.0208648 0.0196564 0.0185577 0.0176289 0.0168755 0.0162718 0.0158033 0.0155421 0.0234862 0.021 0.0200131 0.0189684 0.0180538 0.0173183 0.0167608 0.0163554 0.0160784 0.0159722 0.0219288 0.0196867 0.0188782 0.0180371 0.017338 0.0168218 0.0164829 0.0162957 0.0162309 0.0163056 0.020025 0.0180896 0.0174975 0.0168925 0.0164348 0.0161593 0.0160579 0.0161062 0.0162724 0.0165531 0.0178456 0.0162612 0.0159135 0.0155688 0.0153712 0.015352 0.0155025 0.0157998 0.0162125 0.0167226 0.0154779 0.0142617 0.0141727 0.0141017 0.0141747 0.0144206 0.0148315 0.015387 0.0160577 0.0168178 0.0130325 0.012163 0.0123284 0.0125324 0.0128765 0.0133879 0.0140612 0.0148783 0.015813 0.0168393 0.0104947 0.00998601 0.0104061 0.0108815 0.0114919 0.0122643 0.0131974 0.0142756 0.0154758 0.0167801 0.00793726 0.00778205 0.00844453 0.00917828 0.010042 0.0110634 0.0122468 0.0135795 0.0150392 0.0166252 0.00542098 0.00559565 0.00647763 0.00744748 0.00854371 0.00979474 0.0112121 0.0127865 0.0144915 0.0163485 0.00298653 0.0034595 0.00453104 0.00570764 0.00700895 0.00846389 0.0100918 0.0118898 0.0138227 0.0159147 0.000662292 0.0013997 0.0026232 0.0039727 0.00544606 0.00707372 0.00888228 0.0108774 0.0130231 0.0152959 -0.00152893 -0.000567969 0.000769443 0.00225263 0.00386094 0.00562598 0.00758295 0.00973969 0.0120472 0.0145131 -0.00357494 -0.00243242 -0.00101883 0.000555343 0.00225748 0.0041208 0.00619013 0.00847915 0.0109143 0.0135166 -0.00546967 -0.00418646 -0.00273582 -0.00111445 0.000638767 0.00255907 0.00470127 0.00709395 0.00963831 0.0123145 -0.00721094 -0.00582715 -0.00437838 -0.00275343 -0.000992572 0.000941527 0.00310977 0.00556325 0.00821005 0.0109061 -0.00880334 -0.00735649 -0.00594626 -0.00435974 -0.00263386 -0.000727947 0.00141971 0.00388593 0.00672605 0.00965041 -0.0102697 -0.00878311 -0.00744078 -0.00593007 -0.00427947 -0.00244446 -0.000367601 0.00201198 0.00478425 0.00772782 -0.0115942 -0.0101016 -0.008857 -0.00745623 -0.0059167 -0.00418989 -0.00221921 4.30047e-05 0.00268913 0.00558689 -0.012773 -0.0113112 -0.0101906 -0.00892787 -0.00752709 -0.00593473 -0.00409 -0.00194468 0.000590915 0.00341239 -0.0138064 -0.0124114 -0.0114357 -0.0103318 -0.00908905 -0.00764824 -0.00594347 -0.00392244 -0.0015 0.0012314 -0.0146927 -0.0133992 -0.0125833 -0.0116515 -0.0105779 -0.00929802 -0.00774192 -0.00585441 -0.00355624 -0.000920504 -0.0154277 -0.0142683 -0.0136211 -0.0128668 -0.011965 -0.0108468 -0.00943982 -0.00768749 -0.0055186 -0.00298106 -0.0160063 -0.0150104 -0.014534 -0.0139543 -0.0132179 -0.0122534 -0.0109871 -0.00936308 -0.00732088 -0.00487919 -0.0164227 -0.0156154 -0.0153051 -0.014889 -0.0143034 -0.0134762 -0.0123342 -0.0108247 -0.00890094 -0.00654699 -0.0166656 -0.0160694 -0.0159153 -0.0156454 -0.0151895 -0.014477 -0.0134375 -0.0120237 -0.010207 -0.00793465 -0.0167164 -0.0163506 -0.0163401 -0.016195 -0.0158434 -0.0152198 -0.0142588 -0.0129195 -0.0111966 -0.00900631 -0.0166166 -0.0164761 -0.0165829 -0.0165324 -0.016254 -0.0156898 -0.0147816 -0.0134948 -0.0118484 -0.00974912 -0.016361 -0.0164363 -0.0166328 -0.0166453 -0.0164082 -0.0158736 -0.0149941 -0.0137423 -0.0121605 -0.0101778 -0.0159514 -0.0162313 -0.0164866 -0.0165294 -0.0163018 -0.0157676 -0.0148907 -0.0136585 -0.0121368 -0.010384 -0.0154002 -0.0158714 -0.0161497 -0.0161894 -0.0159396 -0.0153772 -0.0144759 -0.0132404 -0.0117531 -0.00990444 -0.0147442 -0.0153533 -0.0156326 -0.0156368 -0.0153341 -0.0147158 -0.0137656 -0.0125042 -0.0110413 -0.00919326 -0.0139936 -0.0147054 -0.0149528 -0.0148893 -0.0145035 -0.013802 -0.0127775 -0.0114644 -0.0100049 -0.00818627 -0.0131737 -0.0139468 -0.0141308 -0.0139691 -0.0134716 -0.0126598 -0.0115336 -0.010135 -0.00864469 -0.00689136 -0.0123106 -0.0130974 -0.0131899 -0.0129027 -0.0122659 -0.0113137 -0.010048 -0.00849987 -0.0068809 -0.00519345 -0.0114274 -0.0121777 -0.0121553 -0.0117205 -0.010924 -0.00981316 -0.00839878 -0.00669054 -0.00484007 -0.00300805 -0.0105442 -0.0112067 -0.0110517 -0.0104532 -0.00947812 -0.00817619 -0.00654516 -0.00451331 -0.0019765 0.000992148 -0.00968722 -0.0102068 -0.00990478 -0.00913416 -0.00797831 -0.00649408 -0.00468971 -0.0025124 0.000151905 0.00320669 -0.0088554 -0.00918431 -0.00873177 -0.00779362 -0.00647148 -0.00483651 -0.00291505 -0.000697926 0.00186987 0.00482229 -0.0080445 -0.00814347 -0.0075454 -0.00645297 -0.0049836 -0.00322251 -0.00120485 0.0010614 0.00358257 0.00640223 -0.00724672 -0.00708579 -0.00635343 -0.0051258 -0.00353014 -0.00166263 0.000436936 0.0027578 0.00528246 0.0080223 -0.00645154 -0.00600853 -0.00515905 -0.00382053 -0.00212383 -0.000172924 0.00198659 0.00434212 0.00687124 0.00957363 -0.0056389 -0.00491261 -0.00396216 -0.00254164 -0.000774136 0.00123185 0.00342403 0.00578583 0.00829642 0.010954 -0.00479515 -0.00379613 -0.00276355 -0.00129063 0.000513749 0.00254233 0.00473719 0.00707545 0.00953883 0.0121236 -0.00390884 -0.00266276 -0.00156624 -6.96695e-05 0.00173733 0.00375455 0.00592099 0.00820605 0.0105912 0.0130788 -0.00296514 -0.00151468 -0.000373272 0.00111945 0.00289535 0.00486654 0.00697249 0.00917667 0.0114568 0.0138167 ) ; boundaryField { inlet { type zeroGradient; } outlet { type fixedValue; value uniform 0; } cylinder { type zeroGradient; } top { type symmetryPlane; } bottom { type symmetryPlane; } defaultFaces { type empty; } } // ************************************************************************* //
[ "henry.rossiter@utexas.edu" ]
henry.rossiter@utexas.edu
ec8b70af5e003fc3a1f61645655f1f20bd787347
5d329211e35808a250c21927fcbdda6a6b3254f7
/ShapeEnum.cpp
5a6fcc39684dab8e012b67da5c464b4fa26c8e6b
[]
no_license
GaganCJ/SingletonFactory
9f6ca9fb3343cc6040a45999725857ebde42aae5
f0cc0b02506e010cd22104de20fd3689de4cf5b9
refs/heads/master
2020-04-08T19:12:30.599341
2018-08-26T13:49:52
2018-08-26T13:49:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
50
cpp
enum ShapeEnum { circle, triangle, rectangle };
[ "jarenty90@o2.pl" ]
jarenty90@o2.pl
8ddd86195b04d91e63b89e33901feed08935e88f
673a92aedae0171e4054de3f4b67258b2139ebd0
/src/openflow-common.cpp
a6320bcbe5f1b83e7e464b34653f7a57867bdb7a
[ "LicenseRef-scancode-x11-stanford" ]
permissive
travelping/ofdissector
ae65ac05110291993a7dd434fa8985e569f2af09
5850f292c64306536e8c632c5ccd8f5856ffc9fe
refs/heads/master
2021-01-17T03:16:56.592813
2012-07-19T16:44:54
2012-07-19T16:44:54
7,241,831
0
0
null
null
null
null
UTF-8
C++
false
false
1,868
cpp
/* Copyright (c) 2010-2011 The Board of Trustees of The Leland Stanford Junior University */ #define OPENFLOW_INTERNAL #include <openflow-common.hpp> #include <of10/openflow-100.hpp> #include <of11/openflow-110.hpp> #include <of12/openflow-120.hpp> #include <glib.h> #include <epan/packet.h> #include <epan/ftypes/ftypes.h> static int proto_openflow = -1; static dissector_handle_t data_handle = NULL; static dissector_handle_t openflow_handle; static gint ofp = -1; static gint ofp_header = -1; void dissect_openflow (tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { if (tvb_length(tvb) < OFP_MIN_PACKET_SIZE) // This isn't openflow return; guint8 version = tvb_get_guint8(tvb, 0); switch (version) { case OFP_100_NS::gVersion: OFP_100_NS::Context->dissect(tvb, pinfo, tree); break; case OFP_110_NS::gVersion: OFP_110_NS::Context->dissect(tvb, pinfo, tree); break; case OFP_120_NS::gVersion: OFP_120_NS::Context->dissect(tvb, pinfo, tree); break; default: return; } } void proto_reg_handoff_openflow (void) { static bool initialized = false; if (!initialized) { data_handle = find_dissector("data"); openflow_handle = create_dissector_handle(dissect_openflow, proto_openflow); dissector_add("tcp.port", OFP_TCP_PORT, openflow_handle); OFP_100_NS::Context->setHandles(data_handle, openflow_handle); OFP_110_NS::Context->setHandles(data_handle, openflow_handle); OFP_120_NS::Context->setHandles(data_handle, openflow_handle); } } void proto_register_openflow (void) { proto_openflow = proto_register_protocol("OpenFlow Protocol", "OFP", "of"); OFP_100_NS::init(proto_openflow); OFP_110_NS::init(proto_openflow); OFP_120_NS::init(proto_openflow); register_dissector("openflow", dissect_openflow, proto_openflow); }
[ "allanv@cpqd.com.br" ]
allanv@cpqd.com.br
2d692ea24cd5b7bebfd83389420917de36ef758c
e730f520bad150c8a29edf805323731f89c476fc
/LOLDetour/GameFunc.cpp
b7096b719739a51cecca404f4610c895a7e0f6fc
[]
no_license
BlazingForests/LOLDetour_ch
5ee1b2d64e5c6f36e02efa52da328167bd28df19
5170ebacad7d6152b3696bae22175ef3d1a2f580
refs/heads/master
2021-01-18T09:32:20.047698
2016-04-27T09:58:36
2016-04-27T09:58:36
61,734,252
2
0
null
2016-06-22T16:25:13
2016-06-22T16:25:12
null
GB18030
C++
false
false
7,707
cpp
#include "GameProc.h" #pragma comment(lib, "version.lib") extern DWORD dwBASE_LOL; extern HWND hGame_LOL; extern HMODULE hInstance; extern CONFIG_EXE cfgEXE; BOOL bStartD3DHook; BOOL bDraw; DWORD dwBASE_MyObject=0; DWORD dwBASE_NameHook=0; DWORD dwBASE_GameTime=0; void HookHeroName(); DWORD GetMyObjectBase(){ DWORD ret; try{ if(!dwBASE_MyObject) return 0; ret=*(DWORD*)(dwBASE_MyObject); }catch(...){} return ret; } //[A-Z0-9][A-Z0-9] ->\\x\0 //[A-Z0-9] -> x BOOL InitCode(){ DWORD dwResult;DWORD TIME;BOOL bFind=TRUE; try{ //TIME=GetTickCount(); ////MyObjectBase //dwResult=SearchSignature((PBYTE)"\x56\x57\x8B\x3D\x00\x00\x00\x00\xFF\x50\x0C","xxxx????xxx",dwBASE_LOL,5); //if(dwResult){ // dwResult=*(DWORD*)(dwResult+0x4); // dwBASE_MyObject=dwResult; //}else{ // bFind=FALSE; //} //dwResult=SearchSignature((PBYTE)"\x6A\x01\x83\xEC\x08\xC7\x44\x24\x04\x00\x00\x80\x3F\xC7\x04\x24\x00\x00\x80\x3F","xxxxxxxxxxxxxxxxxxxx",dwBASE_LOL,14); //if(dwResult){ // dwBASE_NameHook=dwResult; //}else{ // bFind=FALSE; //} //dwResult=SearchSignature((PBYTE)"\x8B\x0D\x00\x00\x00\x00\x80\x79\x38\x00\x75\x1A","xx????xxxxxx",dwBASE_LOL,15); //if(dwResult){ // dwBASE_GameTime=*(DWORD*)(dwResult+0x2);//-0x16 //}else{ // bFind=FALSE; //} // //if(!bFind){ // Sleep(3000); // InitCode(); // return FALSE; //} //if(!bFind){ // Sleep(3000); // InitCode(); // return FALSE; //} //dwBASE_MyObject = dwBASE_LOL + 0x011A5414; //dwBASE_NameHook = dwBASE_LOL + 0xC5A2C1; //dwBASE_GameTime = dwBASE_LOL + 0x2E368C4; //League of Legends.exe+C5A2C1 dwBASE_MyObject = dwBASE_LOL + 0x11A5414; dwBASE_NameHook = dwBASE_LOL + 0xC5A2C1; dwBASE_GameTime = dwBASE_LOL + 0x2E368C4; CHAR szPath[MAX_PATH] = { 0 }; //DbgPrintA("[Hook]Code Init OK!"); //DbgPrintA("[Hook]MyObjectBase:%08X",dwBASE_MyObject); //DbgPrintA("[Hook]NameHook:%08X",dwBASE_NameHook); //DbgPrintA("[Hook]GameTime:%08X",dwBASE_GameTime); DbgPrintA("[Hook]%s", GetCommandLineA()); DbgPrintA("[Hook]======================================="); GetModuleFileNameA(NULL, szPath, MAX_PATH); DWORD dwSize = GetFileVersionInfoSize(szPath, NULL); LPBYTE pBlock = (BYTE*)malloc(dwSize); GetFileVersionInfoA(szPath, 0, dwSize, pBlock); char* pVerValue = NULL; UINT nlen1 = NULL; VerQueryValue(pBlock, "\\",(LPVOID*)&pVerValue,&nlen1); VS_FIXEDFILEINFO *pfixfileinfo = (VS_FIXEDFILEINFO *)pVerValue; if (HIWORD(pfixfileinfo->dwFileVersionMS) == 6 && LOWORD(pfixfileinfo->dwFileVersionMS) == 7 && HIWORD(pfixfileinfo->dwFileVersionLS) == 138 && LOWORD(pfixfileinfo->dwFileVersionLS) == 9658) HookHeroName(); else DbgPrintA("[Hook]版本失效"); }catch(...){} return TRUE; } float GetGameTime(){ float fRet; try{ __asm { mov eax, dwBASE_GameTime mov eax, [eax] mov eax, [eax + 0x2C] mov fRet,eax } return fRet; }catch(...){} } float GetSkillCoolTime(DWORD dwObject,int SkillID){ float fRet; try{ __asm{ pushad mov eax,dwObject mov ebx,SkillID lea eax,[eax+0x2450+0x518+ebx*4] mov eax,[eax] mov eax,[eax+0x14] mov fRet,eax popad } fRet=fRet-GetGameTime(); if(fRet>=0){ return fRet; }else{ return 0; } }catch(...){} } void __stdcall gDrawText(DWORD Device,OBJECT_POSITION p,WCHAR* Text,DWORD Color){ try { DWORD Param1, Param2; float x, y; Param1 = 0xFF; Param2 = Color; x = p.x; y = p.y; __asm { MOV ESI,Device MOVSS XMM1, y MOVSS XMM2, x PUSH 0x2 MOV ECX, DWORD PTR DS : [ESI + 0x18] SUB ESP, 0x8 MOV EAX, DWORD PTR DS : [ECX] MOV DWORD PTR SS : [ESP + 0x4], 0x3F800000 MOV DWORD PTR SS : [ESP], 0x3F800000 PUSH 0x3 PUSH 0x1 PUSH 0x0 PUSH 0xFF PUSH 0x00 PUSH Color PUSH Text SUB ESP, 0x0C MOVSS DWORD PTR SS : [ESP + 0x8], XMM1 MOVSS DWORD PTR SS : [ESP + 0x4], XMM2 MOV DWORD PTR SS : [ESP], 0x3F800000 CALL DWORD PTR DS : [EAX + 0x14] } } catch (...) { DbgPrintA("[Hook] DrawText Error"); } } LPVOID pHookHeroName; MEMORYINFO MEM_INFO_HERONAME; WCHAR* NEWName=L"GANK提示!请注意周围!"; BOOL bJmp = FALSE; void __stdcall DrawHeroName(DWORD POS,DWORD NAME,DWORD DEVICE,DWORD HEROBASE){ try { OBJECT_POSITION p,p2,p3; WCHAR tmp[25]; DWORD clr; float SkillTime; //DWORD dwTmp; //for (int n = 0; n <= 100; n++) { // dwTmp = *(DWORD*)(HEROBASE + 4 * n); // //DbgPrintA("[Hook]%08X %08X", HEROBASE + 4 * n, dwTmp); // if (dwTmp == GetMyObjectBase()) { // DbgPrintA("[Hook]%08X", 4 * n); // } //} bJmp = FALSE; if (IsBadReadPtr((void*)HEROBASE, 0x4)) return; if (*(DWORD*)(HEROBASE + 0x18) != 0x1401) return; bJmp = TRUE; p3.y = *(float*)POS; p3.x = *(float*)(POS + 0x4); gDrawText(DEVICE, p3, (WCHAR*)NAME, 0xFFFFFFFF); p.y= *(float*)POS + 25; p.x = *(float*)(POS + 0x4) - 85; wsprintfW(tmp, L"%d", (int)*(float*)(HEROBASE+0x154)); //wsprintfW(tmp, L"%08X", HEROBASE); gDrawText(DEVICE, p, tmp, 0xFF00FF00); if (HEROBASE != GetMyObjectBase()) { // if (GetObjectCamp(GetMyObjectBase()) == GetObjectCamp(HEROBASE)) { for (int n = 0; n < 6; n++) { p2.x = *(float*)(POS + 0x4) - 65; p2.y = *(float*)POS + 40; SkillTime = GetSkillCoolTime(HEROBASE, n); if (0 <= n && n <= 3) { DWORD clr = 0xFF00FF00; if (SkillTime > 0) { wsprintfW(tmp, L"%d", (int)(SkillTime + 1)); clr = 0xFFFF0000; } else if (n == 0) wsprintfW(tmp, L"Q"); else if (n == 1) wsprintfW(tmp, L"W"); else if (n == 2) wsprintfW(tmp, L"E"); else if (n == 3) wsprintfW(tmp, L"R"); p2.x += (n + 1) * 25; gDrawText(DEVICE, p2, tmp, clr); } else { DWORD clr = 0xFF00FF00; if (SkillTime > 0) wsprintfW(tmp, L"%d", (int)(SkillTime + 1)); else if (n == 4) wsprintfW(tmp, L"D"); else if (n == 5)wsprintfW(tmp, L"F"); if (SkillTime > 0) { clr = 0xFFFF0000; p2.x += 5; } p2.y += 15 * (n - 3) - 35; p2.x += 4 * 25 + 47; gDrawText(DEVICE, p2, tmp, clr); } } } //} } catch(...){ } } void __declspec(naked) HeroNameProc(){ __asm{ push ebp lea ebp, [esp + 0x4] pushad pushfd mov eax, [ebp + 0x98] push eax //HEROBASE push esi //DEVICE push[ebp + 0x10] //UNINAME lea eax, [ebp + 0x4] push eax //POS call DrawHeroName popfd popad pop ebp cmp bJmp, 1 je Label JMP MEM_INFO_HERONAME.lpOriginCode Label: mov eax,pHookHeroName add eax,0x54 JMP eax } } void HookHeroName(){ pHookHeroName=DetourFunc((BYTE*)dwBASE_NameHook,(BYTE*)&HeroNameProc,0x6,DETOUR_TYPE_JMP,&MEM_INFO_HERONAME); } void UnHookHeroName(){ RetourFunc(MEM_INFO_HERONAME); } float GetObjectHP_Min(DWORD ObjectBase){ float ret_f; try{ __asm{ mov eax,ObjectBase mov eax,[eax+0x154] mov ret_f,eax } return ret_f; }catch(...){ } return 0.0f; } float GetObjectHP_Max(DWORD ObjectBase){ float ret_f; try{ __asm{ mov eax,ObjectBase mov eax,[eax+0x164] mov ret_f,eax } return ret_f; }catch(...){ } return 0.0f; } int GetObjectCamp(DWORD ObjectBase){ int ret; try{ ret= *(int*)(ObjectBase+0x14); }catch(...){} return ret; } char* GetAnsiName(DWORD ObjectBase){ char* ret_char; DWORD dwAddr; try{ dwAddr=*(DWORD*)(ObjectBase+0x24); if(dwAddr==0x656A624F){ dwAddr=*(DWORD*)(ObjectBase+0x20); ret_char=(char*)dwAddr; }else{ dwAddr=ObjectBase+0x20; ret_char=(char*)dwAddr; } }catch(...){} return ret_char; } char* GetHeroName(DWORD ObjectBase){ char* ret_char; try{ __asm{ mov eax,ObjectBase mov eax,[eax+0x38] lea eax,[eax+0x1C] mov ret_char,eax }}catch(...){} return ret_char; }
[ "kevinsmail@vip.qq.com" ]
kevinsmail@vip.qq.com
104f68726f957ff48c11f4d270fc0cec7eb108de
22aa78e3809b48dd475f42ff1c6b9d7af3548405
/CPP_Primer/Cyber_Mancing_WBot/Resource_Files/utils/gen_webpage/ubc_hash.cpp
67f75348f10236ce8bce107f027a781a680bd666
[]
no_license
addisonu/Cpp_Primer
30fe8ef3a6a32bb80e18ec7125557e3ba6552a3a
69a4a3b6679c18e257c5502fb3910f2d31b36089
refs/heads/master
2021-01-01T05:49:57.844516
2017-11-16T15:36:26
2017-11-16T15:36:26
15,954,636
0
0
null
null
null
null
UTF-8
C++
false
false
10,022
cpp
// DESC : Search for urls and index words using Hash_indexer data structure // LEFT OFF // /* * adding code to generate webpage */ // BUGS // /* * relative URLs with only final part of path are duplicating last part of path which produces incorrect URLs - status [fixed] - prblem [used string function find_last_of which will search all char up to arg position, instead of find_first_of which will search all char at and after arg position] * file not being downloaded #1 - status [fixed] - problem [fstream opened in trunc mode for parse() function] * file not being downloaded #2 - status [fixed] - problem [test_download.txt file must exist] * urls with only one '/' are discarded, and others are returned from resolve_url() with extra '/' at concatenation point - status [fixed] - problem [handle the separate case where there is no overlap and entire home URL must be concatenated with relative URL] * program will terminate if page can't be downloaded - status [fixed] - problem [added exception handling code in try catch block to catch CS240Exception, bad URLs are now skipped] * no objects of type Word are being added to var words - status [fixed] - problem [some words begin with a nonalpha char and can't be hashed, hash_word() changed and condition checks string size] */ // POSSIBLE SOLUTIONS/ADDITIONS // /* */ // NOTES // /* */ #include <iostream> #include <string> #include <fstream> #include <set> #include <sstream> #include <queue> #include <map> #include "web/URLConnection.h" #include "web/CS240Exception.h" #include "../../test_pages/build_url.cpp" #include "Hash_indexer.h" #include "Word.h" std::set<std::string> parse(std::string url, std::string &page_text, Hash_indexer &words); std::map<std::string, char> page_links(std::string curr_url, std::string &page_text, Hash_indexer &words); int get_page(std::string url, std::string &page_text, Hash_indexer &words); bool has_websuffix(std::string str, std::size_t pg_pos); bool has_webprefix(std::string str); bool in_scope(std::string home_url, std::string new_url); std::set<std::string> find_url(std::fstream fs); int main() { //Resources to download and parse page //!!ADD PROPER URL BEFORE TESTING!! std::string url("http://www.bobateahouse.net"); std::string page_text = "test_download.txt"; Hash_indexer words; std::map<std::string, char> urls = page_links(url, page_text, words); std::cout << "There are " << urls.size() << " urls. Oh yeah!" << std::endl; for(std::pair<std::string, char> link : urls){ std::cout << link.first << std::endl; } words.gen_webpage(); return 0; } // PRECONDITIONS : home_url is the original URL passed to program in absolute path form // POSTCONDITIONS : return true if new_url is part website, false otherwise bool in_scope(std::string home_url, std::string new_url) { std::string location = home_url.substr(0, home_url.find("/", 7)); return new_url.find(location) == 0; } // PRECONDITIONS : str has no spaces // POSTCONDITIONS : return true if first 5 - 7 characters represent beginning of proper URL bool has_webprefix(std::string str) { //Simplify string beginning conditions to limit URLs recognized as links return (str.substr(0, 7) == "http://") || (str.substr(0, 5) == "file:"); } // PRECONDITIONS : url is the main URL of website and is the absolute path // POSTCONDITIONS : Webpage is downloaded and stored in a file specified by page_text int get_page(std::string url, std::string &page_text, Hash_indexer &words) { // Download page // //Write downloaded page to argument file std::fstream fs(page_text, std::fstream::binary | std::fstream::in | std::fstream::out); fs << std::noskipws; try{ InputStream *doc; doc = URLConnection::Open(url); while(!doc->IsDone()){ char c = doc->Read(); fs << c; } fs.close(); return 0; } catch(CS240Exception err){ std::cout << err.GetMessage() << std::endl; return -1; } } // PRECONDITIONS : pg_pos represents the '/' after http:// or file:// and immediately before the file name in it's absoluted path form // POSTCONDITIONS : true is returned if the file name has one of the following webpage file extensions, false otherwise bool has_websuffix(std::string str, std::size_t pg_pos) { //Simplify string ending conditions to limit URLs recognized as links bool end = (str.substr(pg_pos, str.length() - pg_pos - 1 ).find(".html") != std::string::npos) || (str.substr(pg_pos, str.length() - pg_pos - 1 ).find(".htm") != std::string::npos) || (str.substr(pg_pos, str.length() - pg_pos - 1 ).find(".shtml") != std::string::npos) || (str.substr(pg_pos, str.length() - pg_pos - 1 ).find(".cgi") != std::string::npos) || (str.substr(pg_pos, str.length() - pg_pos - 1 ).find(".jsp") != std::string::npos) || (str.substr(pg_pos, str.length() - pg_pos - 1 ).find(".asp") != std::string::npos) || (str.substr(pg_pos, str.length() - pg_pos - 1 ).find(".aspx") != std::string::npos) || (str.substr(pg_pos, str.length() - pg_pos - 1 ).find(".php") != std::string::npos) || (str.substr(pg_pos, str.length() - pg_pos - 1 ).find(".pl") != std::string::npos) || (str.substr(pg_pos, str.length() - pg_pos - 1 ).find(".cfm") != std::string::npos); return end; } // PRECONDITIONS : N/A // POSTCONDITIONS : Downloaded webpage is parsed and URLs and words are isolated and processed std::set<std::string> parse(std::string url, std::string &page_text, Hash_indexer &words) { // Download page // //If page isn't downloaded return an empty set, the calling function will check set size and handle as appropriate if(get_page(url, page_text, words)){ std::set<std::string> empty; return empty; } // Isolate URLs // std::fstream fs(page_text, std::fstream::binary | std::fstream::in | std::fstream::out); std::set<std::string> found_links; //Parse text to isolate tags if(fs.is_open()){ //Create variables to read text std::string str, tmp_words; // str holds tags and words holds words to be indexed unsigned char c(' '); unsigned url_cnt(0); bool in_body(false); fs << std::noskipws;//change default fstream behavior to read white space while(fs >> c){ if(c == '<'){ fs << std::skipws; while(c != '>'){ str += c; fs >> c; } str += c; //Check for words to index only between body tags if(str.find("<body>") != std::string::npos) in_body = true; else if(str == "</body>") in_body = false; //Find links std::size_t spos(0), epos(0), pg_pos(0); if(!str.empty() && (spos = str.find("ahref")) != std::string::npos){ spos = str.find("\"", spos); epos = str.find("\"", spos + 1); str = str.substr(spos, epos - spos + 1); if(str.find("/") != std::string::npos){ pg_pos = str.find_last_of("/"); } if(has_websuffix(str, pg_pos)){ //Remove quotes from str str = str.substr(1, str.size() - 2); found_links.insert(str); } str = ""; } else str = ""; fs << std::noskipws; } else if(!ispunct(c) && in_body){ if((isspace(c) || c == '\n') && !tmp_words.empty()){ if(tmp_words.size() && isalpha(tmp_words[0])) words.add(Word(tmp_words, 1, url)); tmp_words = ""; } else if(isalpha(c)){ tmp_words += c; } } } } return found_links; } // Do bfs of website // // PRECONDITIONS : N/A // POSTCONDITIONS : A breadth first search of website starting at curr_url is performed and URLs are processed std::map<std::string, char> page_links(std::string curr_url, std::string &page_text, Hash_indexer &words) { //Hold all links found on page of processed url std::set<std::string> found_links; //Hold all urls to be processed std::queue<std::string> process_links; //Track process status of url std::map<std::string, char> urls; //Prepare to process the first url before entering loop //Add code to make sure initial URL contains only location curr_url = resolve_url(curr_url, curr_url); std::cout << "curr_url = " << curr_url << '\n'; urls.insert(std::pair<std::string, char>(curr_url, 't')); process_links.push(curr_url); std::string abs_url(curr_url); //Process urls until no new ones remain while(!process_links.empty()){ found_links = parse(process_links.front(), page_text, words); //Check that initial page was downloaded if(!found_links.size()){ if(process_links.front() == curr_url){ std::cerr << "You have entered an invalid initial URL. The program will now exit." << std::endl; return urls; } else{ std::cerr << "Invalid URL" << std::endl; process_links.pop(); } } //Transfer elements from found_links to URLs and process_links std::string abs_path; for(std::string link : found_links){ abs_path = resolve_url(process_links.front(), link); if(in_scope(curr_url, abs_path)){ urls.insert(std::pair<std::string, char>(abs_path, 'f')); if(urls[abs_path] == 'f'){ process_links.push(abs_path); urls[abs_path] = 't'; } } } //Remove processed URL from process_links process_links.pop(); } return urls; }
[ "my_wireless_world@yahoo.com" ]
my_wireless_world@yahoo.com
b7cf2b5f242b6039f589a66153e5358076392f45
23470f3d6bbf520b76c1c7f39adbcbdbfdd58fd2
/app/src/main/jni/inc/NCCTemplateClassifierTraining.h
922b9428d5065f5451281de5c6e4e1b9cd42b81d
[ "BSD-3-Clause" ]
permissive
heifetz0906/Camera-Tra-UWB-Loc
6dbf07da99289dbc84154aaea0a8d0e0175d7df6
38eb4d8aadc152d099b7ebdbd83a222d5d7d524f
refs/heads/master
2021-05-10T16:59:01.951441
2018-02-15T08:21:36
2018-02-15T08:21:36
118,592,235
3
0
null
null
null
null
UTF-8
C++
false
false
3,870
h
// // /**============================================================================= @file NCCTemplateClassifierTraining.h @brief Training methods for NCCTemplateClassifier Copyright (c) 2013 Qualcomm Technologies Incorporated. All Rights Reserved Qualcomm Technologies Proprietary Export of this technology or software is regulated by the U.S. Government. Diversion contrary to U.S. law prohibited. All ideas, data and information contained in or disclosed by this document are confidential and proprietary information of Qualcomm Technologies Incorporated and all rights therein are expressly reserved. By accepting this material the recipient agrees that this material and the information contained therein are held in confidence and in trust and will not be used, copied, reproduced in whole or in part, nor its contents revealed in any manner to others without the express written permission of Qualcomm Technologies Incorporated. =============================================================================**/ #ifndef qcv_ncc_template_classifier_training_h_ #define qcv_ncc_template_classifier_training_h_ #include <cstddef> #include <vector> #include <cassert> #include "ClassifierTraining.h" #include "NCCTemplateClassifier.h" namespace qcv { /******************************************************************** Training methods for NCCTemplateClassifier ********************************************************************/ template<uint32_t _PATCH_WIDTH, uint32_t _PATCH_HEIGHT, uint32_t _MAX_NUM_POS_TMPL, uint32_t _MAX_NUM_NEG_TMPL> class NCCTemplateClassifierTraining : public ClassifierTraining<float32_t, NCCTemplateClassifierModel<_PATCH_WIDTH, _PATCH_HEIGHT, _MAX_NUM_POS_TMPL, _MAX_NUM_NEG_TMPL> > { typedef NCCTemplateClassifierModel<_PATCH_WIDTH, _PATCH_HEIGHT, _MAX_NUM_POS_TMPL, _MAX_NUM_NEG_TMPL> NCCClassifierModel; public: NCCTemplateClassifierTraining() { } //public member functions uint32_t getNumClass() const {return nccModel.getNumClass();} uint32_t getFeatureLength() const {return nccModel.getFeatureLength();} //adding training sampels only //each implmented class will decide how to accumulate the samples, but should not update the model until the update() function is called //return false if the sample is not added bool addSample(TrainingSample<float32_t> &sample) { assert(sample.featureView.getLength() == getFeatureLength() && sample.classIndex < 2); //add the positive or negative template directly to the Incremental model return nccModelInc.addTemplate(sample.featureView.getData(), sample.classIndex==1); } //update the classifier model using the added samples, returned the number of samples learned uint32_t update() { uint32_t totalSample = 0; //add the templates from the incremental model to the model for (uint32_t i=0; i< nccModelInc.sizePositiveModelPatches; i++) if (nccModel.addTemplate(nccModelInc.PositiveModelPatches[i])) totalSample++; for (uint32_t i=0; i< nccModelInc.sizeNegativeModelPatches; i++) if (nccModel.addTemplate(nccModelInc.NegativeModelPatches[i])) totalSample++; //reset the incremental nccModelInc.reset(); return totalSample; } //get the classifier model NCCClassifierModel & getClassifierModel(void) {return nccModel;} void setClassifierModel(NCCClassifierModel &model) {nccModel = model;} //reset the classifier model void resetClassifierModel(void) { nccModel.reset(); } private: //member variables NCCClassifierModel nccModel; NCCClassifierModel nccModelInc; //the incremental model for updates }; } //namespace qcvlib #endif //qcv_ncc_template_classifier_training_h_
[ "597323109@qq.com" ]
597323109@qq.com
7ec8ed98f9e88c38771033ba7060d9fd123b988f
bb014ae989a5c08da56881c76c6662461cd7785b
/src/consensus/params.h
e6a9845fb278f43b48789a025c9db4bdef9d5248
[ "MIT" ]
permissive
UN-Robotic/LVRcoin
330fac5a9d8343e34911116c8791804128280a8f
c1a2b9a542afab16184fa2ddfb28a206c36d84f5
refs/heads/master
2021-09-01T10:10:23.930384
2017-12-26T11:23:44
2017-12-26T11:23:44
115,306,520
0
0
null
null
null
null
UTF-8
C++
false
false
1,674
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Copyright (c) 2015 The Dogecoin Core developers // Copyright (c) 2017 LeVasseur // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CONSENSUS_PARAMS_H #define BITCOIN_CONSENSUS_PARAMS_H #include "uint256.h" namespace Consensus { /** * Parameters that influence chain consensus. */ struct Params { uint256 hashGenesisBlock; int nSubsidyHalvingInterval; /** Used to check majorities for block version upgrade */ int nMajorityEnforceBlockUpgrade; int nMajorityRejectBlockOutdated; int nMajorityWindow; int nCoinbaseMaturity; /** Proof of work parameters */ uint256 powLimit; bool fPowAllowMinDifficultyBlocks; int64_t nPowTargetSpacing; int64_t nPowTargetTimespan; int64_t DifficultyAdjustmentInterval() const { return nPowTargetTimespan / nPowTargetSpacing; } /** LVRcoin-specific parameters */ bool fDigishieldDifficultyCalculation; bool fPowAllowDigishieldMinDifficultyBlocks; // Allow minimum difficulty blocks where a retarget would normally occur bool fSimplifiedRewards; /** Auxpow parameters */ int16_t nAuxpowChainId; bool fAllowAuxPow; bool fStrictChainId; bool fAllowLegacyBlocks; /** Height-aware consensus parameters */ uint32_t nHeightEffective; // When these parameters come into use struct Params *pLeft; // Left hand branch struct Params *pRight; // Right hand branch }; } // namespace Consensus #endif // BITCOIN_CONSENSUS_PARAMS_H
[ "root@StockData" ]
root@StockData
928be61fda95b5a07d140e28d9c6f9703eb9c29a
e46ee69b346b72e91200efb6dc9bb513e5255811
/tests/unit_tests/test_wallet.cpp
d1947863abfea838ae279452071faff7b0248ade
[]
no_license
szenekonzept/quazarcoin
81f28ef76c759daceb63dbc5bbbf1c5730584ec5
c407468c8fc13b469c8598c202bb050353b47f16
refs/heads/master
2021-01-16T19:44:25.786927
2016-07-03T13:35:42
2016-07-03T13:35:42
20,430,079
1
0
null
2016-07-03T13:35:45
2014-06-03T04:51:00
C++
UTF-8
C++
false
false
21,638
cpp
// Copyright (c) 2012-2013 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "gtest/gtest.h" #include <future> #include <chrono> #include <array> #include "INode.h" #include "wallet/Wallet.h" #include "cryptonote_core/account.h" #include "INodeStubs.h" #include "TestBlockchainGenerator.h" class TrivialWalletObserver : public CryptoNote::IWalletObserver { public: TrivialWalletObserver() {} bool waitForSyncEnd() { auto future = syncPromise.get_future(); return future.wait_for(std::chrono::seconds(3)) == std::future_status::ready; } bool waitForSendEnd(std::error_code& ec) { auto future = sendPromise.get_future(); if (future.wait_for(std::chrono::seconds(5)) == std::future_status::timeout) { return false; } ec = future.get(); return true; } bool waitForSaveEnd(std::error_code& ec) { auto future = savePromise.get_future(); if (future.wait_for(std::chrono::seconds(5)) == std::future_status::timeout) { return false; } ec = future.get(); return true; } bool waitForLoadEnd(std::error_code& ec) { auto future = loadPromise.get_future(); if (future.wait_for(std::chrono::seconds(5)) == std::future_status::timeout) { return false; } ec = future.get(); return true; } void reset() { syncPromise = std::promise<void>(); sendPromise = std::promise<std::error_code>(); savePromise = std::promise<std::error_code>(); loadPromise = std::promise<std::error_code>(); } virtual void synchronizationProgressUpdated(uint64_t current, uint64_t total, std::error_code result) { if (result) { syncPromise.set_value(); return; } if (current == total) { syncPromise.set_value(); } } virtual void sendTransactionCompleted(CryptoNote::TransactionId transactionId, std::error_code result) { sendPromise.set_value(result); } virtual void saveCompleted(std::error_code result) { savePromise.set_value(result); } virtual void initCompleted(std::error_code result) { loadPromise.set_value(result); } virtual void actualBalanceUpdated(uint64_t actualBalance) { // std::cout << "actual balance: " << actualBalance << std::endl; } virtual void pendingBalanceUpdated(uint64_t pendingBalance) { // std::cout << "pending balance: " << pendingBalance << std::endl; } std::promise<void> syncPromise; std::promise<std::error_code> sendPromise; std::promise<std::error_code> savePromise; std::promise<std::error_code> loadPromise; }; static const uint64_t TEST_BLOCK_REWARD = 8796093022207; CryptoNote::TransactionId TransferMoney(CryptoNote::Wallet& from, CryptoNote::Wallet& to, int64_t amount, uint64_t fee, uint64_t mixIn = 0, const std::string& extra = "") { CryptoNote::Transfer transfer; transfer.amount = amount; transfer.address = to.getAddress(); return from.sendTransaction(transfer, fee, extra, mixIn); } void WaitWalletSync(TrivialWalletObserver* observer) { observer->reset(); ASSERT_TRUE(observer->waitForSyncEnd()); } void WaitWalletSend(TrivialWalletObserver* observer) { std::error_code ec; observer->reset(); ASSERT_TRUE(observer->waitForSendEnd(ec)); } void WaitWalletSend(TrivialWalletObserver* observer, std::error_code& ec) { observer->reset(); ASSERT_TRUE(observer->waitForSendEnd(ec)); } void WaitWalletSave(TrivialWalletObserver* observer) { observer->reset(); std::error_code ec; ASSERT_TRUE(observer->waitForSaveEnd(ec)); EXPECT_FALSE(ec); } class WalletApi : public ::testing::Test { public: void SetUp(); protected: void prepareAliceWallet(); void prepareBobWallet(); void prepareCarolWallet(); void GetOneBlockReward(CryptoNote::Wallet& wallet); void TestSendMoney(int64_t transferAmount, uint64_t fee, uint64_t mixIn = 0, const std::string& extra = ""); void performTransferWithErrorTx(const std::array<int64_t, 5>& amounts, uint64_t fee); TestBlockchainGenerator generator; std::shared_ptr<TrivialWalletObserver> aliceWalletObserver; std::shared_ptr<INodeTrivialRefreshStub> aliceNode; std::shared_ptr<CryptoNote::Wallet> alice; std::shared_ptr<TrivialWalletObserver> bobWalletObserver; std::shared_ptr<INodeTrivialRefreshStub> bobNode; std::shared_ptr<CryptoNote::Wallet> bob; std::shared_ptr<TrivialWalletObserver> carolWalletObserver; std::shared_ptr<INodeTrivialRefreshStub> carolNode; std::shared_ptr<CryptoNote::Wallet> carol; }; void WalletApi::SetUp() { prepareAliceWallet(); generator.generateEmptyBlocks(3); } void WalletApi::prepareAliceWallet() { aliceNode.reset(new INodeTrivialRefreshStub(generator)); aliceWalletObserver.reset(new TrivialWalletObserver()); alice.reset(new CryptoNote::Wallet(*aliceNode)); alice->addObserver(aliceWalletObserver.get()); } void WalletApi::prepareBobWallet() { bobNode.reset(new INodeTrivialRefreshStub(generator)); bobWalletObserver.reset(new TrivialWalletObserver()); bob.reset(new CryptoNote::Wallet(*bobNode)); bob->addObserver(bobWalletObserver.get()); } void WalletApi::prepareCarolWallet() { carolNode.reset(new INodeTrivialRefreshStub(generator)); carolWalletObserver.reset(new TrivialWalletObserver()); carol.reset(new CryptoNote::Wallet(*carolNode)); carol->addObserver(carolWalletObserver.get()); } void WalletApi::GetOneBlockReward(CryptoNote::Wallet& wallet) { cryptonote::account_public_address address; ASSERT_TRUE(cryptonote::get_account_address_from_str(address, wallet.getAddress())); generator.getBlockRewardForAddress(address); } void WalletApi::performTransferWithErrorTx(const std::array<int64_t, 5>& amounts, uint64_t fee) { std::vector<CryptoNote::Transfer> trs; CryptoNote::Transfer tr; tr.address = bob->getAddress(); tr.amount = amounts[0]; trs.push_back(tr); tr.address = bob->getAddress(); tr.amount = amounts[1]; trs.push_back(tr); tr.address = carol->getAddress(); tr.amount = amounts[2]; trs.push_back(tr); aliceNode->setNextTransactionError(); alice->sendTransaction(trs, fee); std::error_code result; ASSERT_NO_FATAL_FAILURE(WaitWalletSend(aliceWalletObserver.get(), result)); ASSERT_NE(result.value(), 0); trs.clear(); tr.address = bob->getAddress(); tr.amount = amounts[3]; trs.push_back(tr); tr.address = carol->getAddress(); tr.amount = amounts[4]; trs.push_back(tr); alice->sendTransaction(trs, fee); ASSERT_NO_FATAL_FAILURE(WaitWalletSend(aliceWalletObserver.get(), result)); ASSERT_EQ(result.value(), 0); } void WalletApi::TestSendMoney(int64_t transferAmount, uint64_t fee, uint64_t mixIn, const std::string& extra) { prepareBobWallet(); prepareCarolWallet(); alice->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); ASSERT_NO_FATAL_FAILURE(GetOneBlockReward(*alice)); //unblock Alice's money generator.generateEmptyBlocks(10); uint64_t expectedBalance = TEST_BLOCK_REWARD; alice->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); EXPECT_EQ(alice->pendingBalance(), expectedBalance); EXPECT_EQ(alice->actualBalance(), expectedBalance); bob->initAndGenerate("pass2"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(bobWalletObserver.get())); ASSERT_NO_FATAL_FAILURE(TransferMoney(*alice, *bob, transferAmount, fee, 0, "")); generator.generateEmptyBlocks(10); alice->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); bob->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(bobWalletObserver.get())); EXPECT_EQ(bob->pendingBalance(), transferAmount); EXPECT_EQ(bob->actualBalance(), transferAmount); EXPECT_EQ(alice->pendingBalance(), expectedBalance - transferAmount - fee); EXPECT_EQ(alice->actualBalance(), expectedBalance - transferAmount - fee); alice->shutdown(); bob->shutdown(); } void WaitWalletLoad(TrivialWalletObserver* observer, std::error_code& ec) { observer->reset(); ASSERT_TRUE(observer->waitForLoadEnd(ec)); } TEST_F(WalletApi, refreshWithMoney) { alice->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); ASSERT_EQ(alice->actualBalance(), 0); ASSERT_EQ(alice->pendingBalance(), 0); cryptonote::account_public_address address; ASSERT_TRUE(cryptonote::get_account_address_from_str(address, alice->getAddress())); generator.getBlockRewardForAddress(address); alice->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); EXPECT_EQ(alice->actualBalance(), 0); EXPECT_EQ(alice->pendingBalance(), TEST_BLOCK_REWARD); alice->shutdown(); } TEST_F(WalletApi, TransactionsAndTransfersAfterSend) { prepareBobWallet(); prepareCarolWallet(); alice->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); EXPECT_EQ(alice->getTransactionCount(), 0); EXPECT_EQ(alice->getTransferCount(), 0); ASSERT_NO_FATAL_FAILURE(GetOneBlockReward(*alice)); //unblock Alice's money generator.generateEmptyBlocks(10); alice->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); bob->initAndGenerate("pass2"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(bobWalletObserver.get())); uint64_t fee = 100000; int64_t amount1 = 1230000; ASSERT_NO_FATAL_FAILURE(TransferMoney(*alice, *bob, amount1, fee, 0)); ASSERT_NO_FATAL_FAILURE(WaitWalletSend(aliceWalletObserver.get())); int64_t amount2 = 1234500; ASSERT_NO_FATAL_FAILURE(TransferMoney(*alice, *bob, amount2, fee, 0)); ASSERT_NO_FATAL_FAILURE(WaitWalletSend(aliceWalletObserver.get())); int64_t amount3 = 1234567; ASSERT_NO_FATAL_FAILURE(TransferMoney(*alice, *bob, amount3, fee, 0)); ASSERT_NO_FATAL_FAILURE(WaitWalletSend(aliceWalletObserver.get())); carol->initAndGenerate("pass3"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(carolWalletObserver.get())); int64_t amount4 = 1020304; ASSERT_NO_FATAL_FAILURE(TransferMoney(*alice, *carol, amount4, fee, 0)); ASSERT_NO_FATAL_FAILURE(WaitWalletSend(aliceWalletObserver.get())); EXPECT_EQ(alice->getTransactionCount(), 5); CryptoNote::Transaction tx; //Transaction with id = 0 is tested in getTransactionSuccess ASSERT_TRUE(alice->getTransaction(1, tx)); EXPECT_EQ(tx.totalAmount, amount1 + fee); EXPECT_EQ(tx.fee, fee); EXPECT_EQ(tx.isCoinbase, false); EXPECT_EQ(tx.firstTransferId, 0); EXPECT_EQ(tx.transferCount, 1); ASSERT_TRUE(alice->getTransaction(2, tx)); EXPECT_EQ(tx.totalAmount, amount2 + fee); EXPECT_EQ(tx.fee, fee); EXPECT_EQ(tx.isCoinbase, false); EXPECT_EQ(tx.firstTransferId, 1); EXPECT_EQ(tx.transferCount, 1); ASSERT_TRUE(alice->getTransaction(3, tx)); EXPECT_EQ(tx.totalAmount, amount3 + fee); EXPECT_EQ(tx.fee, fee); EXPECT_EQ(tx.isCoinbase, false); EXPECT_EQ(tx.firstTransferId, 2); EXPECT_EQ(tx.transferCount, 1); ASSERT_TRUE(alice->getTransaction(4, tx)); EXPECT_EQ(tx.totalAmount, amount4 + fee); EXPECT_EQ(tx.fee, fee); EXPECT_EQ(tx.isCoinbase, false); EXPECT_EQ(tx.firstTransferId, 3); EXPECT_EQ(tx.transferCount, 1); //Now checking transfers CryptoNote::Transfer tr; ASSERT_TRUE(alice->getTransfer(0, tr)); EXPECT_EQ(tr.amount, amount1); EXPECT_EQ(tr.address, bob->getAddress()); ASSERT_TRUE(alice->getTransfer(1, tr)); EXPECT_EQ(tr.amount, amount2); EXPECT_EQ(tr.address, bob->getAddress()); ASSERT_TRUE(alice->getTransfer(2, tr)); EXPECT_EQ(tr.amount, amount3); EXPECT_EQ(tr.address, bob->getAddress()); ASSERT_TRUE(alice->getTransfer(3, tr)); EXPECT_EQ(tr.amount, amount4); EXPECT_EQ(tr.address, carol->getAddress()); EXPECT_EQ(alice->findTransactionByTransferId(0), 1); EXPECT_EQ(alice->findTransactionByTransferId(1), 2); EXPECT_EQ(alice->findTransactionByTransferId(2), 3); EXPECT_EQ(alice->findTransactionByTransferId(3), 4); alice->shutdown(); } TEST_F(WalletApi, saveAndLoadCacheDetails) { prepareBobWallet(); prepareCarolWallet(); alice->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); ASSERT_NO_FATAL_FAILURE(GetOneBlockReward(*alice)); //unblock Alice's money generator.generateEmptyBlocks(10); alice->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); bob->initAndGenerate("pass2"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(bobWalletObserver.get())); carol->initAndGenerate("pass3"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(carolWalletObserver.get())); uint64_t fee = 1000000; int64_t amount1 = 1234567; int64_t amount2 = 1020304; int64_t amount3 = 2030405; std::vector<CryptoNote::Transfer> trs; CryptoNote::Transfer tr; tr.address = bob->getAddress(); tr.amount = amount1; trs.push_back(tr); tr.address = bob->getAddress(); tr.amount = amount2; trs.push_back(tr); alice->sendTransaction(trs, fee, "", 0, 0); ASSERT_NO_FATAL_FAILURE(WaitWalletSend(aliceWalletObserver.get())); trs.clear(); tr.address = carol->getAddress(); tr.amount = amount3; trs.push_back(tr); alice->sendTransaction(trs, fee, "", 0, 0); ASSERT_NO_FATAL_FAILURE(WaitWalletSend(aliceWalletObserver.get())); std::stringstream archive; alice->save(archive, true, true); ASSERT_NO_FATAL_FAILURE(WaitWalletSave(aliceWalletObserver.get())); alice->shutdown(); prepareAliceWallet(); alice->initAndLoad(archive, "pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); ASSERT_EQ(alice->getTransactionCount(), 3); ASSERT_EQ(alice->getTransferCount(), 3); CryptoNote::Transaction tx; ASSERT_TRUE(alice->getTransaction(1, tx)); EXPECT_EQ(tx.totalAmount, amount1 + amount2 + fee); EXPECT_EQ(tx.fee, fee); EXPECT_EQ(tx.firstTransferId, 0); EXPECT_EQ(tx.transferCount, 2); ASSERT_TRUE(alice->getTransaction(2, tx)); EXPECT_EQ(tx.totalAmount, amount3 + fee); EXPECT_EQ(tx.fee, fee); EXPECT_EQ(tx.firstTransferId, 2); EXPECT_EQ(tx.transferCount, 1); ASSERT_TRUE(alice->getTransfer(0, tr)); EXPECT_EQ(tr.address, bob->getAddress()); EXPECT_EQ(tr.amount, amount1); ASSERT_TRUE(alice->getTransfer(1, tr)); EXPECT_EQ(tr.address, bob->getAddress()); EXPECT_EQ(tr.amount, amount2); ASSERT_TRUE(alice->getTransfer(2, tr)); EXPECT_EQ(tr.address, carol->getAddress()); EXPECT_EQ(tr.amount, amount3); EXPECT_EQ(alice->findTransactionByTransferId(0), 1); EXPECT_EQ(alice->findTransactionByTransferId(1), 1); EXPECT_EQ(alice->findTransactionByTransferId(2), 2); alice->shutdown(); carol->shutdown(); bob->shutdown(); } TEST_F(WalletApi, sendMoneySuccessNoMixin) { ASSERT_NO_FATAL_FAILURE(TestSendMoney(10000000, 1000000, 0)); } TEST_F(WalletApi, sendMoneySuccessWithMixin) { ASSERT_NO_FATAL_FAILURE(TestSendMoney(10000000, 1000000, 3)); } TEST_F(WalletApi, getTransactionSuccess) { alice->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); ASSERT_NO_FATAL_FAILURE(GetOneBlockReward(*alice)); alice->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); CryptoNote::Transaction tx; ASSERT_EQ(alice->getTransactionCount(), 1); ASSERT_TRUE(alice->getTransaction(0, tx)); EXPECT_EQ(tx.firstTransferId, CryptoNote::INVALID_TRANSFER_ID); EXPECT_EQ(tx.transferCount, 0); EXPECT_EQ(tx.totalAmount, TEST_BLOCK_REWARD); EXPECT_EQ(tx.fee, 0); EXPECT_EQ(tx.isCoinbase, false); alice->shutdown(); } TEST_F(WalletApi, getTransactionFailure) { alice->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); CryptoNote::Transaction tx; ASSERT_EQ(alice->getTransactionCount(), 0); ASSERT_FALSE(alice->getTransaction(0, tx)); alice->shutdown(); } TEST_F(WalletApi, useNotInitializedObject) { EXPECT_THROW(alice->pendingBalance(), std::system_error); EXPECT_THROW(alice->actualBalance(), std::system_error); EXPECT_THROW(alice->getTransactionCount(), std::system_error); EXPECT_THROW(alice->getTransferCount(), std::system_error); EXPECT_THROW(alice->getAddress(), std::system_error); std::stringstream archive; EXPECT_THROW(alice->save(archive, true, true), std::system_error); EXPECT_THROW(alice->findTransactionByTransferId(1), std::system_error); CryptoNote::Transaction tx; CryptoNote::Transfer tr; EXPECT_THROW(alice->getTransaction(1, tx), std::system_error); EXPECT_THROW(alice->getTransfer(2, tr), std::system_error); tr.address = "lslslslslslsls"; tr.amount = 1000000; EXPECT_THROW(alice->sendTransaction(tr, 300201), std::system_error); std::vector<CryptoNote::Transfer> trs; trs.push_back(tr); EXPECT_THROW(alice->sendTransaction(trs, 329293), std::system_error); } TEST_F(WalletApi, sendWrongAmount) { alice->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); CryptoNote::Transfer tr; tr.address = "1234567890qwertasdfgzxcvbyuiophjklnm"; tr.amount = 1; EXPECT_THROW(alice->sendTransaction(tr, 1), std::system_error); alice->shutdown(); } TEST_F(WalletApi, wrongPassword) { alice->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); std::stringstream archive; alice->save(archive, true, false); ASSERT_NO_FATAL_FAILURE(WaitWalletSave(aliceWalletObserver.get())); alice->shutdown(); prepareAliceWallet(); alice->initAndLoad(archive, "wrongpass"); std::error_code result; ASSERT_NO_FATAL_FAILURE(WaitWalletLoad(aliceWalletObserver.get(), result)); EXPECT_EQ(result.value(), cryptonote::error::WRONG_PASSWORD); } TEST_F(WalletApi, detachBlockchain) { alice->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); ASSERT_NO_FATAL_FAILURE(GetOneBlockReward(*alice)); generator.generateEmptyBlocks(10); alice->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); aliceNode->startAlternativeChain(3); generator.generateEmptyBlocks(10); alice->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); EXPECT_EQ(alice->actualBalance(), 0); EXPECT_EQ(alice->pendingBalance(), 0); alice->shutdown(); } TEST_F(WalletApi, saveAndLoadErroneousTxsCacheDetails) { prepareBobWallet(); prepareCarolWallet(); alice->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); ASSERT_NO_FATAL_FAILURE(GetOneBlockReward(*alice)); generator.generateEmptyBlocks(10); alice->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); bob->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(bobWalletObserver.get())); carol->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(carolWalletObserver.get())); std::array<int64_t, 5> amounts; amounts[0] = 1234567; amounts[1] = 1345678; amounts[2] = 1456789; amounts[3] = 1567890; amounts[4] = 1678901; uint64_t fee = 10000; ASSERT_NO_FATAL_FAILURE(performTransferWithErrorTx(amounts, fee)); std::stringstream archive; alice->save(archive); ASSERT_NO_FATAL_FAILURE(WaitWalletSave(aliceWalletObserver.get())); prepareAliceWallet(); alice->initAndLoad(archive, "pass"); std::error_code result; ASSERT_NO_FATAL_FAILURE(WaitWalletLoad(aliceWalletObserver.get(), result)); ASSERT_EQ(result.value(), 0); EXPECT_EQ(alice->getTransactionCount(), 2); EXPECT_EQ(alice->getTransferCount(), 2); CryptoNote::Transaction tx; ASSERT_TRUE(alice->getTransaction(1, tx)); EXPECT_EQ(tx.totalAmount, amounts[3] + amounts[4] + fee); EXPECT_EQ(tx.firstTransferId, 0); EXPECT_EQ(tx.transferCount, 2); CryptoNote::Transfer tr; ASSERT_TRUE(alice->getTransfer(0, tr)); EXPECT_EQ(tr.amount, amounts[3]); EXPECT_EQ(tr.address, bob->getAddress()); ASSERT_TRUE(alice->getTransfer(1, tr)); EXPECT_EQ(tr.amount, amounts[4]); EXPECT_EQ(tr.address, carol->getAddress()); alice->shutdown(); } TEST_F(WalletApi, saveAndLoadErroneousTxsCacheNoDetails) { prepareBobWallet(); prepareCarolWallet(); alice->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); ASSERT_NO_FATAL_FAILURE(GetOneBlockReward(*alice)); generator.generateEmptyBlocks(10); alice->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); bob->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(bobWalletObserver.get())); carol->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(carolWalletObserver.get())); std::array<int64_t, 5> amounts; amounts[0] = 1234567; amounts[1] = 1345678; amounts[2] = 1456789; amounts[3] = 1567890; amounts[4] = 1678901; uint64_t fee = 10000; ASSERT_NO_FATAL_FAILURE(performTransferWithErrorTx(amounts, fee)); std::stringstream archive; alice->save(archive, false, true); ASSERT_NO_FATAL_FAILURE(WaitWalletSave(aliceWalletObserver.get())); prepareAliceWallet(); alice->initAndLoad(archive, "pass"); std::error_code result; ASSERT_NO_FATAL_FAILURE(WaitWalletLoad(aliceWalletObserver.get(), result)); ASSERT_EQ(result.value(), 0); EXPECT_EQ(alice->getTransactionCount(), 2); EXPECT_EQ(alice->getTransferCount(), 0); CryptoNote::Transaction tx; ASSERT_TRUE(alice->getTransaction(1, tx)); EXPECT_EQ(tx.totalAmount, amounts[3] + amounts[4] + fee); EXPECT_EQ(tx.firstTransferId, CryptoNote::INVALID_TRANSFER_ID); EXPECT_EQ(tx.transferCount, 0); alice->shutdown(); }
[ "szenekonzept@googlemail.com" ]
szenekonzept@googlemail.com
68ac3b378a0321c6dc34324d0107bf90788a4178
61d48dfafbdaea578517879b1efc87f13a402598
/erge/database/databaseTest/cquery.h
a49b7828c4748eef4163eb243c4a81b5081b8eb0
[]
no_license
paulojcpinto/ERGE
f1d7f40cc3596e8767b9dac038d5e9b5de35214f
15ece235333237c966e01c104f5a24c9843bc179
refs/heads/master
2020-09-19T03:31:41.843354
2020-02-04T23:41:56
2020-02-04T23:41:56
224,195,319
0
0
null
2020-01-08T09:27:25
2019-11-26T13:10:14
C
UTF-8
C++
false
false
1,640
h
#ifndef _QUERY_H_ #define _QUERY_H_ /* This is the daemon database communication driver */ #include <pthread.h> #include <mqueue.h> #include <string> #include <string.h> #include <vector> #define MAX_MSG_LEN 10000 using namespace std; class CQuery{ public: CQuery(); ~CQuery(); bool openQueryQueue(); bool openCallbackQueue(); bool closeQueryQueue(); bool closeCallbackQueue(); bool insertRFIDQuery(const char*, const char *, bool); // RFID entity bool insertFaceQuery(const char*); // Face entity bool insertImageQuery(int, const char*); // Image entity bool deleteRFID(const char*); bool deleteFace(int); bool deleteFacePath(int); bool selectQuery(const char*, const char*, const char*, const char*); bool selectQuery(const char*, const char*, const char*, int cond); bool selectQuery(const char*, const char*); string selectQueryGetResponse(const char*, const char*, const char*, const char*); string selectQueryGetResponse(const char*, const char*, const char*, int); string selectQueryGetResponse(const char*, const char*); bool getFaceIDByRFID(int*, const char*); bool sendQuery(string); bool receiveQuery(); string getLastQueryResult(); bool getMaxID(int*, const char*, const char*); bool getMaxID(int*); vector<int> getFaceLabels(); vector<string> getFacePaths(); bool checkRFIDDuplicate(string); private: char query[MAX_MSG_LEN]; char result[MAX_MSG_LEN]; const char * msgq_query; const char * msgq_callback; mqd_t msgq_id_query; mqd_t msgq_id_callback; int fd; string messageLog; }; #endif
[ "andrecampos1998@gmail.com" ]
andrecampos1998@gmail.com
e0d91f19388f632e4c40f742de1c5d89ada0a19e
1e484767fd60a6a5faa1df53aa772b1daa5d1d28
/services/data_decoder/data_decoder_service.h
2c438cf29286b9324789d946ac90ebfdcd1b7d76
[ "BSD-3-Clause" ]
permissive
lvjianchun/chromium
a80a0d9d825dd6b02324a62253b56ed397b9662f
9d8d8ccad92ce8757385bdaf803683f847e69804
refs/heads/master
2023-03-04T16:10:28.333059
2019-06-17T15:53:33
2019-06-17T15:53:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,167
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_DATA_DECODER_DATA_DECODER_SERVICE_H_ #define SERVICES_DATA_DECODER_DATA_DECODER_SERVICE_H_ #include <memory> #include "base/macros.h" #include "services/data_decoder/public/mojom/bundled_exchanges_parser.mojom.h" #include "services/data_decoder/public/mojom/image_decoder.mojom.h" #include "services/data_decoder/public/mojom/json_parser.mojom.h" #include "services/data_decoder/public/mojom/xml_parser.mojom.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" #include "services/service_manager/public/cpp/service_keepalive.h" #include "services/service_manager/public/mojom/service.mojom.h" namespace data_decoder { class DataDecoderService : public service_manager::Service { public: DataDecoderService(); explicit DataDecoderService(service_manager::mojom::ServiceRequest request); ~DataDecoderService() override; // May be used to establish a latent Service binding for this instance. May // only be called once, and only if this instance was default-constructed. void BindRequest(service_manager::mojom::ServiceRequest request); // service_manager::Service: void OnBindInterface(const service_manager::BindSourceInfo& source_info, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe) override; private: void BindBundledExchangesParser(mojom::BundledExchangesParserRequest request); void BindImageDecoder(mojom::ImageDecoderRequest request); void BindJsonParser(mojom::JsonParserRequest request); void BindXmlParser(mojom::XmlParserRequest request); service_manager::ServiceBinding binding_{this}; service_manager::ServiceKeepalive keepalive_; service_manager::BinderRegistry registry_; DISALLOW_COPY_AND_ASSIGN(DataDecoderService); }; } // namespace data_decoder #endif // SERVICES_DATA_DECODER_DATA_DECODER_SERVICE_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
e95d027a6eace74c4fea113a394d54a4a3162e74
fcb16918dc51b85b6b531188b1b587b376f7a456
/OpenGL/Gravity Wells/Code/GravityWells/GravityWells/MySphere.cpp
c5de510f74e06aa35436446aafad3ebd82ed6ff0
[]
no_license
JamieSandell/University
a534991a2e71572f841c9d3ee443b19690deb358
472b5c6cbe5a4e6bed3e68882fa6d0fc3a231ed3
refs/heads/main
2023-03-04T00:33:57.722010
2021-02-15T13:50:24
2021-02-15T13:50:24
334,415,301
0
0
null
null
null
null
UTF-8
C++
false
false
7,019
cpp
#include "MySphere.h" #include <math.h> using std::vector; #define PI (float)3.1415926 MySphere::MySphere() { } MySphere::~MySphere() { DeallocateMemory(); } MySphere::MySphere(const MySphere &A){ CopyNonPointerDataMembers(A); CopyPointerDataMembers(A); } MySphere& MySphere::operator =(const MySphere &A){ if (&A != this){ CopyNonPointerDataMembers(A); DeallocateMemory(); AllocateMemory();// make sure the pointer members have enough space allocated for the memcpy CopyPointerDataMembers(A); } return *this; } void MySphere::AllocateMemory(void){ /*_vertexarray = new float[_vertexarraySize][3]; _normalarray = new float[_normalarraySize][3]; _indexarray = new GLuint[_indexarraySize]; _texarray = new float[_texarraySize][2]; _normalVertexArray = new GLfloat [_normalVertexArraySize][3]; _normalVertexIndexArray = new GLuint [_normalVertexIndexArraySize];*/ } void MySphere::CopyNonPointerDataMembers(const MySphere &A){ // Copy non-pointer data members //_indexarraySize = A._indexarraySize; //_normalarraySize = A._normalarraySize; //_vertexarraySize = A._vertexarraySize; _radius = A._radius; //_normalVertexIndexArraySize = A._normalVertexIndexArraySize; //_normalVertexArraySize = A._normalVertexArraySize; CopyBaseMembers(A); } void MySphere::CopyPointerDataMembers(const MySphere &A){ // C++ guarantee that elements of multidimensional arrays occupy contiguous memory addresses // this is quicker then the for-loop method // Copy pointer data members //memcpy(_vertexarray, A._vertexarray, _vertexarraySize*sizeof(float)*3);//*3 because array[][3] //memcpy(_normalarray, A._normalarray, _normalarraySize*sizeof(float)*3); //memcpy(_texarray, A._texarray, _texarraySize*sizeof(float)*2); //memcpy(_indexarray, A._indexarray, _indexarraySize*sizeof(float)); //memcpy(_normalVertexArray, A._normalVertexArray, _normalVertexArraySize*sizeof(float)*3); // *3 because array[][3] //memcpy(_normalVertexIndexArray, A._normalVertexIndexArray, _normalVertexIndexArraySize*sizeof(GLuint)); // *3 because array[][3] } void MySphere::DeallocateMemory(void){ //delete [] _vertexarray; //delete [] _normalarray; //delete [] _indexarray; //delete [] _texarray; //delete [] _normalVertexArray; //delete [] _normalVertexIndexArray; } bool MySphere::Create(){ //_vertexarraySize = 1; //_texarraySize = 1; //_normalarraySize = 1; //_indexarraySize = 1; //_normalVertexArraySize = 1; //_normalVertexIndexArraySize = 1; Create(Vector3f(0.0f, 0.0f, 0.0f), Vector3f(1.0f,1.0f,1.0f), false); return true; } bool MySphere::Create(const Vector3f &position, const Vector3f &heightWidthDepth, bool texture) { float stack_inc; float slice_inc; float x, y , z; int vertex_count; int index_count; int temp_vc; float temp_tex; float temp_rad; //_vertexarraySize = array_size; //_normalarraySize = array_size; //_indexarraySize = 2+(_stacks-1)*(_slices+1)*2; //_texarraySize = array_size; //_normalVertexIndexArraySize = array_size*2; //_normalVertexArraySize = _normalVertexIndexArraySize; AllocateMemory(); if ((_stacks < 2) & (_slices <2)) return false; stack_inc = 1.0f/(float)_stacks; slice_inc = PI*2.0f/_slices; // define the vertex array float radius = heightWidthDepth.y(); // top point vertex_count = 0; _vertexarray[vertex_count][0] = 0.0f; _vertexarray[vertex_count][1] = radius; _vertexarray[vertex_count][2] = 0.0f; _normalarray[vertex_count][0] = 0.0f; _normalarray[vertex_count][1] = 1.0f; _normalarray[vertex_count][2] = 0.0f; _texarray[vertex_count][0] = 0; _texarray[vertex_count++][1] = 1; // bottom point _vertexarray[vertex_count][0] = 0.0f; _vertexarray[vertex_count][1] = -radius; _vertexarray[vertex_count][2] = 0.0f; _normalarray[vertex_count][0] = 0.0f; _normalarray[vertex_count][1] = -1.0f; _normalarray[vertex_count][2] = 0.0f; _texarray[vertex_count][0] = 0; _texarray[vertex_count++][1] = 0; for (int i = 1; i < _stacks; i++) { y = sin(PI*(1/2.0f - stack_inc*(float)i)); temp_rad = cos(PI*(1/2.0f - stack_inc*(float)i)); temp_vc = vertex_count; temp_tex = 1.0f - stack_inc*(float)i; for(int j = 0; j < _slices; j++) { x = cos((float)j*slice_inc); z = -sin((float)j*slice_inc); _vertexarray[vertex_count][0] = radius*temp_rad*x; _vertexarray[vertex_count][1] = radius*y; _vertexarray[vertex_count][2] = radius*temp_rad*z; _normalarray[vertex_count][0] = temp_rad*x; _normalarray[vertex_count][1] = y; _normalarray[vertex_count][2] = temp_rad*z; _texarray[vertex_count][0] = (float)j/(float)_slices; _texarray[vertex_count++][1] = temp_tex; }; _vertexarray[vertex_count][0] = _vertexarray[temp_vc][0]; _vertexarray[vertex_count][1] = _vertexarray[temp_vc][1]; _vertexarray[vertex_count][2] = _vertexarray[temp_vc][2]; _normalarray[vertex_count][0] = _normalarray[temp_vc][0]; _normalarray[vertex_count][1] = _normalarray[temp_vc][1]; _normalarray[vertex_count][2] = _normalarray[temp_vc][2]; _texarray[vertex_count][0] = 1; _texarray[vertex_count++][1] = temp_tex; }; // now generate the index array // start with triangle fans for the top index_count = 0; vertex_count =2; _indexarray[index_count++] = 0; // very top vertex for(int j = 0; j<= _slices; j++) { _indexarray[index_count++] = vertex_count++; }; vertex_count -= (_slices+1); // now do the main strips for(int i = 0; i< (_stacks-2); i++) { for(int j = 0; j<= _slices; j++) { _indexarray[index_count++] = vertex_count++; _indexarray[index_count++] = _slices+vertex_count; }; }; _indexarray[index_count++] = 1; // very bottom vertex for(int j = 0; j<= _slices; j++) { _indexarray[index_count++] = vertex_count+_slices-j; }; this->SetPosition(position); this->SetTextureEnabledStatus(texture); this->SetHeightWidthDepth(heightWidthDepth); _radius = radius; return true; } void MySphere::Draw(void) const { if (GetTextureEnabledStatus()){ glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, 0, _texarray); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, GetTextureID()); } glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, 0, _normalarray); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, _vertexarray); Color _color = GetColor(); glColor4fv(GetColorFloat()); glDrawElements(GL_TRIANGLE_FAN, _slices+2, GL_UNSIGNED_INT, &_indexarray[0]); for (int i = 0; i < (_stacks-2); i++) { glDrawElements(GL_TRIANGLE_STRIP, (_slices+1)*2, GL_UNSIGNED_INT, &_indexarray[_slices+2+i*(_slices+1)*2]); }; glDrawElements(GL_TRIANGLE_FAN, _slices+2, GL_UNSIGNED_INT, &_indexarray[_slices+2+(_stacks-2)*(_slices+1)*2]); if (GetTextureEnabledStatus()){ glDisableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, 0, _texarray); glDisable(GL_TEXTURE_2D); } glDisableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, 0, _normalarray); glDisableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, _vertexarray); }
[ "jamie.sandell@outlook.com" ]
jamie.sandell@outlook.com
acb34447c7be3d9cb164c920372dbc02d0e4cd57
49506eb1eaa0f0c8663362a74c3a57941da1f41c
/Graph.cpp
1e7d0aa75b08467266bda7569924c50981c56541
[]
no_license
alal4055/Moein_CSCI2270_FinalProject
acad9921776a80f7d00e077853ad7fc0ac2d7f56
102b6e11634e6d3d9ec9ef9a958b9ebdf9d80937
refs/heads/master
2020-12-31T01:35:35.032952
2015-04-23T21:10:04
2015-04-23T21:10:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,100
cpp
// // Vertex.cpp // ReactionGenerator // // Created by Saman Moein on 4/21/15. // Copyright (c) 2015 Saman Moein. All rights reserved. // #include "Graph.h" void graph::make_adjs_av( ver * plus ) { plus->availabe = true; for( size_t i(0); i < plus->adjs.size(); i++) plus->adjs[i].toself->availabe = true; } bool graph::all_av(ver * plus) { for( size_t i(0); i < plus->adjs.size(); i++) if(!plus->adjs[i].toself->availabe && plus->adjs[i].dif_side == 0 ) return false; return true; } ver * graph::find_make_av(ver * reactors) { ver * found(nullptr); for( size_t i(0); i < vertices.size(); i++) { if( vertices[i].name == reactors->name ) { found = &vertices[i];// this should be a vector of pointers and we will add founds to the vector. found->availabe = 1; } } return found; } vector<vector<adj*>> * graph::reactionGenerator (vector<ver *> & reactors, vector<ver *> & products ) { vector<vector<adj*>> * paths = new vector<vector<adj*>>; vector<adj*> path; for( ver * reactor : reactors ) { for( ver * product : products ) { bool found(false); reactionFinder(reactor, product, *paths, found,path); if (!found) return nullptr; } } return paths; } void graph::reactionFinder( ver * reactors, ver * product,vector<vector<adj*>> & paths, bool & found,vector<adj*> & path) { ver * chem = reactors ; if(product->name == chem->name) { paths.push_back(path); path.clear(); found = true; } for( adj & A : chem->adjs ) { if (!A.visited) { A.visited = 1; if( A.toself->plus ) path.push_back(&A); if (A.dif_side == 1) { make_adjs_av(A.toself); reactionFinder(A.toself, product, paths, found,path); } else { if (A.toself->plus && all_av(A.toself)) reactionFinder(A.toself, product, paths, found,path); if(!A.toself->plus) reactionFinder(A.toself, product, paths, found,path); } } } } void graph::print_paths(vector<vector<adj*>> & paths) { int i(1); for( vector<adj*> & path : paths ) { cout << i << " :" << endl;//These can be sorted by total cost,number of reactions, change in H,S,G etc. USING A TREE. int j(1); for(adj * step : path ) { cout << " "<< j << ". "; if( step->parent->plus ) { vector<adj>::iterator rct(step->parent->adjs.begin()); for(; rct != step->parent->adjs.end()-1; rct++ ) cout << rct->toself->name << " + "; cout << rct->toself->name; } else cout << step->parent->name; cout << " --> ";//Used catalyst can be reported here: a good way to do that : A + B --Cat--> C + D if( step->toself->plus ) { vector<adj>::iterator rct(step->toself->adjs.begin()); for(; rct != step->toself->adjs.end()-1; rct++ ) cout << rct->toself->name << " + "; cout << rct->toself->name; } else cout << step->toself->name; cout << " Change in Enthalpy: " << step->H; //many other things such as change in S,G, cost etc. can be reported here. cout << endl; j++; } i++; cout << endl; // The total change in H,S,G total cost etc. can be reported here. } } void build_graph(const string & fileD) { //build graph using the file directory in the command line }
[ "samo4342@colorado.edu" ]
samo4342@colorado.edu
d619f64e147f6e551f305399e8d61bfac4cb22ff
ebcf224ed980879cc34d67a1e97f126d0f800ebe
/src/_tests/ContextTest.cpp
517ec8989843f394c88e64e2dcf2e369d65d7ac6
[ "MIT" ]
permissive
pdinges/kadm5pp
9e28dfdb4dffaddfacab50e72f70f8fdf0ac35a6
145e32226b1f6471a2220315841f6df1819092e2
refs/heads/master
2020-06-02T07:16:57.631232
2012-12-29T04:53:39
2012-12-29T16:14:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,818
cpp
/****************************************************************************** * * * Copyright (c) 2006 Peter Dinges <pdinges@acm.org> * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * 3. The name of the author may not be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * * IN NO EVENT SHALL THE AUTHOR 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. * * * *****************************************************************************/ // System libs for tests #include <stdlib.h> // Kerberos #include <krb5.h> // Local #include "../Context.hpp" #include "../Error.hpp" #include "ContextTest.hpp" CPPUNIT_TEST_SUITE_REGISTRATION (kadm5::_test::ContextTest); namespace kadm5 { namespace _test { /** * \brief * Helper class to gain access to Context's protected constructor. **/ class ContextExpose : public kadm5::Context { public: explicit ContextExpose( const string& client, const string& realm, const string& host, const int port ) : Context(client, realm, host, port) {} }; void ContextTest::testTypeConversion() { ContextExpose c("client", "REALM", "host", 42); krb5_realm r = NULL; CPPUNIT_ASSERT_MESSAGE( "Could not use Context object as krb5_context. " "(Maybe ./data/krb5.conf does not set a default_realm?)", krb5_get_default_realm(c, &r) == 0 ); free(r); } void ContextTest::testRealm() { ContextExpose c("", "", "", 0); CPPUNIT_ASSERT_MESSAGE( "Default realm is not 'TEST.LOCAL'. " "(Maybe ./data/krb5.conf has wrong default_realm?)", c.realm() == "TEST.LOCAL" ); ContextExpose c2("", "CUSTOM.REALM", "custom.kadmin.server", 0); CPPUNIT_ASSERT_MESSAGE( "Custom realm name differs from input.", c2.realm() == "CUSTOM.REALM" ); } void ContextTest::testClient() { std::string u( getenv("LOGNAME") ); // Default principal expected by KAdmind is '<currentuser>/admin'. // Note: '/admin'-context is enforced by KAdmind. ContextExpose c( "", "", "", 0 ); CPPUNIT_ASSERT_MESSAGE( "Default user is not '<currentuser>/admin'", c.client() == u + "/admin@" + c.realm() ); ContextExpose c2( "user", "", "", 0 ); CPPUNIT_ASSERT_MESSAGE( "Plain username is not returned with '/admin'-context.", c2.client() == "user/admin@" + c.realm() ); ContextExpose c3( "user/context", "", "", 0 ); CPPUNIT_ASSERT_MESSAGE( "Custom context is not overwritten with '/admin'.", c3.client() == "user/admin@" + c.realm() ); ContextExpose c4( "user@OTHER.REALM", "", "", 0 ); CPPUNIT_ASSERT_MESSAGE( "Plain username is not returned with '/admin'-context (w/ REALM).", c4.client() == "user/admin@OTHER.REALM" ); ContextExpose c5( "user/context@OTHER.REALM", "", "", 0 ); CPPUNIT_ASSERT_MESSAGE( "Custom context is not overwritten with '/admin' (w/ REALM).", c5.client() == "user/admin@OTHER.REALM" ); ContextExpose c6( "user/admin@OTHER.REALM", "", "", 0 ); CPPUNIT_ASSERT_MESSAGE( "Custom complete principal returned differs from input.", c6.client() == "user/admin@OTHER.REALM" ); } void ContextTest::testHost() { ContextExpose c("", "", "", 0); CPPUNIT_ASSERT_MESSAGE( "Default host for default realm is not '127.0.0.1'. " "(Maybe ./data/krb5.conf has wrong admin_server?)", c.host() == "127.0.0.1" ); ContextExpose c2("", "", "custom.host", 0); CPPUNIT_ASSERT_MESSAGE( "Custom host differs from input.", c2.host() == "custom.host" ); ContextExpose c3("", "", "custom.host:42", 0); CPPUNIT_ASSERT_MESSAGE( "Specifying 'host:port' as host makes returned value differ " "from 'host'.", c3.host() == "custom.host" ); // Contexts for unknown realms need to have a host specified since we // cannot guess its name. CPPUNIT_ASSERT_THROW( ContextExpose c4("", "UNKNOWN.REALM", "", 0), kadm5::bad_server ); } void ContextTest::testPort() { ContextExpose c("", "", "", 0); CPPUNIT_ASSERT_MESSAGE( "Default port for default realm not 16749. " "(Maybe ./data/krb5.conf admin_server does not specify a port?)", c.port() == 16749 ); ContextExpose c2("", "UNKNOWN.REALM", "", 0); CPPUNIT_ASSERT_MESSAGE( "Default port for unknown realm ist not 749.", c2.port() == 749 ); ContextExpose c3("", "", "", 42); CPPUNIT_ASSERT_MESSAGE( "Custom port differs from input.", c3.port() == 42 ); ContextExpose c4("", "", "host:42", 0); CPPUNIT_ASSERT_MESSAGE( "Setting port in host string does not work.", c4.port() == 42 ); // Setting a port in the hostname string overrides the other setting // (as specified in MIT's KAdmin API Documentation, Section 4.3 // "Configuration parameters" under "admin_server"). ContextExpose c5("", "", "host:42", 17); CPPUNIT_ASSERT_MESSAGE( "Setting port in host string does not override extra parameter.", c5.port() == 42 ); } } /* namespace _test */ } /* namespace kadm5 */
[ "pdinges@acm.org" ]
pdinges@acm.org
080f4c31ef587b3cf3e0ce832d42b632cb4ae842
b8180b258a6e7280096d8ef80c3fce9bad298bad
/src/cost.cpp
3b2aa1126233bea987f6140fe9abed3dc2b4eaf6
[]
no_license
khatiba/Path-Planning-Udacity
0f0b82d6f524f13ebcb573decfdf609eeb4bcac5
52a50c8f947a230a661806295aa883cb1297f06f
refs/heads/master
2021-05-09T16:59:41.744006
2018-02-05T04:57:40
2018-02-05T04:57:40
119,126,898
0
0
null
null
null
null
UTF-8
C++
false
false
1,367
cpp
#include "cost.h" #include "vehicle.h" #include "utils.h" #include <functional> #include <iterator> #include <map> #include <math.h> const double EFFICIENCY_WEIGHT = pow(10, 4); double calculate_cost(const Vehicle & vehicle, const Vehicle & trajectory, const vector<Vehicle> & predictions) { double cost = 0.0; cost += inefficiency_cost(vehicle, trajectory, predictions); return cost; } double inefficiency_cost(const Vehicle & vehicle, const Vehicle & trajectory, const vector<Vehicle> & predictions) { map<string, int> lane_direction = {{"PLCL", -1}, {"PLCR", 1}}; int final_lane = trajectory.lane; int intended_lane = trajectory.lane; if (lane_direction.find(trajectory.state) != lane_direction.end() ) { intended_lane = intended_lane + lane_direction[trajectory.state]; } vector<double> intended_kinematics = get_lane_kinematics(vehicle, intended_lane, 40.0, predictions); vector<double> final_kinematics = get_lane_kinematics(vehicle, final_lane, 40.0, predictions); double intended_speed = intended_kinematics[0]; double final_speed = final_kinematics[0]; // Don't jump between lanes if it's just slightly faster. if (abs(intended_speed - final_speed) < 1.5) { final_speed = intended_speed; } double cost = EFFICIENCY_WEIGHT * (2.0*speed_limit - intended_speed - final_speed)/speed_limit; return cost; }
[ "ackhatib@gmail.com" ]
ackhatib@gmail.com
f2204ae9db427806c203e8530cef301e2e7f2dee
aaf60acb1d2443a39895df22fdc391b702857b17
/MyTwoApplication/generated/texts/src/TypedTextDatabase.cpp
5ad8e9a107d78cb82e7162cfc413ac3cb3f611ae
[]
no_license
xinyue1007/touchgfx
fa4989ec8ddd37b86bbe0e3ba6b9d29679fc3d40
0263b5b818dfb9c0171cdfbaca4555093b73ab92
refs/heads/main
2023-05-03T21:51:16.440650
2021-05-20T05:53:08
2021-05-20T05:53:08
368,415,600
0
0
null
null
null
null
UTF-8
C++
false
false
2,720
cpp
/* DO NOT EDIT THIS FILE */ /* This file is autogenerated by the text-database code generator */ #include <touchgfx/TypedText.hpp> #include <fonts/GeneratedFont.hpp> #include <texts/TypedTextDatabase.hpp> extern touchgfx::GeneratedFont& getFont_verdana_20_4bpp(); extern touchgfx::GeneratedFont& getFont_verdana_40_4bpp(); extern touchgfx::GeneratedFont& getFont_verdana_10_4bpp(); extern touchgfx::GeneratedFont& getFont_verdana_25_4bpp(); const touchgfx::Font* touchgfx_fonts[] = { &(getFont_verdana_20_4bpp()), &(getFont_verdana_40_4bpp()), &(getFont_verdana_10_4bpp()), &(getFont_verdana_25_4bpp()) }; extern const touchgfx::TypedText::TypedTextData typedText_database_DEFAULT[]; extern const touchgfx::TypedText::TypedTextData* const typedTextDatabaseArray[]; TEXT_LOCATION_FLASH_PRAGMA const touchgfx::TypedText::TypedTextData typedText_database_DEFAULT[] TEXT_LOCATION_FLASH_ATTRIBUTE = { { 0, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 0, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 3, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 3, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 3, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR } }; TEXT_LOCATION_FLASH_PRAGMA const touchgfx::TypedText::TypedTextData* const typedTextDatabaseArray[] TEXT_LOCATION_FLASH_ATTRIBUTE = { typedText_database_DEFAULT }; namespace TypedTextDatabase { const touchgfx::TypedText::TypedTextData* getInstance(touchgfx::LanguageId id) { return typedTextDatabaseArray[id]; } uint16_t getInstanceSize() { return sizeof(typedText_database_DEFAULT) / sizeof(touchgfx::TypedText::TypedTextData); } const touchgfx::Font** getFonts() { return touchgfx_fonts; } const touchgfx::Font* setFont(touchgfx::FontId fontId, const touchgfx::Font* font) { const touchgfx::Font* old = touchgfx_fonts[fontId]; touchgfx_fonts[fontId] = font; return old; } void resetFont(touchgfx::FontId fontId) { switch (fontId) { case 0: touchgfx_fonts[0] = &(getFont_verdana_20_4bpp()); break; case 1: touchgfx_fonts[1] = &(getFont_verdana_40_4bpp()); break; case 2: touchgfx_fonts[2] = &(getFont_verdana_10_4bpp()); break; case 3: touchgfx_fonts[3] = &(getFont_verdana_25_4bpp()); break; } } } // namespace TypedTextDatabase
[ "851910295@qq.com" ]
851910295@qq.com
1f4061ec7f61e6e1370dceae295f5dc77dc071ff
81ef501be98309ef68f3f1d7311a77c2930c4117
/utilities/Histograms.cpp
bdd7ecbaa4c06d236d1e06d83e281ced2d6fe53c
[]
no_license
jsensenig/Pion_CEX_Studies
8a28020f198469966806c27e91cdb4553d6b21c4
e94eb777e6734d66f49dd04200ef868bad2c2cc9
refs/heads/main
2023-05-21T10:47:31.844835
2021-06-12T19:09:38
2021-06-12T19:09:38
375,884,818
0
0
null
null
null
null
UTF-8
C++
false
false
2,857
cpp
// // Created by Jon Sensenig on 12/5/20. // #include "Histograms.hpp" Histograms::Histograms() { ; } Histograms::~Histograms() { ; } bool Histograms::ConfigureHistos( std::string config_file ) { json conf = utils::LoadConfig( config_file ); if ( conf == nullptr ) return false; // Failed to load config json hists_1d = conf.at("1d_hists"); for ( auto & h : hists_1d ) { auto name = h.at("name").get<std::string>(); th1_hists[name] = Create1dHist( h ); } json hists_2d = conf.at("2d_hists"); for ( auto & h : hists_2d ) { auto name = h.at("name").get<std::string>(); th2_hists[name] = Create2dHist( h ); } return true; } std::unique_ptr<TH1> Histograms::Create1dHist( json & c ) { auto name = c.at( "name" ).get<std::string>(); auto type = c.at( "type" ).get<std::string>(); auto axes = c.at( "axes" ).get<std::string>(); int bins = c.at( "bins" ).get<int>(); auto u_lim = c.at( "u_lim" ).get<double>(); auto l_lim = c.at( "l_lim" ).get<double>(); if ( type == "TH1I" ) return std::make_unique<TH1I>( name.c_str(), axes.c_str(), bins, l_lim, u_lim ); else if ( type == "TH1D" ) return std::make_unique<TH1D>( name.c_str(), axes.c_str(), bins, l_lim, u_lim ); else if ( type == "TH1F" ) return std::make_unique<TH1F>( name.c_str(), axes.c_str(), bins, l_lim, u_lim ); else return nullptr; } std::unique_ptr<TH2> Histograms::Create2dHist( json & c ) { auto name = c.at( "name" ).get<std::string>(); auto type = c.at( "type" ).get<std::string>(); auto axes = c.at( "axes" ).get<std::string>(); auto xbins = c.at( "xbins" ).get<int>(); auto xu_lim = c.at( "xu_lim" ).get<double>(); auto xl_lim = c.at( "xl_lim" ).get<double>(); auto ybins = c.at( "ybins" ).get<int>(); auto yu_lim = c.at( "yu_lim" ).get<double>(); auto yl_lim = c.at( "yl_lim" ).get<double>(); if ( type == "TH2I" ) return std::make_unique<TH2I>( name.c_str(), axes.c_str(), xbins, xl_lim, xu_lim, ybins, yl_lim, yu_lim ); else if ( type == "TH2D" ) return std::make_unique<TH2D>( name.c_str(), axes.c_str(), xbins, xl_lim, xu_lim, ybins, yl_lim, yu_lim ); else if ( type == "TH2F" ) return std::make_unique<TH2F>( name.c_str(), axes.c_str(), xbins, xl_lim, xu_lim, ybins, yl_lim, yu_lim ); else return nullptr; } void Histograms::WriteHistos( TString & out_file ) { //if ( ! OpenFile( out_file ) ) return; auto ofile = std::make_unique<TFile>(out_file, "recreate"); for ( auto & h : th1_hists ) { h.second -> Write(); } for ( auto & h : th2_hists ) { h.second -> Write(); } ofile -> Close(); } bool Histograms::OpenFile( TString & out_file ) { ofile = std::make_unique<TFile>(out_file,"recreate"); if ( !ofile -> IsOpen() ) { std::cout << " Failed to open output file " << out_file << std::endl; return false; } return true; }
[ "jonsensenig17@gmail.com" ]
jonsensenig17@gmail.com
bf4139d642cf5f8af6c4efc068e527482e401bf8
a756eed9030c5afa645436412d777a1774357c70
/CP/march17q6.cpp
56a7af5dde80cd0472463bef368b8259e73ac3ed
[]
no_license
jainsourav43/DSA
fc92faa7f8e95151c8f0af4c69228d4db7e1e5ce
deb46f70a1968b44bb28389d01b35cb571a8c293
refs/heads/master
2021-05-25T09:13:42.418930
2020-06-30T07:36:56
2020-06-30T07:36:56
126,943,860
0
1
null
2020-06-30T07:36:57
2018-03-27T07:07:51
C++
UTF-8
C++
false
false
1,675
cpp
#include<iostream> #define ll long long #include<algorithm> using namespace std; bool v[100000][4][4]; int main() { ll t ; cin>>t; while(t--) { ll n,m; cin>>n>>m; char b[4]; ll i,j,k; ll a[n][4][4],q[m],l[m],r[m],pos[m]; for(i=0;i<n;i++) { for(j=0;j<4;j++) { for(k=0;k<4;k++) { cin>>a[i][j][k]; } } // cin>>b; } cout<<"sex\n"; int count[n]={0}; for(i=0;i<n;i++) { for(j=0;j<4;j++) { for(k=0;k<4;k++) { if(a[i][j][k]==1&&!v[i][j][k]) { if(((j-1)>=0&&!v[i][j-1][k])||(j-1<0)) { if(((k-1)>=0&&!v[i][j][k-1])||k-1<0) { if((((j+1)<=3)&&!v[i][j+1][k])||j+1>3) { if((((k+1)<=3)&&!v[i][j][k+1])||k+1>3) { count[i]++; } } } } if(j>0&&k>0&&j<3&&k<3) { if((k+1)<=3&&a[i][j][k+1]==1&&v[i][j][k+1]==false) { v[i][j][k+1]=true; } if((j+1)<=3&&a[i][j+1][k]==1&&v[i][j+1][k]==false) { v[i][j+1][k]=true; } if((k-1)>=0&&a[i][j][k-1]==1&&v[i][j][k-1]==false) { v[i][j][k-1]=true; } if((j-1)>=0&&a[i][j-1][k]==1&&v[i][j-1][k]==false) { v[i][j-1][k]=true; } } } } } } for(i=0;i<n;i++) { cout<<"Count for "<<" i= "<<i<< " "<<count[i]<<" "; } j=0;k=0; int u,v,w; for(i=0;i<m;i++) { cin>>q[i]; if(q[i]==1) { cin>>l[j]>>r[j]; j++; } else { cin>>pos[k]; for(int h=0;h<4;h++) { for(int h1=0;h1<4;h1++) { cin>>a[pos[k]][h][h1]; } } k++; } } } }
[ "jainsourav43@gmail.com" ]
jainsourav43@gmail.com
19f6965232477c5b5a143673f543adc3a1ca7fd7
62c3b95274990f280ed331160b6337cbd70fea36
/LatticeRepresentationLib/Niggli.cpp
9510c01512546e581dfe7a167c17142e8133f993
[]
no_license
duck10/LatticeRepLib
c10324a93e72789b7caa0b3df05fb388e5a12f7f
af45645270228d1d889effda0ae8da1c92b2b9fd
refs/heads/master
2023-09-01T15:30:11.303915
2023-08-26T23:02:39
2023-08-26T23:02:39
115,875,896
7
2
null
null
null
null
UTF-8
C++
false
false
46,314
cpp
#include "D7.h" #include "LRL_Cell.h" #include "LRL_ToString.h" #include "MatG6.h" #include "Niggli.h" #include "S6.h" #include "Selling.h" #include "StoreResults.h" #include <cfloat> #include <cmath> #include <cstdlib> #include <cstdio> #include <iostream> #include <string> //StoreResults<std::string, G6> g_store(5); /* R5 1 0 0 0 0 0 0 1 0 0 0 0 0 1 1 -s 0 0 0 -2s 0 1 0 0 0 0 0 0 1 -s 0 0 0 0 0 1 */ /* class Niggli +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ A class to implement Niggli reduction in the G6 space. Reduce returns a reduced cell and the matrix that converts the input cell to the reduced cell. Reduced(void) == constructor -- nothing to do here static void Reduce( const G6& vi, MatG6& m, G6& vout, const double delta ) == returns vout as the reduced cell of vi and m, the conversion matrix static bool NearRed( const G6& gvec, const double delta ); == determines whether gvec is reduced within delta static bool Near2Red( const G6& gvec, const double delta, G6& vout, double& dist ) == determines whether gvec is reduced within delta, and returns the reduced cell and how far from reduced static void Reporter( const std::string& text, const G6& vin, const G6& vout, const MatG6& m ) == prints information about each step in reduction (including standard presentation) private: static void MKnorm( const G6& vi, MatG6& m, G6& vout, const double delta ) == internal function to convert vi to standard presentation - the matrix to implement that change is returned +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ const bool DEBUG_REDUCER(false); size_t Niggli::m_ReductionCycleCount; //----------------------------------------------------------------------------- // Name: g6sign() // Description: returns the value of the first variable with the sign of the second /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ double g6sign(const double d, const double x) { return(x > 0.0 ? d : -d); } static void PrintG6(const std::string& text, const G6& v) { printf("%s %f %f %f %f %f %f", text.c_str(), v[0], v[1], v[2], v[3], v[4], v[5]); } static void PrintMG6_INT(const std::string& text, const MatG6& v) { for (int i = 0; i < 6; ++i) { printf("%s ", text.c_str()); for (int j = 0; j < 36; j += 6) { printf(" %3d", int(v[i + j])); } printf("\n"); } } //----------------------------------------------------------------------------- // Name: Reporter() // Description: prints out the intermediate step values and looks for // changes in the volume (indication of error) /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ void Niggli::Reporter(const std::string& text, const G6& vin, const G6& vout, const MatG6& m) { if (!DEBUG_REDUCER) return; const double volume = LRL_Cell(vout).Volume(); const double previousVolume = LRL_Cell(vin).Volume(); const bool volumeChanged = (fabs(volume - previousVolume) / std::max(volume, previousVolume)) > 1.0E-12; if (volumeChanged) { printf("**************************************************************************************\n"); } if (text.empty()) { const int i19191 = 19191; } const std::string s1 = LRL_ToString(std::string("vin ") + text.c_str() + " ", vin); const std::string s2 = LRL_ToString("vout ", vout); printf("%s\n%s\n", s1.c_str(), s2.c_str()); if (volumeChanged) { printf("\nVolume(vout) %f", volume); printf(" PREVIOUS VOLUME %f\n", previousVolume); } else { printf("\nVolume %f\n", volume); } printf("\n,%s\n", LRL_ToString("m ", m).c_str()); } // end Reporter //----------------------------------------------------------------------------- // Name: Niggli() // Description: constructor /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ Niggli::Niggli(void) { } //----------------------------------------------------------------------------- // Name: Niggli() // Description: destructor /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ Niggli::~Niggli(void) { } void Niggli::MKnormWithoutMatrices(const G6& vi, G6& vout, const double delta) { /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ // These are the matrices that can be used to convert a vector to standard // presentation. They are used in MKnorm. There are NO OTHER POSSIBILITIES. // The numbering is from Andrews and Bernstein, 1988 const static MatG6 spnull("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1"); const static MatG6 sp1("0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1"); //0,1 3,4 const static MatG6 sp2("1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0"); //1,2 4,5 const static MatG6 sp34a("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 -1 0 0 0 0 0 0 1"); // -3,-4 const static MatG6 sp34b("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1"); // -3,-5 const static MatG6 sp34c("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 -1"); // -4,-5 /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ const static MatG6 R5_Plus(" 1 0 0 0 0 0 0 1 0 0 0 0 0 1 1 -1 0 0 0 -2 0 1 0 0 0 0 0 0 1 -1 0 0 0 0 0 1"); const static MatG6 R5_Minus(" 1 0 0 0 0 0 0 1 0 0 0 0 0 1 1 +1 0 0 0 +2 0 1 0 0 0 0 0 0 1 +1 0 0 0 0 0 1"); const static MatG6 R6_Plus(" 1 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 -1 0 0 0 0 1 0 -1 -2 0 0 0 1 0 0 0 0 0 0 1"); const static MatG6 R6_Minus(" 1 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 +1 0 0 0 0 1 0 +1 +2 0 0 0 1 0 0 0 0 0 0 1"); const static MatG6 R7_Plus(" 1 0 0 0 0 0 1 1 0 0 0 -1 0 0 1 0 0 0 0 0 0 1 -1 0 0 0 0 0 1 0 -2 0 0 0 0 1"); const static MatG6 R7_Minus(" 1 0 0 0 0 0 1 1 0 0 0 +1 0 0 1 0 0 0 0 0 0 1 +1 0 0 0 0 0 1 0 +2 0 0 0 0 1"); const static MatG6 R8(" 1 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 0 2 0 1 0 1 2 0 0 0 1 1 0 0 0 0 0 1"); const static MatG6 R9_Plus(R5_Plus); const static MatG6 R9_Minus(R5_Minus); const static MatG6 R10_Plus(R6_Plus); const static MatG6 R10_Minus(R6_Minus); const static MatG6 R11_Plus(R7_Plus); const static MatG6 R11_Minus(R7_Minus); const static MatG6 R12("1 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 0 -2 0 -1 0 -1 -2 0 0 0 -1 -1 0 0 0 0 0 1"); bool again = true; m_ReductionCycleCount = 0; G6 vin; vin = vi; double& g1 = vin[0]; double& g2 = vin[1]; double& g3 = vin[2]; double& g4 = vin[3]; double& g5 = vin[4]; double& g6 = vin[5]; size_t count = 0; // assure that g1<=g2<=g3 while (again && (count < 5)) { ++count; again = false; //std::string sptext; if ((fabs(vin[0]) > fabs(vin[1]) + delta + 1.e-12 * (vin[0] + vin[1])) || (fabs(vin[0] - vin[1]) < 1.e-38 + 1.e-12 * fabs(vin[0] + vin[1]) && delta<1.0E-12 && fabs(vin[3])>fabs(vin[4]) + delta + 1.e-12 * (fabs(vin[3]) + fabs(vin[4])))) { // SP1 0,1 3,4 //mat = sp1; std::swap(g1, g2); std::swap(g4, g5); again = true; //sptext = "SP1"; //g_store.Store(sptext, vin); } else if ((fabs(vin[1]) > fabs(vin[2]) + delta + 1.e-12 * (vin[1] + vin[2])) || (fabs(vin[1] - vin[2]) < 1.e-38 + 1.e-12 * fabs(vin[1] + vin[2]) && delta<1.0E-12 && fabs(vin[4])>fabs(vin[5]) + delta + 1.e-12 * (fabs(vin[4]) + fabs(vin[5])))) { // SP2 1,2 4,5 //mat = sp2; std::swap(g2, g3); std::swap(g5, g6); again = true; //sptext = "SP2"; //g_store.Store(sptext, vin); } // DEBUG_REPORT_STRING(LRL_ToString( " MKNORM input "+sptext+" ", vi));; // DEBUG_REPORT_STRING(LRL_ToString( " MKNORM output "+sptext+" ", vout));; } // now we assure (within delta) that the vector is +++ or --- int bMinusPattern = 0; int bZeroPattern = 0; if (g4 < delta + 1.0E-13 * (g2 + g3)) bMinusPattern |= 4; if (g5 < delta + 1.0E-13 * (g1 + g3)) bMinusPattern |= 2; if (g6 < delta + 1.0E-13 * (g1 + g2)) bMinusPattern |= 1; if (fabs(g4) < delta + 1.0E-13 * (g2 + g3)) bZeroPattern |= 4; if (fabs(g5) < delta + 1.0E-13 * (g1 + g3)) bZeroPattern |= 2; if (fabs(g6) < delta + 1.0E-13 * (g1 + g2)) bZeroPattern |= 1; //std::string sptext2("Not_All_+++/---_in_MKnorm"); switch (bMinusPattern) { case 0: /* +++ */ { //mat = spnull; //sptext2 = "no_mknorm_action_sp1,sp2-0"; //g_store.Store(sptext2, vin); break; } case 1: /* ++- -> --- */ { //mat = sp34a; g4 = -g4; g5 = -g5; //sptext2 = "SP34a-1"; //g_store.Store(sptext2, vin); break; } case 2: /* +-+ -> --- */ { //mat = sp34b; g4 = -g4; g6 = -g6; //sptext2 = "SP34b-2"; //g_store.Store(sptext2, vin); break; } case 3: /* +-- -> +++, but +0- -> -0- and +-0 -> --0 and +00 -> -00 */ { if ((bZeroPattern & 2) == 2) { //mat = sp34a; g4 = -g4; g5 = -g5; //sptext2 = "SP34a-3"; //g_store.Store(sptext2, vin); break; } else if ((bZeroPattern & 1) == 1) { //mat = sp34b; //sptext2 = "SP34b-3"; g4 = -g4; g6 = -g6; //g_store.Store(sptext2, vin); break; } else { //mat = sp34c; g5 = -g5; g6 = -g6; //sptext2 = "SP34c-3"; //g_store.Store(sptext2, vin); } break; } case 4: /* -++ -> --- */ { //mat = sp34c; g5 = -g5; g6 = -g6; //sptext2 = "SP34c-4"; //g_store.Store(sptext2, vin); break; } case 5: /* -+- -> +++, but 0+- -> 0-- and -+0 -> --0 and 0+0 -> 0-0 */ { //mat = sp34b; //sptext2 = "SP34b-5"; if ((bZeroPattern & 4) == 4) { //mat = sp34a; g4 = -g4; g5 = -g5; //sptext2 = "SP34a-5"; //g_store.Store(sptext2, vin); break; } else if ((bZeroPattern & 1) == 1) { //mat = sp34c; //sptext2 = "SP34c-5a"; g5 = -g5; g6 = -g6; //g_store.Store(sptext2, vin); break; } else { //mat = sp34b; g4 = -g4; g6 = -g6; //sptext2 = "SP34b-5"; //g_store.Store(sptext2, vin); } break; } case 6: /* --+ - > +++, but 0-+ -> 0-- and -0+ - > -0- and 00+ -> 00- */ { if ((bZeroPattern & 4) == 4) { //mat = sp34b; g4 = -g4; g6 = -g6; //sptext2 = "SP34b-5"; ////g_store.Store(sptext2, vin); break; } else if ((bZeroPattern & 2) == 2) { //mat = sp34c; g5 = -g5; g6 = -g6; //sptext2 = "SP34c-5"; //g_store.Store(sptext2, vin); break; } else { //mat = sp34a; g4 = -g4; g5 = -g5; //sptext2 = "SP34a-6"; //g_store.Store(sptext2, vin); } break; } case 7: { //mat = spnull; //sptext2 = "no-mknorm_action_sp1,sp2-7"; //g_store.Store(sptext2, vin); break; } } //vout = mat * vin; vout = vin; // DEBUG_REPORT_STRING(LRL_ToString( " MKNORM input "+sptext2+" ", vi));; // DEBUG_REPORT_STRING(LRL_ToString( " MKNORM output "+sptext2+" ", vout));; //std::cout << std::flush; } //----------------------------------------------------------------------------- // Name: MKnorm() // Description: changes a G6 vector to standard presentation (often called // normalization in the literature) and returns the standard // vector and the matrix that changes the input vector to the // standard one /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ void Niggli::MKnorm(const G6& vi, MatG6& m, G6& vout, const double delta) { /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ // These are the matrices that can be used to convert a vector to standard // presentation. They are used in MKnorm. There are NO OTHER POSSIBILITIES. // The numbering is from Andrews and Bernstein, 1988 const static MatG6 spnull("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1"); const static MatG6 sp1("0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1"); const static MatG6 sp2("1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0"); const static MatG6 sp34a("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 -1 0 0 0 0 0 0 1"); const static MatG6 sp34b("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1"); const static MatG6 sp34c("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 -1"); /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ const static MatG6 R5_Plus(" 1 0 0 0 0 0 0 1 0 0 0 0 0 1 1 -1 0 0 0 -2 0 1 0 0 0 0 0 0 1 -1 0 0 0 0 0 1"); const static MatG6 R5_Minus(" 1 0 0 0 0 0 0 1 0 0 0 0 0 1 1 +1 0 0 0 +2 0 1 0 0 0 0 0 0 1 +1 0 0 0 0 0 1"); const static MatG6 R6_Plus(" 1 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 -1 0 0 0 0 1 0 -1 -2 0 0 0 1 0 0 0 0 0 0 1"); const static MatG6 R6_Minus(" 1 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 +1 0 0 0 0 1 0 +1 +2 0 0 0 1 0 0 0 0 0 0 1"); const static MatG6 R7_Plus(" 1 0 0 0 0 0 1 1 0 0 0 -1 0 0 1 0 0 0 0 0 0 1 -1 0 0 0 0 0 1 0 -2 0 0 0 0 1"); const static MatG6 R7_Minus(" 1 0 0 0 0 0 1 1 0 0 0 +1 0 0 1 0 0 0 0 0 0 1 +1 0 0 0 0 0 1 0 +2 0 0 0 0 1"); const static MatG6 R8(" 1 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 0 2 0 1 0 1 2 0 0 0 1 1 0 0 0 0 0 1"); const static MatG6 R9_Plus(R5_Plus); const static MatG6 R9_Minus(R5_Minus); const static MatG6 R10_Plus(R6_Plus); const static MatG6 R10_Minus(R6_Minus); const static MatG6 R11_Plus(R7_Plus); const static MatG6 R11_Minus(R7_Minus); //const MatG6 R12(R8); const static MatG6 R12("1 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 0 -2 0 -1 0 -1 -2 0 0 0 -1 -1 0 0 0 0 0 1"); bool again = true; int mkCycleCount = 0; MatG6 mat = MatG6::Eye(); MatG6 accumulator = mat; G6 vin; m = MatG6::Eye(); vin = vi; // assure that g1<=g2<=g3 while (again && (mkCycleCount <= 5)) { ++mkCycleCount = 0; again = false; std::string sptext; if ((fabs(vin[0]) > fabs(vin[1]) + delta + 1.e-12 * (vin[0] + vin[1])) || (fabs(vin[0] - vin[1]) < 1.e-38 + 1.e-12 * fabs(vin[0] + vin[1]) && delta<1.0E-12 && fabs(vin[3])>fabs(vin[4]) + delta + 1.e-12 * (fabs(vin[3]) + fabs(vin[4])))) { // SP1 mat = sp1; accumulator = mat * accumulator; again = true; sptext = "SP1"; } else if ((fabs(vin[1]) > fabs(vin[2]) + delta + 1.e-12 * (vin[1] + vin[2])) || (fabs(vin[1] - vin[2]) < 1.e-38 + 1.e-12 * fabs(vin[1] + vin[2]) && delta<1.0E-12 && fabs(vin[4])>fabs(vin[5]) + delta + 1.e-12 * (fabs(vin[4]) + fabs(vin[5])))) { // SP2 mat = sp2; accumulator = mat * accumulator; again = true; sptext = "SP2"; } if (again) { // Accumulate the total transformation from the input vector into vout and // the total transformation itself into matrix m. const MatG6 mtemp = mat * m; m = mtemp; vout = mat * vin; Reporter(sptext, vin, vout, mat); vin = vout; } // DEBUG_REPORT_STRING(LRL_ToString( " MKNORM input "+sptext+" ", vi));; // DEBUG_REPORT_STRING(LRL_ToString( " MKNORM output "+sptext+" ", vout));; } // now we assure (within delta) that the vector is +++ or --- int bMinusPattern = 0; int bZeroPattern = 0; if (vin[3] < delta + 1.0E-13 * (vin[1] + vin[2])) bMinusPattern |= 4; if (vin[4] < delta + 1.0E-13 * (vin[0] + vin[2])) bMinusPattern |= 2; if (vin[5] < delta + 1.0E-13 * (vin[0] + vin[1])) bMinusPattern |= 1; if (fabs(vin[3]) < delta + 1.0E-13 * (vin[1] + vin[2])) bZeroPattern |= 4; if (fabs(vin[4]) < delta + 1.0E-13 * (vin[0] + vin[2])) bZeroPattern |= 2; if (fabs(vin[5]) < delta + 1.0E-13 * (vin[0] + vin[1])) bZeroPattern |= 1; std::string sptext2("Not_All_++ + / -- - _in_MKnorm"); switch (bMinusPattern) { case 0: /* +++ */ { mat = spnull; accumulator = mat * accumulator; sptext2 = "no_mknorm_action_sp1,sp2-0"; break; } case 1: /* ++- -> --- */ { mat = sp34a; accumulator = mat * accumulator; sptext2 = "SP34a-1"; break; } case 2: /* +-+ -> --- */ { mat = sp34b; accumulator = mat * accumulator; sptext2 = "SP34b-2"; break; } case 3: /* +-- -> +++, but +0- -> -0- and +-0 -> --0 and +00 -> -00 */ { mat = sp34c; accumulator = mat * accumulator; sptext2 = "SP34c-3"; if ((bZeroPattern & 2) == 2) { mat = sp34a; accumulator = mat * accumulator; sptext2 = "SP34a-3"; break; } if ((bZeroPattern & 1) == 1) { mat = sp34b; accumulator = mat * accumulator; sptext2 = "SP34b-3"; break; } break; } case 4: /* -++ -> --- */ { mat = sp34c; accumulator = mat * accumulator; sptext2 = "SP34c-4"; break; } case 5: /* -+- -> +++, but 0+- -> 0-- and -+0 -> --0 and 0+0 -> 0-0 */ { mat = sp34b; accumulator = mat * accumulator; sptext2 = "SP34b-5"; if ((bZeroPattern & 4) == 4) { mat = sp34a; accumulator = mat * accumulator; sptext2 = "SP34a-5"; break; } if ((bZeroPattern & 1) == 1) { mat = sp34c; accumulator = mat * accumulator; sptext2 = "SP34c-5"; break; } break; } case 6: /* --+ - > +++, but 0-+ -> 0-- and -0+ - > -0- and 00+ -> 00- */ { mat = sp34a; accumulator = mat * accumulator; sptext2 = "SP34a-6"; if ((bZeroPattern & 4) == 4) { mat = sp34b; accumulator = mat * accumulator; sptext2 = "SP34b-5"; break; } if ((bZeroPattern & 2) == 2) { mat = sp34c; accumulator = mat * accumulator; sptext2 = "SP34c-5"; break; } break; } case 7: { mat = spnull; accumulator = mat * accumulator; sptext2 = "no_mknorm_action_sp1,sp2-7"; break; } } // Accumulate the total transformation from the input vector into vout and // the total transformation itself into matrix m. vout = mat * vin; // DEBUG_REPORT_STRING(LRL_ToString( " MKNORM input "+sptext2+" ", vi));; // DEBUG_REPORT_STRING(LRL_ToString( " MKNORM output "+sptext2+" ", vout));; //std::cout << std::flush; Reporter(sptext2, vin, vout, accumulator); } // end MKnorm bool Niggli::Reduce(const G6& vi, G6& vout) { const bool b = Selling::Reduce(vi, vout); return ReduceWithoutMatrices(vout, vout, 0.0); } bool Niggli::Reduce(const G6& vi, G6& vout, const bool sellingFirst) { if (IsNiggli(vi)) { vout = vi; return true; } S6 s6out; bool b = true; if (sellingFirst) { b = Selling::Reduce(S6(vi), s6out); vout = D7(s6out); } else { vout = vi; } if (!b) { MatG6 m; const bool bniggli = Niggli::Reduce(vi, m, vout, 0.0); return bniggli; } else if (IsNiggli(vout)) { return true; } else { MatG6 m; return Niggli::Reduce(vi, m, vout, 0.0); } } bool Niggli::ReduceWithoutMatrices(const G6& vi, G6& vout, const double delta) { if (Niggli::IsNiggli(vi)) { vout = vi; return true; } /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ // These are the matrices that can be used to convert a vector to standard // presentation. They are used in MKnorm. There are NO OTHER POSSIBILITIES. // The numbering is from Andrews and Bernstein, 1988 const static MatG6 spnull("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1"); const static MatG6 sp1("0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1"); const static MatG6 sp2("1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0"); const static MatG6 sp34a("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 -1 0 0 0 0 0 0 1"); const static MatG6 sp34b("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1"); const static MatG6 sp34c("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 -1"); /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ const static MatG6 R5_Plus(" 1 0 0 0 0 0 0 1 0 0 0 0 0 1 1 -1 0 0 0 -2 0 1 0 0 0 0 0 0 1 -1 0 0 0 0 0 1"); const static MatG6 R5_Minus(" 1 0 0 0 0 0 0 1 0 0 0 0 0 1 1 +1 0 0 0 +2 0 1 0 0 0 0 0 0 1 +1 0 0 0 0 0 1"); const static MatG6 R6_Plus(" 1 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 -1 0 0 0 0 1 0 -1 -2 0 0 0 1 0 0 0 0 0 0 1"); const static MatG6 R6_Minus(" 1 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 +1 0 0 0 0 1 0 +1 +2 0 0 0 1 0 0 0 0 0 0 1"); const static MatG6 R7_Plus(" 1 0 0 0 0 0 1 1 0 0 0 -1 0 0 1 0 0 0 0 0 0 1 -1 0 0 0 0 0 1 0 -2 0 0 0 0 1"); const static MatG6 R7_Minus(" 1 0 0 0 0 0 1 1 0 0 0 +1 0 0 1 0 0 0 0 0 0 1 +1 0 0 0 0 0 1 0 +2 0 0 0 0 1"); const static MatG6 R8(" 1 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 0 2 0 1 0 1 2 0 0 0 1 1 0 0 0 0 0 1"); const static MatG6 R9_Plus(R5_Plus); const static MatG6 R9_Minus(R5_Minus); const static MatG6 R10_Plus(R6_Plus); const static MatG6 R10_Minus(R6_Minus); const static MatG6 R11_Plus(R7_Plus); const static MatG6 R11_Minus(R7_Minus); //const MatG6 R12(R8); const static MatG6 R12("1 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 0 -2 0 -1 0 -1 -2 0 0 0 -1 -1 0 0 0 0 0 1"); G6 vin; size_t reduceCycleCount = 0; bool again = true; const bool debug = true; const int maxCycle = 1000; vin = vi; G6 voutPrev(vin); /* Mapping from Fortran indices: 1 2 3 4 5 6 0 6 12 18 24 30 7 8 9 10 11 12 1 7 13 19 25 31 13 14 15 16 17 18 2 8 14 20 26 32 19 20 21 22 23 24 3 9 15 21 27 33 25 26 27 28 29 30 4 10 16 22 28 34 31 32 33 34 35 36 5 11 17 23 29 35 */ // Try some number of times to reduce the input vector and accumulate // the changing vector and total transformation matrix // The limit on the number of cycles is because (whether because of // floating point rounding or algorithm issues) there might be a // case of an infinite loop. The designations R5-R12 are from double& g1 = vout[0]; double& g2 = vout[1]; double& g3 = vout[2]; double& g4 = vout[3]; double& g5 = vout[4]; double& g6 = vout[5]; // Andrews and Bernstein, 1988 MKnormWithoutMatrices(vin, vout, delta); while (again && reduceCycleCount < maxCycle) { // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE start cycle ", ncycle, " ", vin));; vin = vout; if (fabs(g4) > fabs(g2) + delta) { // R5 //const MatG6 m1 =(vin[3] <= 0.0) ? R5_Minus : R5_Plus; again = true; //// DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R5-m1\n", m1,"\n"));; //vout = m1 * vin; if (g4 <= 0.0) { g3 = g2 + g3 + g4; // R5_Minus & R9_Minus g4 = 2 * g2 + g4; g5 = g5 + g6; //g_store.Store("R5_Minus", vin); } else { g3 = g2 + g3 - g4; // R5_Plus & R9_Plus g4 = -2 * g2 + g4; g5 = g5 - g6; //g_store.Store("R5_Plus", vin); } } else if (fabs(g5) > fabs(g1) + delta) { // R6 //const MatG6 m1 =(vin[4] <= 0.0) ? R6_Minus : R6_Plus; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R6-m1\n", m1,"\n"));; //vout = m1 * vin; if (g5 <= 0.0) { g3 = g1 + g3 + g5; // R6_Minus & R10_Minus g4 = g4 + g6; g5 = 2 * g1 + g5; //g_store.Store("R6_Minus", vin); } else { g3 = g1 + g3 - g5; // R6_Plus & R10_Plus g4 = g4 - g6; //g_store.Store("R6_Plus", vin); g5 = -2 * g1 + g5; } } else if (fabs(g6) > fabs(g1) + delta) { // R7 //const MatG6 m1 =(vin[5] <= 0.0) ? R7_Minus : R7_Plus; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R7-m1\n", m1,"\n"));; //vout = m1 * vin; if (g6 <= 0.0) { g2 = g1 + g2 + g6; // R7_Minus & R11_Minus g4 = g4 + g5; g6 = 2 * g1 + g6; //g_store.Store("R7_Minus", vin); } else { g2 = g1 + g2 - g6; // R7_Plus && R11_Plus g4 = g4 - g5; g6 = -2 * g1 + g6; //g_store.Store("R7_Plus", vin); } } else if (g4 + g5 + g6 + fabs(g1) + fabs(g2) + delta < 0.0) { //R8 //const MatG6 m1 = R8; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R8-m1\n", m1,"\n"));; //vout = m1 * vin; g3 = g1 + g2 + g3 + g4 + g5 + g6; // R8 g4 = 2 * g2 + g4 + g6; g5 = 2 * g1 + g5 + g6; //g_store.Store("R8", vin); } else if ((fabs(g4 - g2) <= delta && 2.0 * g5 - delta < g6) || (fabs(g4 + g2) <= delta && g6 < 0.0)) { // R9 There is an error in the paper says "2g5<g5" should be "2g5<g6" //const MatG6 m1 =(vin[3] <= 0.0) ? R9_Minus : R9_Plus; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R9-m1\n", m1,"\n"));; //vout = m1 * vin; if (g4 <= 0.0) { g3 = g2 + g3 + g4; // R5_Minus & R9_Minus g4 = 2 * g2 + g4; g5 = g5 + g6; //g_store.Store("R9_Minus", vin); } else { g3 = g2 + g3 - g4; // R5_Plus & R9_Plus g4 = -2 * g2 + g4; g5 = g5 - g6; //g_store.Store("R9_Plus", vin); } } else if ((fabs(g5 - g1) <= delta && 2.0 * g4 - delta < g6) || (fabs(g5 + g1) <= delta && g6 < 0.0)) { //R10 (LAST=15 in ITERATE) //const MatG6 m1 =(vin[4] <= 0.0) ? R10_Minus : R10_Plus; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R10-m\n", m,"\n")); // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R10-m1\n", m1,"\n")); // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R10-m2=m1*m\n", m2,"\n")); //vout = m1 * vin; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R10-in ", vin)); // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R10-out ", vout)) if (g5 <= 0.0) { g3 = g1 + g3 + g5; // R6_Minus & R10_Minus g4 = g4 + g6; g5 = 2 * g1 + g5; //g_store.Store("R10_Minus", vin); } else { g3 = g1 + g3 - g5; // R6_Plus & R10_Plus g4 = g4 - g6; g5 = -2 * g1 + g5; //g_store.Store("R10_Plus", vin); } } else if ((fabs(g6 - g1) <= delta && 2.0 * g4 - delta < g5) || (fabs(g6 + g1) <= delta && g5 < 0.0)) // paper says g6<0, but it seems wrong { // R11 //const MatG6 m1 =(vin[5] <= 0.0) ? R11_Minus : R11_Plus; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE 1-m1\n", m1,"\n"));; //vout = m1 * vin; if (g6 <= 0.0) { g2 = g1 + g2 + g6; // R7_Minus & R11_Minus g4 = g4 + g5; g6 = 2 * g1 + g6; //g_store.Store("R11_Minus", vin); } else { g2 = g1 + g2 - g6; // R7_Plus && R11_Plus g4 = g4 - g5; g6 = -2 * g1 + g6; //g_store.Store("R11_Plus", vin); } } else if (fabs(g4 + g5 + g6 + fabs(g1) + fabs(g2)) <= delta && (2.0 * (fabs(g1) + g5) + g6 > delta)) { //R12 //const MatG6 m1 =R12; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R12-m1\n", m1,"\n"));; //vout = m1 * vin; g3 = g1 + g2 + g3 + g4 + g5 + g6; // R12 g4 = -2 * g2 - g4 - g6; g5 = -2 * g1 - g5 - g6; //g_store.Store("R12", vin); } else { again = false; vout = vin; } // probably don't need to do this group of code when again==false !!!!!!!!!!!!!! if (again) { MKnormWithoutMatrices(vout, vin, delta); vout = vin; } for (size_t i = 3; i < 6; ++i) if (std::fabs(vin[i]) < 1.0E-10) vin[i] = 0.0; if (vin[0] < 0.0 || vin[1] < 0.0 || vin[2] < 0.0) { // ERROR ERROR ERROR if (DEBUG_REDUCER) { fprintf(stderr, " Negative sq, axis %d \n", (int)(reduceCycleCount)); fprintf(stderr, " vin: [%g,%g,%g,%g,%g,%g]\n", vin[0], vin[1], vin[2], vin[3], vin[4], vin[5]); fprintf(stderr, " vi: [%g,%g,%g,%g,%g,%g]\n", vi[0], vi[1], vi[2], vi[3], vi[4], vi[5]); } return(false); } if (reduceCycleCount == 0) voutPrev = vin; if (DEBUG_REDUCER) { //printf( "%d %f %f %f %f %f %f\n", m_ReductionCycleCount, vout[0], vout[1], vout[2], vout[3], vout[4], vout[5] ); } // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE output ", vi));; // if (reduceCycleCount > 250) { // std::cout << std::endl; // std::cout << "cycle " << reduceCycleCount << std::endl; // std::cout << "\tvin " << vin << std::endl; // std::cout << "\tvout " << vout << std::endl; // } ++reduceCycleCount; } bool isNearReduced = Niggli::NearRed(vout, delta); if (reduceCycleCount >= maxCycle) { if (isNearReduced) { std::cout << "THERE IS A REDUCE PROBLEM, m_ReductionCycleCount " << reduceCycleCount << std::endl; } } m_ReductionCycleCount = reduceCycleCount; return (reduceCycleCount <= maxCycle) || isNearReduced; } //----------------------------------------------------------------------------- // Name: Reduce() // Description: performs Niggli reduction and returns the standard reduced // vector and the matrix that changes the input vector to the // reduced one /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ bool Niggli::Reduce(const G6& vi, MatG6& m, G6& vout, const double delta) { MatG6 accumulator = MatG6::Eye(); if (IsNiggli(vi)) { vout = vi; return true; } /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ // These are the matrices that can be used to convert a vector to standard // presentation. They are used in MKnorm. There are NO OTHER POSSIBILITIES. // The numbering is from Andrews and Bernstein, 1988 const static MatG6 spnull("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1"); const static MatG6 sp1("0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1"); const static MatG6 sp2("1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0"); const static MatG6 sp34a("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 -1 0 0 0 0 0 0 1"); const static MatG6 sp34b("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1"); const static MatG6 sp34c("1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 -1"); /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ const static MatG6 R5_Plus(" 1 0 0 0 0 0 0 1 0 0 0 0 0 1 1 -1 0 0 0 -2 0 1 0 0 0 0 0 0 1 -1 0 0 0 0 0 1"); const static MatG6 R5_Minus(" 1 0 0 0 0 0 0 1 0 0 0 0 0 1 1 +1 0 0 0 +2 0 1 0 0 0 0 0 0 1 +1 0 0 0 0 0 1"); const static MatG6 R6_Plus(" 1 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 -1 0 0 0 0 1 0 -1 -2 0 0 0 1 0 0 0 0 0 0 1"); const static MatG6 R6_Minus(" 1 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 +1 0 0 0 0 1 0 +1 +2 0 0 0 1 0 0 0 0 0 0 1"); const static MatG6 R7_Plus(" 1 0 0 0 0 0 1 1 0 0 0 -1 0 0 1 0 0 0 0 0 0 1 -1 0 0 0 0 0 1 0 -2 0 0 0 0 1"); const static MatG6 R7_Minus(" 1 0 0 0 0 0 1 1 0 0 0 +1 0 0 1 0 0 0 0 0 0 1 +1 0 0 0 0 0 1 0 +2 0 0 0 0 1"); const static MatG6 R8(" 1 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 0 2 0 1 0 1 2 0 0 0 1 1 0 0 0 0 0 1"); const static MatG6 R9_Plus(R5_Plus); const static MatG6 R9_Minus(R5_Minus); const static MatG6 R10_Plus(R6_Plus); const static MatG6 R10_Minus(R6_Minus); const static MatG6 R11_Plus(R7_Plus); const static MatG6 R11_Minus(R7_Minus); //const MatG6 R12(R8); const static MatG6 R12("1 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 0 -2 0 -1 0 -1 -2 0 0 0 -1 -1 0 0 0 0 0 1"); G6 vin; MatG6 m1; size_t count = 0; bool again = true; const bool debug = true; const int maxCycle = 260; m1 = MatG6::Eye(); vin = vi; G6 voutPrev(vin); /* Mapping from Fortran indices: 1 2 3 4 5 6 0 6 12 18 24 30 7 8 9 10 11 12 1 7 13 19 25 31 13 14 15 16 17 18 2 8 14 20 26 32 19 20 21 22 23 24 3 9 15 21 27 33 25 26 27 28 29 30 4 10 16 22 28 34 31 32 33 34 35 36 5 11 17 23 29 35 */ // Try some number of times to reduce the input vector and accumulate // the changing vector and total transformation matrix // The limit on the number of cycles is because (whether because of // floating point rounding or algorithm issues) there might be a // case of an infinite loop. The designations R5-R12 are from // Andrews and Bernstein, 1988 m1 = MatG6::Eye(); MKnorm(vin, m1, vout, delta); accumulator = m1 * accumulator; vin = vout; while (again && count < maxCycle) { // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE start m_ReductionCycleCount ", m_ReductionCycleCount, " ", vin));; m1 = m; const MatG6 m2temp = m1 * m; m = m2temp; m1 = MatG6::Eye(); if (fabs(vin[3]) > fabs(vin[1]) + delta) { // R5 m1 = (vin[3] <= 0.0) ? R5_Minus : R5_Plus; accumulator = m1 * accumulator; again = true; //// DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R5-m1\n", m1,"\n"));; vout = m1 * vin; Reporter("R5", vin, vout, m1); } else if (fabs(vin[4]) > fabs(vin[0]) + delta) { // R6 m1 = (vin[4] <= 0.0) ? R6_Minus : R6_Plus; accumulator = m1 * accumulator; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R6-m1\n", m1,"\n"));; vout = m1 * vin; Reporter("R6", vin, vout, m1); } else if (fabs(vin[5]) > fabs(vin[0]) + delta) { // R7 m1 = (vin[5] <= 0.0) ? R7_Minus : R7_Plus; accumulator = m1 * accumulator; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R7-m1\n", m1,"\n"));; vout = m1 * vin; Reporter("R7", vin, vout, m1); } else if (vin[3] + vin[4] + vin[5] + fabs(vin[0]) + fabs(vin[1]) + delta < 0.0) { //R8 m1 = R8; accumulator = m1 * accumulator; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R8-m1\n", m1,"\n"));; vout = m1 * vin; Reporter("R8", vin, vout, m1); } else if ((fabs(vin[3] - vin[1]) <= delta && 2.0 * vin[4] - delta < vin[5]) || (fabs(vin[3] + vin[1]) <= delta && vin[5] < 0.0)) { // R9 There is an error in the paper says "2g5<g5" should be "2g5<g6" m1 = (vin[3] <= 0.0) ? R9_Minus : R9_Plus; accumulator = m1 * accumulator; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R9-m1\n", m1,"\n"));; vout = m1 * vin; Reporter("R9", vin, vout, m1); } else if ((fabs(vin[4] - vin[0]) <= delta && 2.0 * vin[3] - delta < vin[5]) || (fabs(vin[4] + vin[0]) <= delta && vin[5] < 0.0)) { //R10 (LAST=15 in ITERATE) m1 = (vin[4] <= 0.0) ? R10_Minus : R10_Plus; accumulator = m1 * accumulator; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R10-m\n", m,"\n")); // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R10-m1\n", m1,"\n")); // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R10-m2=m1*m\n", m2,"\n")); vout = m1 * vin; Reporter("R10", vin, vout, m1); // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R10-in ", vin)); // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R10-out ", vout)) } else if ((fabs(vin[5] - vin[0]) <= delta && 2.0 * vin[3] - delta < vin[4]) || (fabs(vin[5] + vin[0]) <= delta && vin[4] < 0.0)) // paper says g6<0, but it seems wrong { // R11 m1 = (vin[5] <= 0.0) ? R11_Minus : R11_Plus; accumulator = m1 * accumulator; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE 1-m1\n", m1,"\n"));; vout = m1 * vin; Reporter("R11", vin, vout, m1); } else if (fabs(vin[3] + vin[4] + vin[5] + fabs(vin[0]) + fabs(vin[1])) <= delta && (2.0 * (fabs(vin[0]) + vin[4]) + vin[5] > delta)) { //R12 (same as R8) m1 = R12; accumulator = m1 * accumulator; again = true; // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE R12-m1\n", m1,"\n"));; vout = m1 * vin; Reporter("R12", vin, vout, m1); } else { again = false; vout = vin; } // probably don't need to do this group of code when again==false !!!!!!!!!!!!!! m1 = MatG6::Eye(); MKnorm(vout, m1, vin, delta); //accumulator = m1 * accumulator; const MatG6 mtemp = m1 * m; m = mtemp; Reporter("vout after MKnorm at end of reduced m_ReductionCycleCount", vout, vin, m1); for (size_t i = 3; i < 6; ++i) if (std::fabs(vin[i]) < 1.0E-10) vin[i] = 0.0; if (vin[0] < 0.0 || vin[1] < 0.0 || vin[2] < 0.0) { // ERROR ERROR ERROR if (DEBUG_REDUCER) { fprintf(stderr, " Negative sq, axis %d \n", (int)(count)); fprintf(stderr, " vin: [%g,%g,%g,%g,%g,%g]\n", vin[0], vin[1], vin[2], vin[3], vin[4], vin[5]); fprintf(stderr, " vi: [%g,%g,%g,%g,%g,%g]\n", vi[0], vi[1], vi[2], vi[3], vi[4], vi[5]); } return(false); } if (count == 0) voutPrev = vin; if (DEBUG_REDUCER) { //printf( "%d %f %f %f %f %f %f\n", m_ReductionCycleCount, vout[0], vout[1], vout[2], vout[3], vout[4], vout[5] ); } // DEBUG_REPORT_STRING(LRL_ToString( "REDUCE output ", vi));; ++count; // if (count > 250) { // std::cout << std::endl; // std::cout << "cycle " << count << std::endl; // std::cout << "\tvin " << vin << std::endl; // std::cout << vin[0] - vin[1] << " " << vin[0] - vin[2] << " " << vin[1] - vin[2] << std::endl; // std::cout << "\tvout " << vout << std::endl; // std::cout << vout[0] - vout[1] << " " << vout[0] - vout[2] << " " << vout[1] - vout[2] << std::endl; // } m1 = MatG6::Eye(); MKnorm(vout, m1, vin, delta); accumulator = m1 * accumulator; //std::cout << "in Niggli::Reduce end of cycle " << count << " in reduced\n"; //std::cout << "in Niggli::Reduce m \n"<< m <<std::endl; //std::cout << "in Niggli::Reduce vin " << vin << std::endl; //std::cout << "in Niggli::Reduce vi " << vi << std::endl; //std::cout << "in Niggli::Reduce vout " << vout << std::endl; //std::cout << "in Niggli::Reduce m1*vi " << m1 * vi << std::endl << std::endl; //std::cout << "in Niggli::Reduce m*vi " << m * vi << std::endl << std::endl; m = m1; } vout = vin; bool isNearReduced = NearRed(vout, delta); if (count >= maxCycle) { if (!isNearReduced) { std::cout << "THERE IS A REDUCE PROBLEM, m_ReductionCycleCount " << count << std::endl; } } m_ReductionCycleCount = count; m = accumulator; return (count < maxCycle) || isNearReduced; } // end of Reduce //----------------------------------------------------------------------------- // Name: NearRed() // Description: test whether a vector is nearly Niggli reduced /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ bool Niggli::NearRed(const G6& gvec, const double delta) { //C //C RETURNS .true. IF GVEC IS NEARLY NIGGLI REDUCED //C ALLOWING A NON_REDUCTION ERROR OF DELTA. NO //C MATRICES OR VECTORS ARE KEPT. //C //C IF DELTA .EQ. 0.D0, THE TESTS ARE ON REDUCTION //C RATHER THAN NEAR REDUCTION //C //C ALL CASES OF BEING ON THE WRONG SIDES OF THE //C FOLDING BOUNDARIES ARE ACCEPTED AS NEAR //C REDUCED //C----------------------------------------------------------------------C //C TEST FOR G1, G2, G3 OUT OF BOUNDS OR WRONG ORDER //C if (gvec[0] < -delta || gvec[1] < -delta || gvec[2] < -delta || gvec[0] > gvec[1] + delta || gvec[1] > gvec[2] + delta) { return(false); } //C //C TEST FOR NON-REDUCED SIGN COMBINATIONS IN //C G4, G5 AND G6 //C if ((gvec[3] <= delta || gvec[4] <= delta || gvec[5] <= delta) && (gvec[4] > delta || gvec[4] > delta || gvec[5] > delta)) { return(false); } //C //C TEST ABS(G{4,5,6}) AGAINST G{1,2,3} //C if (fabs(gvec[3]) > fabs(gvec[2]) + delta || fabs(gvec[4]) > fabs(gvec[0]) + delta || fabs(gvec[5]) > fabs(gvec[0]) + delta) { return(false); } //C //C TEST THE BODY DIAGONAL //C if (gvec[3] + gvec[4] + gvec[5] + fabs(gvec[0]) + fabs(gvec[1]) + delta < 0.0) return(false); if (delta > 0.0) return(true); //C //C TEST THE 678, 9AB, CDE BOUNDARY FOLDS //C if ((gvec[3] == gvec[1] && 2.0 * gvec[4] < gvec[5]) || (gvec[4] == gvec[0] && 2.0 * gvec[3] < gvec[5]) || (gvec[5] == gvec[0] && 2.0 * gvec[3] < gvec[4]) || (gvec[3] + gvec[1] == 0.0 && gvec[5] <= 0.0) || (gvec[4] + gvec[0] == 0.0 && gvec[5] <= 0.0) || (gvec[5] + gvec[0] == 0.0 && gvec[4] <= 0.0)) return(false); //C //C TEST THE F BOUDARY FOLD //C if (fabs(gvec[3] + gvec[4] + gvec[5] + gvec[0] + gvec[1]) <= delta) return(false); return(true); } // end NearRed bool Niggli::IsNiggli(const S6& s) { G6 g{ D7{ s } }; return IsNiggli(g); } bool Niggli::IsNiggli(const D7& d) { G6 g{ d }; return IsNiggli(g); } bool Niggli::IsNiggli(const G6& v) { const double& g1 = v[0]; const double& g2 = v[1]; const double& g3 = v[2]; const double& g4 = v[3]; const double& g5 = v[4]; const double& g6 = v[5]; const double delta = 10E-6; if (g1 <= 0.0) return false; if (g2 <= 0.0) return false; if (g3 <= 0.0) return false; if (g1 > g2) return false; if (g2 > g3) return false; if (abs(g4) > g2) return false; if (abs(g5) > g1) return false; if (abs(g6) > g1) return false; int nneg = 0; for (size_t i = 3; i < 6; ++i) if (v[i] <= 0.0) ++nneg; if (nneg != 0 && nneg != 3) return false; if (g4 == g2 && g6 > 2.0 * g5) return false; if (g5 == g1 && g6 > 2.0 * g4) return false; if (g6 == g1 && g5 > 2.0 * g4) return false; if (abs(g2 - g3) < delta && abs(g5) > abs(g6)) return false; if (abs(g3) > g1 + g2 + g3 + g4 + g5 + g6) return false; if (g4 == g2 && g6 != 0) return false; if (g5 == g1 && g6 != 0) return false; if (g6 == g1 && g5 != 0) return false; if (g3 == (g1 + g2 + g3 + g4 + g5 + g6) && 2.0 * (g1 + g5) > 0.0) return false; return true; } void Niggli::ShowStoreResults() { //g_store.ShowResults(); }
[ "larry6640995@gmail.com" ]
larry6640995@gmail.com
57946b1bda1062edad0490ae88ccd28e4067ed19
648fc20bb41cb03b9c1b70204824af53b814dd42
/URI/uri1397-CASTILHO.cpp
3f3df80005c0dc40305c72d96f6ee8614850af36
[]
no_license
joaopaulocastilho/aBNT-Codes
a2a9c3a87e20ff3e219efeccfe42eade4470e485
5af8fe1b789efbbcf3d293656e47ec674377bc5b
refs/heads/master
2021-03-27T12:30:58.405856
2019-10-24T18:15:56
2019-10-24T18:15:56
104,107,658
1
2
null
2019-10-24T18:15:58
2017-09-19T17:43:30
C++
UTF-8
C++
false
false
257
cpp
#include<stdio.h> int main(void) { int n, a, b, j1, j2; while (scanf("%d", &n), n) { for (j1 = j2 = 0; n--; ) { scanf("%d %d", &a, &b); if (a > b) j1++; else if (a < b) j2++; } printf("%d %d\n", j1, j2); } return 0; }
[ "joao.pkc@gmail.com" ]
joao.pkc@gmail.com
569ee7d6fb2c4a92746ef2e4cdf067074917ef09
7cbbc8789a4455d88eb91490a836e9fc39641f05
/TP3/Fichiers/transfert.cpp
cc4321aa838c3d1fa78fe1fb3b6ac2532ca9ddca
[]
no_license
cora-maltese/INF1010-19---ProgOrienteeObjet
85a015b3317c8967cd80b1fcdba4f0a2e2bd2752
09e880d169d92eecd1e254270965c8a09638b7ca
refs/heads/master
2020-03-31T16:27:08.603692
2018-11-06T05:47:20
2018-11-06T05:47:20
152,376,113
0
0
null
null
null
null
UTF-8
C++
false
false
1,215
cpp
/******************************************** * Titre: Travail pratique #3 - transfert.cpp * Date: 16 septembre 2018 * Auteur: Wassim Khene *******************************************/ #include "transfert.h" // Constructeurs Transfert::Transfert() : montant_(0), expediteur_(nullptr), receveur_(nullptr) { } Transfert::Transfert(double montant, Utilisateur* expediteur, Utilisateur* receveur) : montant_(montant), expediteur_(expediteur), receveur_(receveur) { } // Methodes d'acces double Transfert::getMontant() const { return montant_; } Utilisateur* Transfert::getExpediteur() const { return expediteur_; } Utilisateur* Transfert::getReceveur() const { return receveur_; } // Methodes de modifications void Transfert::setMontant(double montant) { montant_ = montant; } void Transfert::setExpediteur(Utilisateur *donneur) { expediteur_ = donneur; } void Transfert::setReceveur(Utilisateur *receveur) { receveur_ = receveur; } //Methode affichage ostream& operator<<(ostream& os, const Transfert& transfert) { return os << "Transfert fait par " << transfert.getExpediteur()->getNom() << " vers " << transfert.getReceveur()->getNom() << " d'un montant de " << transfert.getMontant() << endl; }
[ "paul.corrand@hotmail.fr" ]
paul.corrand@hotmail.fr
1431ef00d713fe14aaef5f68a487e96072ab5547
5cbe584278d9a505961753ce225443d1684c2a74
/AIE Year1 Framework VS2013_QuinnM/source/EvadeBeehaviour.cpp
36ea32b609b50279440981bc634861de3b3481e9
[]
no_license
jaredramey/SteeringBehaviour
2f29e56cf77aa943049331fb4f8ed6f5144fd468
11600dd192943f6de3b5ba9c59fe4e86947df09f
refs/heads/master
2021-01-17T03:38:22.398177
2015-03-11T00:53:45
2015-03-11T00:53:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,399
cpp
#include "EvadeBehaviour.h" EvadeBehaviour::EvadeBehaviour(Agent* pt_target, float in_maxForce) : Behaviour() { if (pt_target == nullptr) { throw("Argument of EvadeBehaviour(Agent*) cannot be null"); } target = pt_target; maxForce = in_maxForce; } EvadeBehaviour::~EvadeBehaviour() { } Point EvadeBehaviour::GetForce() { Point out_velocity = Point(0, 0); //get target's position from the origin of position Point targetDirectPos = (target->position) - owner->position; float targetDirectDist = std::sqrt((targetDirectPos.x * targetDirectPos.x) + (targetDirectPos.y * targetDirectPos.y)); if (targetDirectDist > maxForce) {//if far away find where the target is going Point TargetRelPos = (target->position + target->GetVelocity()) - owner->position; float targetRelDist = std::sqrt((TargetRelPos.x * TargetRelPos.x) + (TargetRelPos.y * TargetRelPos.y)); TargetRelPos.x /= targetRelDist; TargetRelPos.y /= targetRelDist; out_velocity.x = (TargetRelPos.x * (maxForce * -1)); out_velocity.y = (TargetRelPos.y * (maxForce * -1)); } else {//if they're close then go strait to them targetDirectPos.x /= targetDirectDist; targetDirectPos.y /= targetDirectDist; //add to velocity out_velocity.x = (targetDirectPos.x * ((maxForce - targetDirectDist) * -1)); out_velocity.y = (targetDirectPos.y * ((maxForce - targetDirectDist) * -1)); } return out_velocity; }
[ "Darkstaro59@gmail.com" ]
Darkstaro59@gmail.com
4a29a1410f1b703cf72d9fca8089c43697e5baea
6dc2e2422b2e32011b32576c36c34b0773bdc639
/10/10.1-2.cpp
220f7af75994cb554597efd7b0649a8a778785dd
[]
no_license
Ramengi-chawngthu/CLRS
41afccc94828865c1c1659f9810c433ec1e7e180
91ee1880bf99e3e274be5e025ec37965a2e55b7d
refs/heads/main
2023-08-26T08:26:25.491564
2021-10-31T07:45:37
2021-10-31T07:45:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
818
cpp
#include <cassert> #include <iostream> #include <utility> #include <stdexcept> #include <vector> template <typename T> struct TwoStack { std::vector<T> data; size_t top1; size_t top2; TwoStack(size_t n) : data(n), top1 {0}, top2 {n - 1} {assert(n);} void Push1(const T& x) { data[top1++] = x; } void Push2(const T& x) { data[top2--] = x; } T Pop1(const T& x) { if (top1 == 0) { throw std::underflow_error("Stack underflow"); } else { return data[--top1]; } } T Pop2(const T& x) { if (top2 == data.size() - 1) { throw std::underflow_error("Stack underflow"); } else { return data[++top2]; } } }; int main() { }
[ "frozenca91@gmail.com" ]
frozenca91@gmail.com
7a8b6a0e54e868b54255dc08455ee77f70990065
cd3978958f135ac551e31becb84551dc5d2c746d
/gpac/Applications/Osmo4_w32/Osmo4.h
ce46f0fff584c36f436c4ea09481e93b1a5fde39
[]
no_license
DmitrySigaev/DSMedia
d515e1248aae90c87b798c91d3c25a5c9bb2d704
80a5030306fcb088df73f1011689f984425b65ff
refs/heads/master
2020-04-10T14:17:01.721904
2015-09-28T13:16:01
2015-09-28T13:16:01
41,440,862
0
1
null
null
null
null
UTF-8
C++
false
false
2,446
h
// GPAC.h : main header file for the GPAC application // #if !defined(AFX_GPAC_H__8B06A368_E142_47E3_ABE7_0B459FC0E853__INCLUDED_) #define AFX_GPAC_H__8B06A368_E142_47E3_ABE7_0B459FC0E853__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // WinGPAC: // See GPAC.cpp for the implementation of this class // /*MPEG4 term*/ #include <gpac/m4_terminal.h> enum { WM_SCENE_DONE = WM_USER + 1, WM_NAVIGATE, WM_SETSIZE, WM_OPENURL, WM_RESTARTURL, WM_CONSOLEMSG, WM_SETTIMING, }; Bool is_supported_file(LPINIFILE cfg, const char *fileName, Bool disable_no_ext); class WinGPAC : public CWinApp { public: WinGPAC(); MPEG4CLIENT m_term; LPPLUGMAN m_plugins; LPINIFILE m_config; M4User m_user; CString m_config_dir; Bool m_isopen, m_paused, m_reset; u32 max_duration; Bool can_seek; u32 orig_width,orig_height, m_reconnect_time; u32 current_time_ms, m_prev_time; Float current_FPS; CString m_navigate_url; void Pause(); void PlayFromTime(u32 time); void SetOptions(); void UpdateRenderSwitch(); /*general options*/ Bool m_Loop, m_LookForSubtitles, m_NoConsole; Bool m_ViewXMTA; void ReloadTerminal(); CString GetFileFilter(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(WinGPAC) public: virtual BOOL InitInstance(); virtual int ExitInstance(); //}}AFX_VIRTUAL // Implementation public: //{{AFX_MSG(WinGPAC) afx_msg void OnAppAbout(); afx_msg void OnOpenFile(); afx_msg void OnMainPause(); afx_msg void OnFileStep(); afx_msg void OnOpenUrl(); afx_msg void OnFileReload(); afx_msg void OnFilePlay(); afx_msg void OnUpdateFilePlay(CCmdUI* pCmdUI); afx_msg void OnUpdateFileStep(CCmdUI* pCmdUI); afx_msg void OnFileStop(); afx_msg void OnUpdateFileStop(CCmdUI* pCmdUI); afx_msg void OnSwitchRender(); afx_msg void OnReloadTerminal(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; inline WinGPAC *GetApp() { return (WinGPAC *)AfxGetApp(); } ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_GPAC_H__8B06A368_E142_47E3_ABE7_0B459FC0E853__INCLUDED_)
[ "dsigaev@yandex.ru" ]
dsigaev@yandex.ru
737011f2a6115bdc9107edcb864c445812b7a48a
9ec26541e31a905d61c92a3e3bc7bfac08edca21
/DeviceCode/GHI/Libraries/GHI.OSHW.Native/Native/HAL_GHI_OSHW_Native_RLPLite__Procedure.cpp
91775dc4a8a21977bf5cf1822aa6c42ccce182e9
[]
no_license
errolt/NETMF4.3_Community
3298450a8f259318b788290e0bec79a4499bff16
5cc0dc18d23baaa9fa3597ad25e86c38c4f4151a
refs/heads/master
2021-01-18T07:58:03.557133
2014-09-03T20:51:57
2014-09-03T20:51:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,249
cpp
//----------------------------------------------------------------------------- // // ** WARNING! ** // This file was generated automatically by a tool. // Re-running the tool will overwrite this file. // You should copy this file to a custom location // before adding any customization in the copy to // prevent loss of your changes when the tool is // re-run. // //----------------------------------------------------------------------------- #include "HAL.h" #include "HAL_GHI_OSHW_Native_RLPLite__Procedure.h" using namespace GHI::OSHW::Native; INT32 InvokeRLP(UINT32 address, void* param0, int* param1, unsigned char* param2); INT32 RLPLite_Procedure::Invoke_Helper( CLR_RT_HeapBlock* pMngObj, CLR_RT_TypedArray_float param0, CLR_RT_TypedArray_INT32 param1, CLR_RT_TypedArray_UINT8 param2, HRESULT &hr ) { UINT32 address = Get_address( pMngObj ); return InvokeRLP( address, param0.GetBuffer(), param1.GetBuffer(), param2.GetBuffer() ); } INT32 RLPLite_Procedure::Invoke_Helper( CLR_RT_HeapBlock* pMngObj, CLR_RT_TypedArray_UINT32 param0, CLR_RT_TypedArray_INT32 param1, CLR_RT_TypedArray_UINT8 param2, HRESULT &hr ) { UINT32 address = Get_address( pMngObj ); return InvokeRLP( address, param0.GetBuffer(), param1.GetBuffer(), param2.GetBuffer() ); } INT32 RLPLite_Procedure::Invoke_Helper( CLR_RT_HeapBlock* pMngObj, CLR_RT_TypedArray_INT32 param0, CLR_RT_TypedArray_INT32 param1, CLR_RT_TypedArray_UINT8 param2, HRESULT &hr ) { UINT32 address = Get_address( pMngObj ); return InvokeRLP( address, param0.GetBuffer(), param1.GetBuffer(), param2.GetBuffer() ); } INT32 RLPLite_Procedure::Invoke_Helper( CLR_RT_HeapBlock* pMngObj, CLR_RT_TypedArray_UINT8 param0, CLR_RT_TypedArray_INT32 param1, CLR_RT_TypedArray_UINT8 param2, HRESULT &hr ) { UINT32 address = Get_address( pMngObj ); return InvokeRLP( address, param0.GetBuffer(), param1.GetBuffer(), param2.GetBuffer() ); } INT32 RLPLite_Procedure::Invoke_Helper( CLR_RT_HeapBlock* pMngObj, CLR_RT_TypedArray_INT8 param0, CLR_RT_TypedArray_INT32 param1, CLR_RT_TypedArray_UINT8 param2, HRESULT &hr ) { UINT32 address = Get_address( pMngObj ); return InvokeRLP( address, param0.GetBuffer(), param1.GetBuffer(), param2.GetBuffer() ); }
[ "Nicolasg3@free.fr" ]
Nicolasg3@free.fr
362bacf99326dd7aa50cc342603e9ed9acd6ee6d
bd18edfafeec1470d9776f5a696780cbd8c2e978
/SlimDX/source/direct3d10/ShaderResourceViewDescription.cpp
ce721dd985242f7658bc6595f79353407104761d
[ "MIT" ]
permissive
MogreBindings/EngineDeps
1e37db6cd2aad791dfbdfec452111c860f635349
7d1b8ecaa2cbd8e8e21ec47b3ce3a5ab979bdde7
refs/heads/master
2023-03-30T00:45:53.489795
2020-06-30T10:48:12
2020-06-30T10:48:12
276,069,149
0
1
null
2021-04-05T16:05:53
2020-06-30T10:33:46
C++
UTF-8
C++
false
false
9,159
cpp
#include "stdafx.h" /* * Copyright (c) 2007-2010 SlimDX Group * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <d3d10.h> #include "ShaderResourceViewDescription.h" namespace SlimDX { namespace Direct3D10 { ShaderResourceViewDescription::ShaderResourceViewDescription( const D3D10_SHADER_RESOURCE_VIEW_DESC& native ) : m_ElementOffset( 0 ), m_ElementWidth( 0 ), m_MipLevels( 0 ), m_MostDetailedMip( 0 ), m_ArraySize( 0 ), m_FirstArraySlice( 0 ) { m_Format = static_cast<DXGI::Format>( native.Format ); m_ViewDimension = static_cast<ShaderResourceViewDimension>( native.ViewDimension ); switch( m_ViewDimension ) { case ShaderResourceViewDimension::Buffer: m_ElementOffset = native.Buffer.ElementOffset; m_ElementWidth = native.Buffer.ElementWidth; break; case ShaderResourceViewDimension::Texture1D: m_MipLevels = native.Texture1D.MipLevels; m_MostDetailedMip = native.Texture1D.MostDetailedMip; break; case ShaderResourceViewDimension::Texture1DArray: m_ArraySize = native.Texture1DArray.ArraySize; m_FirstArraySlice = native.Texture1DArray.FirstArraySlice; m_MipLevels = native.Texture1DArray.MipLevels; m_MostDetailedMip = native.Texture1DArray.MostDetailedMip; break; case ShaderResourceViewDimension::Texture2D: m_MipLevels = native.Texture2D.MipLevels; m_MostDetailedMip = native.Texture2D.MostDetailedMip; break; case ShaderResourceViewDimension::Texture2DArray: m_ArraySize = native.Texture2DArray.ArraySize; m_FirstArraySlice = native.Texture2DArray.FirstArraySlice; m_MipLevels = native.Texture2DArray.MipLevels; m_MostDetailedMip = native.Texture2DArray.MostDetailedMip; break; case ShaderResourceViewDimension::Texture2DMultisampled: // Nothing to do here. break; case ShaderResourceViewDimension::Texture2DMultisampledArray: m_ArraySize = native.Texture2DMSArray.ArraySize; m_FirstArraySlice = native.Texture2DMSArray.FirstArraySlice; break; case ShaderResourceViewDimension::Texture3D: m_MipLevels = native.Texture3D.MipLevels; m_MostDetailedMip = native.Texture3D.MostDetailedMip; break; case ShaderResourceViewDimension::TextureCube: m_MipLevels = native.TextureCube.MipLevels; m_MostDetailedMip = native.TextureCube.MostDetailedMip; break; default: break; } } D3D10_SHADER_RESOURCE_VIEW_DESC ShaderResourceViewDescription::CreateNativeVersion() { D3D10_SHADER_RESOURCE_VIEW_DESC native; native.Format = static_cast<DXGI_FORMAT>( m_Format ); native.ViewDimension = static_cast<D3D10_SRV_DIMENSION>( m_ViewDimension ); switch( m_ViewDimension ) { case ShaderResourceViewDimension::Buffer: native.Buffer.ElementOffset = m_ElementOffset; native.Buffer.ElementWidth = m_ElementWidth; break; case ShaderResourceViewDimension::Texture1D: native.Texture1D.MipLevels = m_MipLevels; native.Texture1D.MostDetailedMip = m_MostDetailedMip; break; case ShaderResourceViewDimension::Texture1DArray: native.Texture1DArray.ArraySize = m_ArraySize; native.Texture1DArray.FirstArraySlice = m_FirstArraySlice; native.Texture1DArray.MipLevels = m_MipLevels; native.Texture1DArray.MostDetailedMip = m_MostDetailedMip; break; case ShaderResourceViewDimension::Texture2D: native.Texture2D.MipLevels = m_MipLevels; native.Texture2D.MostDetailedMip = m_MostDetailedMip; break; case ShaderResourceViewDimension::Texture2DArray: native.Texture2DArray.ArraySize = m_ArraySize; native.Texture2DArray.FirstArraySlice = m_FirstArraySlice; native.Texture2DArray.MipLevels = m_MipLevels; native.Texture2DArray.MostDetailedMip = m_MostDetailedMip; break; case ShaderResourceViewDimension::Texture2DMultisampled: // Nothing to do here. break; case ShaderResourceViewDimension::Texture2DMultisampledArray: native.Texture2DMSArray.ArraySize = m_ArraySize; native.Texture2DMSArray.FirstArraySlice = m_FirstArraySlice; break; case ShaderResourceViewDimension::Texture3D: native.Texture3D.MipLevels = m_MipLevels; native.Texture3D.MostDetailedMip = m_MostDetailedMip; break; case ShaderResourceViewDimension::TextureCube: native.TextureCube.MipLevels = m_MipLevels; native.TextureCube.MostDetailedMip = m_MostDetailedMip; break; default: break; } return native; } DXGI::Format ShaderResourceViewDescription::Format::get() { return m_Format; } void ShaderResourceViewDescription::Format::set( DXGI::Format value ) { m_Format = value; } ShaderResourceViewDimension ShaderResourceViewDescription::Dimension::get() { return m_ViewDimension; } void ShaderResourceViewDescription::Dimension::set( ShaderResourceViewDimension value ) { m_ViewDimension = value; } int ShaderResourceViewDescription::ElementOffset::get() { return m_ElementOffset; } void ShaderResourceViewDescription::ElementOffset::set( int value ) { m_ElementOffset = value; } int ShaderResourceViewDescription::ElementWidth::get() { return m_ElementWidth; } void ShaderResourceViewDescription::ElementWidth::set( int value ) { m_ElementWidth = value; } int ShaderResourceViewDescription::MipLevels::get() { return m_MipLevels; } void ShaderResourceViewDescription::MipLevels::set( int value ) { m_MipLevels = value; } int ShaderResourceViewDescription::MostDetailedMip::get() { return m_MostDetailedMip; } void ShaderResourceViewDescription::MostDetailedMip::set( int value ) { m_MostDetailedMip = value; } int ShaderResourceViewDescription::ArraySize::get() { return m_ArraySize; } void ShaderResourceViewDescription::ArraySize::set( int value ) { m_ArraySize = value; } int ShaderResourceViewDescription::FirstArraySlice::get() { return m_FirstArraySlice; } void ShaderResourceViewDescription::FirstArraySlice::set( int value ) { m_FirstArraySlice = value; } bool ShaderResourceViewDescription::operator == ( ShaderResourceViewDescription left, ShaderResourceViewDescription right ) { return ShaderResourceViewDescription::Equals( left, right ); } bool ShaderResourceViewDescription::operator != ( ShaderResourceViewDescription left, ShaderResourceViewDescription right ) { return !ShaderResourceViewDescription::Equals( left, right ); } int ShaderResourceViewDescription::GetHashCode() { return m_Format.GetHashCode() + m_ViewDimension.GetHashCode() + m_ElementOffset.GetHashCode() + m_ElementWidth.GetHashCode() + m_MostDetailedMip.GetHashCode() + m_MipLevels.GetHashCode() + m_FirstArraySlice.GetHashCode() + m_ArraySize.GetHashCode(); } bool ShaderResourceViewDescription::Equals( Object^ value ) { if( value == nullptr ) return false; if( value->GetType() != GetType() ) return false; return Equals( safe_cast<ShaderResourceViewDescription>( value ) ); } bool ShaderResourceViewDescription::Equals( ShaderResourceViewDescription value ) { return ( m_Format == value.m_Format && m_ViewDimension == value.m_ViewDimension && m_ElementOffset == value.m_ElementOffset && m_ElementWidth == value.m_ElementWidth && m_MostDetailedMip == value.m_MostDetailedMip && m_MipLevels == value.m_MipLevels && m_FirstArraySlice == value.m_FirstArraySlice && m_ArraySize == value.m_ArraySize ); } bool ShaderResourceViewDescription::Equals( ShaderResourceViewDescription% value1, ShaderResourceViewDescription% value2 ) { return ( value1.m_Format == value2.m_Format && value1.m_ViewDimension == value2.m_ViewDimension && value1.m_ElementOffset == value2.m_ElementOffset && value1.m_ElementWidth == value2.m_ElementWidth && value1.m_MostDetailedMip == value2.m_MostDetailedMip && value1.m_MipLevels == value2.m_MipLevels && value1.m_FirstArraySlice == value2.m_FirstArraySlice && value1.m_ArraySize == value2.m_ArraySize ); } } }
[ "Michael@localhost" ]
Michael@localhost
e42b48651e8cbc261a40b69580daec4185d4ef1a
511eee1dde8f8143fa2602ca44777177e0f90ac3
/src/oj/offer05_replaceSpace/replaceSpace.cpp
7688f1f27077b7ae7e1f74792f63ff7403742d9d
[]
no_license
ArmstrongWall/programmer
969cb008b1b98562192a949cece0a85486bb5003
2d66d991d143514cd9a56b36a18ad415ba94de36
refs/heads/master
2021-07-26T13:17:24.723341
2021-02-06T13:08:11
2021-02-06T13:08:11
86,895,330
15
3
null
null
null
null
UTF-8
C++
false
false
1,211
cpp
// // Created by Johnny on 2020/11/7. // #include <string> #include <iostream> #include "replaceSpace.h" /*请实现一个函数,把字符串 s 中的每个空格替换成"%20"。 示例 1: 输入:s = "We are happy." 输出:"We%20are%20happy." 限制: 0 <= s 的长度 <= 10000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ class Solution { public: std::string replaceSpace(std::string s) { int space_count = 0; for(auto &c : s) { if(c == ' ') { space_count++; } } if(space_count == 0) { return s; } int new_length = s.size() + space_count*2; int i = s.size() - 1; int j = new_length - 1; s.resize(new_length); for(; i >= 0; i--) { std::cout << s[i] << " "; if(s[i] == ' ') { s[j--] = '0'; s[j--] = '2'; s[j--] = '%'; } else { s[j--] = s[i]; } } return s; } };
[ "160111223wzq@gmail.com" ]
160111223wzq@gmail.com
dcd5c0d895ec2889badf87605042e0ab2c6bbdac
c1518f5bfcf571a02eff8f3b70d6629e327771fa
/src/nw_package.cc
bcebcecca0e002115bf98e44e3aa9e531f754142
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
aremes/node-webkit
54a68306082c788e8c329a44f348b50d4eb4ee50
9d145b002747266dcaac0758f4891b458cb34e35
refs/heads/master
2021-01-15T20:33:28.117490
2012-11-16T06:46:31
2012-11-16T06:46:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,010
cc
// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // 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 co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "content/nw/src/nw_package.h" #include <vector> #include "base/command_line.h" #include "base/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/scoped_temp_dir.h" #include "base/string_util.h" #include "base/threading/thread_restrictions.h" #include "base/values.h" #include "chrome/common/zip.h" #include "content/nw/src/common/shell_switches.h" #include "googleurl/src/gurl.h" #include "grit/nw_resources.h" #include "net/base/escape.h" #include "third_party/node/deps/uv/include/uv.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia_rep.h" #include "webkit/glue/image_decoder.h" namespace nw { namespace { bool MakePathAbsolute(FilePath* file_path) { DCHECK(file_path); FilePath current_directory; if (!file_util::GetCurrentDirectory(&current_directory)) return false; if (file_path->IsAbsolute()) return true; if (current_directory.empty()) return file_util::AbsolutePath(file_path); if (!current_directory.IsAbsolute()) return false; *file_path = current_directory.Append(*file_path); return true; } FilePath GetSelfPath() { CommandLine* command_line = CommandLine::ForCurrentProcess(); FilePath path; size_t size = 2*PATH_MAX; char* execPath = new char[size]; if (uv_exepath(execPath, &size) == 0) { path = FilePath::FromUTF8Unsafe(std::string(execPath, size)); } else { path = FilePath(command_line->GetProgram()); } #if defined(OS_MACOSX) // Find if we have node-webkit.app/Resources/app.nw. path = path.DirName().DirName().Append("Resources").Append("app.nw"); #endif return path; } void RelativePathToURI(FilePath root, base::DictionaryValue* manifest) { std::string old; if (!manifest->GetString(switches::kmMain, &old)) return; // Don't append path if there is already a prefix if (MatchPattern(old, "*://*")) return; FilePath main_path = root.Append(FilePath::FromUTF8Unsafe(old)); manifest->SetString(switches::kmMain, std::string("file://") + main_path.AsUTF8Unsafe()); } } // namespace Package::Package() : path_(GetSelfPath()), self_extract_(true) { // First try to extract self. if (InitFromPath()) return; // Then see if we have arguments and extract it. CommandLine* command_line = CommandLine::ForCurrentProcess(); const CommandLine::StringVector& args = command_line->GetArgs(); if (args.size() > 0) { self_extract_ = false; path_ = FilePath(args[0]); if (InitFromPath()) return; } // Finally we init with default settings. self_extract_ = false; InitWithDefault(); } Package::Package(FilePath path) : path_(path), self_extract_(false) { if (!InitFromPath()) InitWithDefault(); } Package::~Package() { } FilePath Package::ConvertToAbsoutePath(const FilePath& path) { if (path.IsAbsolute()) return path; return this->path().Append(path); } bool Package::GetImage(const FilePath& icon_path, gfx::Image* image) { FilePath path = ConvertToAbsoutePath(icon_path); // Read the file from disk. std::string file_contents; if (path.empty() || !file_util::ReadFileToString(path, &file_contents)) return false; // Decode the bitmap using WebKit's image decoder. const unsigned char* data = reinterpret_cast<const unsigned char*>(file_contents.data()); webkit_glue::ImageDecoder decoder; scoped_ptr<SkBitmap> decoded(new SkBitmap()); // Note: This class only decodes bitmaps from extension resources. Chrome // doesn't (for security reasons) directly load extension resources provided // by the extension author, but instead decodes them in a separate // locked-down utility process. Only if the decoding succeeds is the image // saved from memory to disk and subsequently used in the Chrome UI. // Chrome is therefore decoding bitmaps here that were generated by Chrome. *decoded = decoder.Decode(data, file_contents.length()); if (decoded->empty()) return false; // Unable to decode. *image = gfx::Image(*decoded.release()); return true; } GURL Package::GetStartupURL() { std::string url; // Specify URL in --url CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kUrl)) { url = command_line->GetSwitchValueASCII(switches::kUrl); GURL gurl(url); if (!gurl.has_scheme()) return GURL(std::string("http://") + url); return gurl; } // Report if encountered errors. if (!error_page_url_.empty()) return GURL(error_page_url_); // Read from manifest. if (root()->GetString(switches::kmMain, &url)) return GURL(url); else return GURL("nw:blank"); } std::string Package::GetName() { std::string name("node-webkit"); root()->GetString(switches::kmName, &name); return name; } bool Package::GetUseNode() { bool use_node = true; root()->GetBoolean(switches::kmNodejs, &use_node); return use_node; } base::DictionaryValue* Package::window() { base::DictionaryValue* window; root()->GetDictionaryWithoutPathExpansion(switches::kmWindow, &window); return window; } bool Package::InitFromPath() { base::ThreadRestrictions::SetIOAllowed(true); if (!ExtractPath()) return false; // path_/package.json FilePath manifest_path = path_.AppendASCII("package.json"); if (!file_util::PathExists(manifest_path)) { if (!self_extract()) ReportError("Invalid package", "There is no 'package.json' in the package, please make " "sure the 'package.json' is in the root of the package."); return false; } // Parse file. std::string error; JSONFileValueSerializer serializer(manifest_path); scoped_ptr<Value> root(serializer.Deserialize(NULL, &error)); if (!root.get()) { ReportError("Unable to parse package.json", error.empty() ? "Failed to read the manifest file: " + manifest_path.AsUTF8Unsafe() : error); return false; } else if (!root->IsType(Value::TYPE_DICTIONARY)) { ReportError("Invalid package.json", "package.json's content should be a object type."); return false; } // Save result in global root_.reset(static_cast<DictionaryValue*>(root.release())); // Check fields const char* required_fields[] = { switches::kmMain, switches::kmName }; for (unsigned i = 0; i < arraysize(required_fields); i++) if (!root_->HasKey(required_fields[i])) { ReportError("Invalid package.json", std::string("Field '") + required_fields[i] + "'" " is required."); return false; } // Force window field no empty. if (!root_->HasKey(switches::kmWindow)) { base::DictionaryValue* window = new base::DictionaryValue(); window->SetString(switches::kmPosition, "center"); root_->Set(switches::kmWindow, window); } RelativePathToURI(path_, this->root()); return true; } void Package::InitWithDefault() { root_.reset(new base::DictionaryValue()); root()->SetString(switches::kmName, "node-webkit"); root()->SetString(switches::kmMain, "nw:blank"); base::DictionaryValue* window = new base::DictionaryValue(); root()->Set(switches::kmWindow, window); // Hide toolbar if specifed in the command line. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kNoToolbar)) window->SetBoolean(switches::kmToolbar, false); // Window should show in center by default. window->SetString(switches::kmPosition, "center"); } bool Package::ExtractPath() { // Convert to absoulute path. if (!MakePathAbsolute(&path_)) { ReportError("Cannot extract package", "Path is invalid: " + path_.AsUTF8Unsafe()); return false; } // Read symbolic link. #if defined(OS_POSIX) FilePath target; if (file_util::ReadSymbolicLink(path_, &target)) path_ = target; #endif // If it's a file then try to extract from it. if (!file_util::DirectoryExists(path_)) { FilePath extracted_path; if (ExtractPackage(path_, &extracted_path)) { path_ = extracted_path; } else if (!self_extract()) { ReportError("Cannot extract package", "Failed to unzip the package file: " + path_.AsUTF8Unsafe()); return false; } } return true; } bool Package::ExtractPackage(const FilePath& zip_file, FilePath* where) { // Auto clean our temporary directory static scoped_ptr<ScopedTempDir> scoped_temp_dir; #if defined(OS_WIN) if (!file_util::CreateNewTempDirectory(L"nw", where)) { #else if (!file_util::CreateNewTempDirectory("nw", where)) { #endif ReportError("Cannot extract package", "Unable to create temporary directory."); return false; } scoped_temp_dir.reset(new ScopedTempDir()); if (!scoped_temp_dir->Set(*where)) { ReportError("Cannot extract package", "Unable to set temporary directory."); return false; } return zip::Unzip(zip_file, *where); } void Package::ReportError(const std::string& title, const std::string& content) { if (!error_page_url_.empty()) return; const base::StringPiece template_html( ResourceBundle::GetSharedInstance().GetRawDataResource(IDR_NW_ERROR)); if (template_html.empty()) { // Print hand written error info if nw.pak doesn't exist. NOTREACHED() << "Unable to load error template."; error_page_url_ = "data:text/html;base64,VW5hYmxlIHRvIGZpbmQgbncucGFrLgo="; return; } std::vector<std::string> subst; subst.push_back(title); subst.push_back(content); error_page_url_ = "data:text/html;charset=utf-8," + net::EscapeQueryParamValue( ReplaceStringPlaceholders(template_html, subst, NULL), false); } } // namespace nw
[ "zcbenz@gmail.com" ]
zcbenz@gmail.com
c6c415d9c38d266b2af93e82c6c9ef41a1c472e8
d95446089a07244fe89ae082fa67c406e583be10
/Sorting/Selection Sort/Selection Sort.cpp
d81263132e8ed83c5d9cb0f7a87adaa711ddeb2a
[]
no_license
Mohit-Arya1211/Data-Structure-and-Algorithm
3fed222404144e78d9538fd66720e0ac1fef652c
e8316107f90813c2c6c74f7b1ca16bdc279559d9
refs/heads/master
2023-06-11T14:40:16.965849
2021-07-07T20:55:31
2021-07-07T20:55:31
379,978,013
0
0
null
null
null
null
UTF-8
C++
false
false
493
cpp
#include<bits/stdc++.h> using namespace std; void swap(int *a, int *b){ int temp = *a; *a = *b; *b = temp; } void SelectionSort(int A[], int n){ int i,j,k; for(i = 0; i<n; i++){ for(j=k=i; j<n; j++){ if(A[j]<A[k]) k=j; } swap(&A[i], & A[k]); } } int main(){ int A[] = {10, 6, 1, 3, 4 , 9}; int n = 6; SelectionSort(A, n); for(int i = 0; i<n; i++){ cout<<A[i]<<" ,"; } return 0; }
[ "mohit.arya1211@gmail.com" ]
mohit.arya1211@gmail.com
6d46902c107f5ded35550b5f7afed881e76f1657
b97b2a40cb5d0307f662f914fba3152326563023
/Attribute Parser/Attribute Parser.cpp
8ae5c399ff5b36ce88955b5f96bd89e3fb3da364
[]
no_license
PhamDinhDuy-2508/Hackerank_solution
5df6f59c3491bf318718b809821861ca33cca563
a76058c165740aec08687365f57e47b34b5be1aa
refs/heads/master
2023-05-03T00:50:43.254618
2021-05-27T17:50:22
2021-05-27T17:50:22
371,457,849
0
0
null
null
null
null
UTF-8
C++
false
false
6,153
cpp
#include<iostream> #include<stack> #include<map> #include<unordered_map> #include<vector> #include<string> #include<future> #include<chrono> #include<thread> #include<deque> #include<algorithm> using namespace std; class Code_Input { private: int n; string _queries = ""; vector<string> step; deque<string> queries; map<string , map<string , string>> Pre_process; unordered_map<string, map<string, string>> Pro; public: Code_Input() = default; Code_Input(int amount) :n(amount) {} unordered_map<string, map<string, string>> Get_Pro() { return this->Pro; } void set_process(string t1, map<string, string> t) { this->Pre_process.insert({t1,t}); } void Set_amount(int amount) { this->n = amount; } void Get_IN() { for (int i = 0; i < n; i++) { string str = ""; getline(std::cin >> std::ws, str, '\n'); Processing_Code_String(str); } } void Processing_Code_String(string _Str) { string key_hash = ""; string temp = ""; string document = ""; string key_close = ""; _Str.pop_back(); map<string, string> HRML_element; int i = 1; if (_Str[i] != '/') { for (; i < _Str.size(); i++) { if (_Str[i] ==' ') { break; } else { key_hash += _Str[i]; } } queries.push_back(key_hash); _Str.erase(remove(_Str.begin(), _Str.end(), ' '), _Str.end()); _Str.erase(remove(_Str.begin(), _Str.end(), '='), _Str.end()); while (i < _Str.size()) { if (_Str[i] != '"') { temp += _Str[i]; } else { int j = i + 1; for (; j < _Str.size(); j++) { if (_Str[j] == '"') { HRML_element.insert({ temp , document }); temp = ""; document = ""; break; } else { document += _Str[j]; } } i = j; } i++; } set_process(key_hash, HRML_element); } else { i= 2 ; while (i < _Str.size()) { key_close += _Str[i]; i++; } string _temp_top = ""; string _temp_queries = ""; _temp_top = queries.back(); queries.pop_back(); deque<string> temp_querie = queries; if (temp_querie.empty()) { _temp_queries += _temp_top; } else { while (!temp_querie.empty()) { if (_temp_queries.size() == 0) { _temp_queries += temp_querie.front(); temp_querie.pop_front(); } else { _temp_queries += '.' + temp_querie.front(); temp_querie.pop_front(); } } if (temp_querie.empty()) { _temp_queries += '.' + _temp_top; } } Pro.insert({ _temp_queries , Pre_process[key_close] }); } return; } }; class Code_Queries:public Code_Input { protected : vector<string> result; vector<pair<string, string>>Pair; int m; public : Code_Queries() = default; Code_Queries(int n) :m(n) { } void set_amount(int amoutn) { this->m = amoutn; } void get_result() { for (auto x : result) { cout << x << endl; } } void Get_In() { for (int i = 0; i < m; i++) { string str = ""; getline(std::cin >> std::ws, str); Process(str); } } vector<pair<string, string>> get_pair() { return Pair; } void Set_Process(string key , string data) { key.erase(remove(key.begin(), key.end(), ' '), key.end()); data.pop_back(); unordered_map<string, map<string, string>> test = Code_Input::Get_Pro(); auto it = test.find(key); if (it != test.end()) { if (test[key][data] != "") { result.push_back(test[key][data]); } else { result.push_back("Not Found!"); } } else { result.push_back("Not Found!"); } } void Process(string str) { string head = ""; string tail = ""; future<void>Thead_head = async(launch::async, [&head,str]() { int i = 0; while (i < str.size()) { if (str[i] == '~') { break; } head += str[i]; i++; } }); future<void>Thead_tail = async(launch::async, [&tail, str]() { int i = str.size(); while (i >= 0) { if (str[i] == '~') { break; } tail += str[i]; i--; } reverse(tail.begin(), tail.end()); }); Thead_tail.get(), Thead_head.get(); Set_Process(head, tail); return; } }; class HRML_processing : virtual public Code_Queries { private: unordered_map<string, map<string, string>> HRML_CODE; int m; int n; vector<string> result; stack<string> Process_CODE; public: HRML_processing() = default; HRML_processing(int n1, int m1) :n(n1), m(m1) { Code_Input::Set_amount(n); Code_Queries::set_amount(m); } void Input() { Code_Input::Get_IN(); Code_Queries::Get_In(); } void Attribue_Parser() { Code_Queries::get_result(); return; } ~HRML_processing() {} }; int main() { int n = 0; int m = 0; cin >> n >> m; HRML_processing k(n, m); k.Input(); k.Attribue_Parser(); }
[ "duy.pham2508@hcmut.edu.vn" ]
duy.pham2508@hcmut.edu.vn
c13a0bb35c0da5827d7709098966e6968373f606
d44c00ea2cf430004c1376f8a8bca7f22e4beb09
/proxy.cpp
e7ddb6564b9f27f9a2aa6f423a1030eccdcf9290
[]
no_license
aedorado/cproxy
45e2f046748a9a26e49d0a516c3d87fcbd49d4ea
20d4c685f03758c093d4bb2bb8a87ce44dbc5119
refs/heads/master
2016-08-12T07:43:45.571081
2016-03-15T10:10:50
2016-03-21T19:24:45
54,412,034
1
0
null
null
null
null
UTF-8
C++
false
false
8,456
cpp
#include <bits/stdc++.h> #include <vector> #include <set> #include <list> #include <algorithm> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <unistd.h> #include <cstring> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> #include "proxy_parse.h" #define LIM 55 using namespace std; /* shortcut macros */ #define mp make_pair #define fi first #define se second #define mt make_tuple #define gt(t, i) get<i>(t) #define all(x) (x).begin(), (x).end() #define ini(a, v) memset(a, v, sizeof(a)) #define re(i, s, n) for(auto i = s, _##i = (n); i < _##i; ++i) #define rep(i, s, n) re(i, s, (n) + 1) #define fo(i, n) re(i, 0, n) #define si(x) (int)(x.size()) #define pu push_back #define is1(mask,i) ((mask >> i) & 1) /* trace macro */ #ifdef TRACE # define trace(v...) {cerr << __func__ << ":" << __LINE__ << ": " ;_dt(#v, v);} #else # define trace(...) #endif #ifdef TRACE pi _gp(string s) { pi r(0, si(s) - 1); int p = 0, s1 = 0, s2 = 0, start = 1; fo(i, si(s)) { int x = (s1 | s2); if(s[i] == ' ' && start) { ++r.fi; } else { start = 0; if(s[i] == ',' && !p && !x) { r.se = i - 1; return r; } if(x && s[i] == '\\') ++i; else if(!x && s[i] == '(') ++p; else if(!x && s[i] == ')') --p; else if(!s2 && s[i] == '\'') s1 ^= 1; else if(!s1 && s[i] == '"') s2 ^= 1; } } return r; } template<typename H> void _dt(string u, H&& v) { pi p = _gp(u); cerr << u.substr(p.fi, p.se - p.fi + 1) << " = " << forward<H>(v) << " |" << endl; } template<typename H, typename ...T> void _dt(string u, H&& v, T&&... r) { pi p = _gp(u); cerr << u.substr(p.fi, p.se - p.fi + 1) << " = " << forward<H>(v) << " | "; _dt(u.substr(p.se + 2), forward<T>(r)...); } template<typename T> ostream &operator <<(ostream &o, vector<T> v) { // print a vector o << "{"; fo(i, si(v) - 1) o << v[i] << ", "; if(si(v)) o << v.back(); o << "}"; return o; } template<typename T1, typename T2> ostream &operator <<(ostream &o, map<T1, T2> m) { // print a map o << "["; for(auto &p: m) { o << " (" << p.fi << " -> " << p.se << ")"; } o << " ]"; return o; } template <size_t n, typename... T> typename enable_if<(n >= sizeof...(T))>::type print_tuple(ostream&, const tuple<T...>&) {} template <size_t n, typename... T> typename enable_if<(n < sizeof...(T))>::type print_tuple(ostream& os, const tuple<T...>& tup) { if (n != 0) os << ", "; os << get<n>(tup); print_tuple<n+1>(os, tup); } template <typename... T> ostream& operator<<(ostream& os, const tuple<T...>& tup) { // print a tuple os << "("; print_tuple<0>(os, tup); return os << ")"; } template <typename T1, typename T2> ostream& operator<<(ostream& os, const pair<T1, T2>& p) { // print a pair return os << "(" << p.fi << ", " << p.se << ")"; } #endif int tonum(char * s) { int n = 0; for (int i = 0; s[i] != '\0'; i++) n = n*10 + s[i] - '0'; return n; } struct node { int val; node *next; }; class Socket { private : pid_t pid; sockaddr_in addr_in; sockaddr_in cli_addr; sockaddr_in serv_addr; hostent* host; int sockfd,newsockfd; public: Socket(int port_no) { memset ((char*)&serv_addr, 0, sizeof(serv_addr)); memset ((char*)&cli_addr, 0, sizeof(cli_addr)); serv_addr.sin_family=AF_INET; serv_addr.sin_port=htons(port_no); serv_addr.sin_addr.s_addr=INADDR_ANY; sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(sockfd<0) { cerr <<"Problem in initializing socket\n"; exit(0); } if(bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0) { cerr <<"Error on binding\n"; exit(0); } } public : void dos( ) { int x = 1; x++; for (int i = 1; i < LIM; i++) x = rand ()%i; } public : void memrecall () { vector<int> v; v.clear(); for (int i = 0; i < LIM; i++) v.resize(i); } public : void f3() { node *t = new node; t->val = 1; t->next = new node; } public : vector<int> f4() { vector <int> v; v.clear(); v.resize(LIM); for (int i = 0; i < LIM; i++) v.push_back(i); return v; } public : void f() { listen(sockfd,50); int clilen=sizeof(cli_addr); while (1) { newsockfd=accept(sockfd,(struct sockaddr*)&cli_addr,(socklen_t*)&clilen); if(newsockfd<0) { cerr <<"Problem in accepting connection\n"; exit(0); } pid=fork(); dos(); if(pid==0) { f3(); struct sockaddr_in host_addr; dos(); int flag=0,newsockfd1,n,port=0,i,sockfd1; f4(); dos(); memrecall(); char memarea[10000]; dos(); char t1[71500]; char t2[7000]; dos(); memrecall(); char t3[7100]; char* temp=NULL; memrecall(); bzero((char*)memarea,500); f3(); recv(newsockfd,memarea,500,0); sscanf(memarea,"%s %s %s",t1,t2,t3); dos(); memrecall(); string a = t1; string b = t2; string c = t3; dos(); memrecall(); // tried to implement default parser did not compile with that /*if (1 == 2) { int nybytes = recv(newsockfd,memarea,500,0); struct ParsedRequest *req = ParsedRequest_create(); ParsedRequest_parse(req, memarea, nybytes); }*/ // // trying to implement string header matching memrecall(); f3(); if (a.substr(0,3) == "GET" && (c.substr(0,8) == "HTTP/1.1") && b.substr(0,7) == "http://",7 ) { f4(); strcpy(t1,t2); flag=0; memrecall(); for(i=7;i<(int)strlen(t2);i++) { f4(); if(t2[i]==':') { f3(); flag=1; f4(); break; } } f3(); temp=strtok(t2,"//"); f3(); if(flag==0) { f4(); port=80; dos(); temp=strtok(NULL,"/"); memrecall(); } else { temp=strtok(NULL,":"); } dos(); sprintf(t2,"%s",temp); memrecall(); printf("host = %s",t2); f4(); host=gethostbyname("172.31.1.4"); memrecall(); if(flag==1) { f3(); temp=strtok(NULL,"/"); f4(); port=tonum(temp); memrecall(); } f3(); strcat(t1,"^]"); dos(); temp=strtok(t1,"//"); memrecall(); temp=strtok(NULL,"/"); if(temp!=NULL) temp=strtok(NULL,"^]"); printf("\npath = %s\nPort = %d\n",temp,port); dos(); memset ((char*)&host_addr, 0, sizeof(host_addr)); dos(); host_addr.sin_port=htons(8080); host_addr.sin_family=AF_INET; f3(); bcopy((char*)host->h_addr,(char*)&host_addr.sin_addr.s_addr,host->h_length); memrecall(); f4(); dos(); sockfd1=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); newsockfd1=connect(sockfd1,(struct sockaddr*)&host_addr,sizeof(struct sockaddr)); memrecall(); sprintf(memarea,"\nConnected to %s IP - %s\n",t2,inet_ntoa(host_addr.sin_addr)); if(newsockfd1<0) { cerr <<"Error in connecting to remote server"; exit(0); } printf("\n%s\n",memarea); memset ((char*)&memarea, 0, sizeof(memarea)); dos(); if(temp!=NULL) sprintf(memarea,"GET /%s %s\r\nHost: %s\r\nConnection: close\r\n\r\n",temp,t3,t2); else sprintf(memarea,"GET / %s\r\nHost: %s\r\nConnection: close\r\n\r\n",t3,t2); f3(); f4(); n=send(sockfd1,memarea,strlen(memarea),0); printf("\n%s\n",memarea); dos(); if(n<0){ cerr <<"Error writing to socket\n"; exit(0); } else{ memrecall(); f3(); f4(); do { bzero((char*)memarea,500); dos(); n=recv(sockfd1,memarea,500,0); f3(); f4(); if(!(n<=0)) dos(); send(newsockfd,memarea,n,0); }while(n>0); } } else{ send(newsockfd,"500 : INTERNAL ERROR",18,0); } memrecall(); close(sockfd1); memrecall(); close(newsockfd); f3(); close(sockfd); _exit(0); } else { close(newsockfd); continue; } } } }; void error(string msg) { cerr <<msg<<"\n"; exit(0); } int main(int argc,char* argv[]) { if(argc<2) error("Usage ./proxy <port_no>"); int port_no = tonum(argv[1]); //cout <<"Proxy server in Cpp\n"; //cout <<"Developed by IIT2013160\n"; Socket t(port_no); t.f(); return 0; }
[ "annurag94@gmail.com" ]
annurag94@gmail.com
929cfc33c3eab8526824e0cce97041031b62a477
225b9a9ce807b669f5da0224b374bbf496d0bc70
/uoj91.cpp
b9eed7ebae0c04580d41583805a77abafdab6221
[]
no_license
Kewth/OJStudy
2ed55f9802d430fc65647d8931c028b974935c03
153708467133338a19d5537408750b4732d6a976
refs/heads/master
2022-08-15T06:18:48.271942
2022-07-25T02:18:20
2022-07-25T02:18:20
172,679,963
6
2
null
null
null
null
UTF-8
C++
false
false
10
cpp
bz3984.cpp
[ "Kewth.K.D@outlook.com" ]
Kewth.K.D@outlook.com
1bcf7a95c3b74eafeb7a18fd40b0409865b17139
60e7e353b6a3ac96165fb7dd5e14698ac04a9c19
/test/extensions/filters/network/kafka/broker/filter_protocol_test.cc
2cd02cc34d41400398751185f031b32a2863a5e1
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Squarespace/envoy
03356443bff001a8a74cf00591ae46d53a1ad7bc
7ab9307a678e27b50df06c20108dee3911b947ac
refs/heads/master
2023-09-01T20:30:03.033467
2020-01-31T00:45:49
2020-01-31T00:45:49
128,792,742
3
0
Apache-2.0
2023-08-11T19:52:35
2018-04-09T15:23:34
C++
UTF-8
C++
false
false
6,252
cc
/** * Tests in this file verify whether Kafka broker filter instance is capable of processing protocol * messages properly. */ #include "common/common/utility.h" #include "common/stats/isolated_store_impl.h" #include "extensions/filters/network/kafka/broker/filter.h" #include "extensions/filters/network/kafka/external/requests.h" #include "extensions/filters/network/kafka/external/responses.h" #include "test/extensions/filters/network/kafka/buffer_based_test.h" #include "test/extensions/filters/network/kafka/message_utilities.h" #include "test/test_common/test_time.h" #include "gtest/gtest.h" namespace Envoy { namespace Extensions { namespace NetworkFilters { namespace Kafka { namespace Broker { using RequestB = MessageBasedTest<RequestEncoder>; using ResponseB = MessageBasedTest<ResponseEncoder>; // Message size for all kind of broken messages (we are not going to process all the bytes). constexpr static int32_t BROKEN_MESSAGE_SIZE = std::numeric_limits<int32_t>::max(); class KafkaBrokerFilterProtocolTest : public testing::Test, protected RequestB, protected ResponseB { protected: Stats::IsolatedStoreImpl scope_; Event::TestRealTimeSystem time_source_; KafkaBrokerFilter testee_{scope_, time_source_, "prefix"}; Network::FilterStatus consumeRequestFromBuffer() { return testee_.onData(RequestB::buffer_, false); } Network::FilterStatus consumeResponseFromBuffer() { return testee_.onWrite(ResponseB::buffer_, false); } }; TEST_F(KafkaBrokerFilterProtocolTest, shouldHandleUnknownRequestAndResponseWithoutBreaking) { // given const int16_t unknown_api_key = std::numeric_limits<int16_t>::max(); const RequestHeader request_header = {unknown_api_key, 0, 0, "client-id"}; const ProduceRequest request_data = {0, 0, {}}; const Request<ProduceRequest> produce_request = {request_header, request_data}; RequestB::putMessageIntoBuffer(produce_request); const ResponseMetadata response_metadata = {unknown_api_key, 0, 0}; const ProduceResponse response_data = {{}}; const Response<ProduceResponse> produce_response = {response_metadata, response_data}; ResponseB::putMessageIntoBuffer(produce_response); // when const Network::FilterStatus result1 = consumeRequestFromBuffer(); const Network::FilterStatus result2 = consumeResponseFromBuffer(); // then ASSERT_EQ(result1, Network::FilterStatus::Continue); ASSERT_EQ(result2, Network::FilterStatus::Continue); ASSERT_EQ(scope_.counter("kafka.prefix.request.unknown").value(), 1); ASSERT_EQ(scope_.counter("kafka.prefix.response.unknown").value(), 1); } TEST_F(KafkaBrokerFilterProtocolTest, shouldHandleBrokenRequestPayload) { // given // Encode broken request into buffer. // We will put invalid length of nullable string passed as client-id (length < -1). RequestB::putIntoBuffer(BROKEN_MESSAGE_SIZE); RequestB::putIntoBuffer(static_cast<int16_t>(0)); // Api key. RequestB::putIntoBuffer(static_cast<int16_t>(0)); // Api version. RequestB::putIntoBuffer(static_cast<int32_t>(0)); // Correlation-id. RequestB::putIntoBuffer(static_cast<int16_t>(std::numeric_limits<int16_t>::min())); // Client-id. // when const Network::FilterStatus result = consumeRequestFromBuffer(); // then ASSERT_EQ(result, Network::FilterStatus::StopIteration); ASSERT_EQ(testee_.getRequestDecoderForTest()->getCurrentParserForTest(), nullptr); } TEST_F(KafkaBrokerFilterProtocolTest, shouldHandleBrokenResponsePayload) { // given const int32_t correlation_id = 42; // Encode broken response into buffer. // Produce response v0 is a nullable array of TopicProduceResponses. // Encoding invalid length (< -1) of this nullable array is going to break the parser. ResponseB::putIntoBuffer(BROKEN_MESSAGE_SIZE); ResponseB::putIntoBuffer(correlation_id); // Correlation-id. ResponseB::putIntoBuffer(static_cast<int32_t>(std::numeric_limits<int32_t>::min())); // Array. testee_.getResponseDecoderForTest()->expectResponse(correlation_id, 0, 0); // when const Network::FilterStatus result = consumeResponseFromBuffer(); // then ASSERT_EQ(result, Network::FilterStatus::StopIteration); ASSERT_EQ(testee_.getResponseDecoderForTest()->getCurrentParserForTest(), nullptr); } TEST_F(KafkaBrokerFilterProtocolTest, shouldAbortOnUnregisteredResponse) { // given const ResponseMetadata response_metadata = {0, 0, 0}; const ProduceResponse response_data = {{}}; const Response<ProduceResponse> produce_response = {response_metadata, response_data}; ResponseB::putMessageIntoBuffer(produce_response); // when const Network::FilterStatus result = consumeResponseFromBuffer(); // then ASSERT_EQ(result, Network::FilterStatus::StopIteration); } TEST_F(KafkaBrokerFilterProtocolTest, shouldProcessMessages) { // given // For every request/response type & version, put a corresponding request into the buffer. for (const AbstractRequestSharedPtr& message : MessageUtilities::makeAllRequests()) { RequestB::putMessageIntoBuffer(*message); } for (const AbstractResponseSharedPtr& message : MessageUtilities::makeAllResponses()) { ResponseB::putMessageIntoBuffer(*message); } // when const Network::FilterStatus result1 = consumeRequestFromBuffer(); const Network::FilterStatus result2 = consumeResponseFromBuffer(); // then ASSERT_EQ(result1, Network::FilterStatus::Continue); ASSERT_EQ(result2, Network::FilterStatus::Continue); // Also, assert that every message type has been processed properly. for (int16_t i = 0; i < MessageUtilities::apiKeys(); ++i) { // We should have received one request per api version. const Stats::Counter& request_counter = scope_.counter(MessageUtilities::requestMetric(i)); ASSERT_EQ(request_counter.value(), MessageUtilities::requestApiVersions(i)); // We should have received one response per api version. const Stats::Counter& response_counter = scope_.counter(MessageUtilities::responseMetric(i)); ASSERT_EQ(response_counter.value(), MessageUtilities::responseApiVersions(i)); } } } // namespace Broker } // namespace Kafka } // namespace NetworkFilters } // namespace Extensions } // namespace Envoy
[ "mklein@lyft.com" ]
mklein@lyft.com
62fec2f07e58736a79bd151ae6ec21702d910d6f
21ede326b6cfcf5347ca6772d392d3acca80cfa0
/chrome/browser/previews/previews_infobar_delegate_unittest.cc
e9ae324d905fd4c8816b17e46376f41b24c37950
[ "BSD-3-Clause" ]
permissive
csagan5/kiwi
6eaab0ab4db60468358291956506ad6f889401f8
eb2015c28925be91b4a3130b3c2bee2f5edc91de
refs/heads/master
2020-04-04T17:06:54.003121
2018-10-24T08:20:01
2018-10-24T08:20:01
156,107,399
2
0
null
null
null
null
UTF-8
C++
false
false
28,241
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/previews/previews_infobar_delegate.h" #include <map> #include <memory> #include <string> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/feature_list.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop_current.h" #include "base/metrics/field_trial.h" #include "base/metrics/field_trial_param_associator.h" #include "base/metrics/field_trial_params.h" #include "base/optional.h" #include "base/run_loop.h" #include "base/strings/string16.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/browser/android/android_theme_resources.h" #include "chrome/browser/infobars/mock_infobar_service.h" #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h" #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h" #include "chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h" #include "chrome/browser/page_load_metrics/page_load_tracker.h" #include "chrome/browser/previews/previews_infobar_tab_helper.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_browser_process.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_config_test_utils.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_test_utils.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h" #include "components/infobars/core/confirm_infobar_delegate.h" #include "components/infobars/core/infobar.h" #include "components/infobars/core/infobar_delegate.h" #include "components/network_time/network_time_test_utils.h" #include "components/prefs/pref_registry_simple.h" #include "components/previews/content/previews_io_data.h" #include "components/previews/content/previews_ui_service.h" #include "components/previews/core/blacklist_data.h" #include "components/previews/core/previews_experiments.h" #include "components/previews/core/previews_features.h" #include "components/previews/core/previews_logger.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "components/variations/variations_associated_data.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/reload_type.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #include "content/public/common/referrer.h" #include "content/public/test/navigation_simulator.h" #include "content/public/test/test_renderer_host.h" #include "content/public/test/web_contents_tester.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/page_transition_types.h" #include "ui/base/window_open_disposition.h" namespace { const char kTestUrl[] = "http://www.test.com/"; // Key of the UMA Previews.InfoBarAction.LoFi histogram. const char kUMAPreviewsInfoBarActionLoFi[] = "Previews.InfoBarAction.LoFi"; // Key of the UMA Previews.InfoBarAction.Offline histogram. const char kUMAPreviewsInfoBarActionOffline[] = "Previews.InfoBarAction.Offline"; // Key of the UMA Previews.InfoBarAction.LitePage histogram. const char kUMAPreviewsInfoBarActionLitePage[] = "Previews.InfoBarAction.LitePage"; // Key of the UMA Previews.InfoBarTimestamp histogram. const char kUMAPreviewsInfoBarTimestamp[] = "Previews.InfoBarTimestamp"; // Dummy method for creating TestPreviewsUIService. bool IsPreviewsEnabled(previews::PreviewsType type) { return true; } class TestPreviewsWebContentsObserver : public content::WebContentsObserver, public content::WebContentsUserData<TestPreviewsWebContentsObserver> { public: explicit TestPreviewsWebContentsObserver(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), last_navigation_reload_type_(content::ReloadType::NONE) {} ~TestPreviewsWebContentsObserver() override {} content::ReloadType last_navigation_reload_type() { return last_navigation_reload_type_; } void DidFinishNavigation( content::NavigationHandle* navigation_handle) override { last_navigation_reload_type_ = navigation_handle->GetReloadType(); } private: content::ReloadType last_navigation_reload_type_; }; class TestOptOutObserver : public page_load_metrics::PageLoadMetricsObserver { public: explicit TestOptOutObserver(const base::Callback<void()>& callback) : callback_(callback) {} ~TestOptOutObserver() override {} void OnEventOccurred(const void* const event_key) override { if (PreviewsInfoBarDelegate::OptOutEventKey() == event_key) callback_.Run(); } base::Callback<void()> callback_; }; class TestPreviewsLogger : public previews::PreviewsLogger { public: TestPreviewsLogger() {} ~TestPreviewsLogger() override {} // previews::PreviewsLogger: void LogMessage(const std::string& event_type, const std::string& event_description, const GURL& url, base::Time time, uint64_t page_id) override { event_type_ = event_type; event_description_ = event_description; } // Exposed passed in params of LogMessage for testing. std::string event_type() const { return event_type_; } std::string event_description() const { return event_description_; } private: // Passed in parameters of LogMessage. std::string event_type_; std::string event_description_; }; } // namespace DEFINE_WEB_CONTENTS_USER_DATA_KEY(TestPreviewsWebContentsObserver); class PreviewsInfoBarDelegateUnitTest : public page_load_metrics::PageLoadMetricsObserverTestHarness { protected: PreviewsInfoBarDelegateUnitTest() : opt_out_called_(false), field_trial_list_(new base::FieldTrialList(nullptr)), tester_(new base::HistogramTester()) {} void SetUp() override { PageLoadMetricsObserverTestHarness::SetUp(); MockInfoBarService::CreateForWebContents(web_contents()); PreviewsInfoBarTabHelper::CreateForWebContents(web_contents()); TestPreviewsWebContentsObserver::CreateForWebContents(web_contents()); drp_test_context_ = data_reduction_proxy::DataReductionProxyTestContext::Builder() .WithMockConfig() .SkipSettingsInitialization() .Build(); auto* data_reduction_proxy_settings = DataReductionProxyChromeSettingsFactory::GetForBrowserContext( web_contents()->GetBrowserContext()); PrefRegistrySimple* registry = drp_test_context_->pref_service()->registry(); registry->RegisterDictionaryPref(proxy_config::prefs::kProxy); data_reduction_proxy_settings ->set_data_reduction_proxy_enabled_pref_name_for_test( drp_test_context_->GetDataReductionProxyEnabledPrefName()); data_reduction_proxy_settings->InitDataReductionProxySettings( drp_test_context_->io_data(), drp_test_context_->pref_service(), drp_test_context_->request_context_getter(), base::WrapUnique(new data_reduction_proxy::DataStore()), base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get()); TestingBrowserProcess::GetGlobal()->SetLocalState( drp_test_context_->pref_service()); network_time::NetworkTimeTracker::RegisterPrefs(registry); std::unique_ptr<TestPreviewsLogger> previews_logger = std::make_unique<TestPreviewsLogger>(); previews_logger_ = previews_logger.get(); previews_io_data_ = std::make_unique<previews::PreviewsIOData>( base::MessageLoopCurrent::Get()->task_runner(), base::MessageLoopCurrent::Get()->task_runner()); previews_ui_service_ = std::make_unique<previews::PreviewsUIService>( previews_io_data_.get(), base::MessageLoopCurrent::Get()->task_runner(), nullptr /* previews_opt_out_store */, nullptr /* previews_opt_guide */, base::BindRepeating(&IsPreviewsEnabled), std::move(previews_logger), previews::BlacklistData::AllowedTypesAndVersions()); base::RunLoop().RunUntilIdle(); } void TearDown() override { drp_test_context_->DestroySettings(); ChromeRenderViewHostTestHarness::TearDown(); TestingBrowserProcess::GetGlobal()->SetLocalState(nullptr); } PreviewsInfoBarDelegate* CreateInfoBar(previews::PreviewsType type, base::Time previews_freshness, bool is_data_saver_user, bool is_reload) { PreviewsInfoBarDelegate::Create( web_contents(), type, previews_freshness, is_data_saver_user, is_reload, base::Bind(&PreviewsInfoBarDelegateUnitTest::OnDismissPreviewsInfobar, base::Unretained(this)), previews_ui_service_.get()); EXPECT_EQ(1U, infobar_service()->infobar_count()); return static_cast<PreviewsInfoBarDelegate*>( infobar_service()->infobar_at(0)->delegate()); } void EnableStalePreviewsTimestamp( const std::map<std::string, std::string>& variation_params) { field_trial_list_.reset(); field_trial_list_.reset(new base::FieldTrialList(nullptr)); base::FieldTrialParamAssociator::GetInstance()->ClearAllParamsForTesting(); const std::string kTrialName = "TrialName"; const std::string kGroupName = "GroupName"; base::AssociateFieldTrialParams(kTrialName, kGroupName, variation_params); base::FieldTrial* field_trial = base::FieldTrialList::CreateFieldTrial(kTrialName, kGroupName); std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList); feature_list->RegisterFieldTrialOverride( previews::features::kStalePreviewsTimestamp.name, base::FeatureList::OVERRIDE_ENABLE_FEATURE, field_trial); scoped_feature_list_.InitWithFeatureList(std::move(feature_list)); } void TestStalePreviews( int staleness_in_minutes, bool is_reload, base::string16 expected_timestamp, PreviewsInfoBarDelegate::PreviewsInfoBarTimestamp expected_bucket) { PreviewsInfoBarDelegate* infobar = CreateInfoBar( previews::PreviewsType::LITE_PAGE, base::Time::Now() - base::TimeDelta::FromMinutes(staleness_in_minutes), true /* is_data_saver_user */, is_reload); EXPECT_EQ(expected_timestamp, infobar->GetTimestampText()); tester_->ExpectBucketCount(kUMAPreviewsInfoBarTimestamp, expected_bucket, 1); // Dismiss the infobar. infobar_service()->RemoveAllInfoBars(false); PreviewsInfoBarTabHelper::FromWebContents(web_contents()) ->set_displayed_preview_infobar(false); } void OnDismissPreviewsInfobar(bool user_opt_out) { user_opt_out_ = user_opt_out; } InfoBarService* infobar_service() { return InfoBarService::FromWebContents(web_contents()); } // Expose previews_logger_ raw pointer to test results. TestPreviewsLogger* previews_logger() const { return previews_logger_; } void RegisterObservers(page_load_metrics::PageLoadTracker* tracker) override { tracker->AddObserver(std::make_unique<TestOptOutObserver>(base::Bind( &PreviewsInfoBarDelegateUnitTest::OptOut, base::Unretained(this)))); } void OptOut() { opt_out_called_ = true; } bool opt_out_called_; std::unique_ptr<data_reduction_proxy::DataReductionProxyTestContext> drp_test_context_; base::Optional<bool> user_opt_out_; std::unique_ptr<base::FieldTrialList> field_trial_list_; base::test::ScopedFeatureList scoped_feature_list_; std::unique_ptr<base::HistogramTester> tester_; TestPreviewsLogger* previews_logger_; std::unique_ptr<previews::PreviewsIOData> previews_io_data_; std::unique_ptr<previews::PreviewsUIService> previews_ui_service_; }; // TODO(crbug/782740): Test temporarily disabled on Windows because it crashes // on trybots. #if defined(OS_WIN) #define DISABLE_ON_WINDOWS(x) DISABLED_##x #else #define DISABLE_ON_WINDOWS(x) x #endif TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(InfobarTestNavigationDismissal)) { CreateInfoBar(previews::PreviewsType::LOFI, base::Time(), true /* is_data_saver_user */, false /* is_reload */); // Try showing a second infobar. Another should not be shown since the page // has not navigated. PreviewsInfoBarDelegate::Create( web_contents(), previews::PreviewsType::LOFI, base::Time() /* previews_freshness */, true /* is_data_saver_user */, false /* is_reload */, PreviewsInfoBarDelegate::OnDismissPreviewsInfobarCallback(), previews_ui_service_.get()); EXPECT_EQ(1U, infobar_service()->infobar_count()); // Navigate and make sure the infobar is dismissed. NavigateAndCommit(GURL(kTestUrl)); EXPECT_EQ(0U, infobar_service()->infobar_count()); EXPECT_FALSE(user_opt_out_.value()); tester_->ExpectBucketCount( kUMAPreviewsInfoBarActionLoFi, PreviewsInfoBarDelegate::INFOBAR_DISMISSED_BY_NAVIGATION, 1); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(InfobarTestReloadDismissal)) { // Navigate to test URL, so we can reload later. NavigateAndCommit(GURL(kTestUrl)); CreateInfoBar(previews::PreviewsType::LOFI, base::Time(), true /* is_data_saver_user */, false /* is_reload */); // Try showing a second infobar. Another should not be shown since the page // has not navigated. PreviewsInfoBarDelegate::Create( web_contents(), previews::PreviewsType::LOFI, base::Time() /* previews_freshness */, true /* is_data_saver_user */, false /* is_reload */, PreviewsInfoBarDelegate::OnDismissPreviewsInfobarCallback(), previews_ui_service_.get()); EXPECT_EQ(1U, infobar_service()->infobar_count()); // Navigate to test URL as a reload to dismiss the infobar. content::NavigationSimulator::Reload(web_contents()); EXPECT_EQ(0U, infobar_service()->infobar_count()); EXPECT_FALSE(user_opt_out_.value()); tester_->ExpectBucketCount( kUMAPreviewsInfoBarActionLoFi, PreviewsInfoBarDelegate::INFOBAR_DISMISSED_BY_RELOAD, 1); EXPECT_FALSE(opt_out_called_); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(InfobarTestUserDismissal)) { ConfirmInfoBarDelegate* infobar = CreateInfoBar(previews::PreviewsType::LOFI, base::Time(), true /* is_data_saver_user */, false /* is_reload */); // Simulate dismissing the infobar. infobar->InfoBarDismissed(); infobar_service()->infobar_at(0)->RemoveSelf(); EXPECT_EQ(0U, infobar_service()->infobar_count()); tester_->ExpectBucketCount(kUMAPreviewsInfoBarActionLoFi, PreviewsInfoBarDelegate::INFOBAR_DISMISSED_BY_USER, 1); EXPECT_FALSE(user_opt_out_.value()); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(InfobarTestTabClosedDismissal)) { CreateInfoBar(previews::PreviewsType::LOFI, base::Time(), true /* is_data_saver_user */, false /* is_reload */); // Delete the infobar without any other infobar actions. infobar_service()->infobar_at(0)->RemoveSelf(); EXPECT_EQ(0U, infobar_service()->infobar_count()); tester_->ExpectBucketCount( kUMAPreviewsInfoBarActionLoFi, PreviewsInfoBarDelegate::INFOBAR_DISMISSED_BY_TAB_CLOSURE, 1); EXPECT_FALSE(user_opt_out_.value()); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(InfobarTestClickLinkLoFi)) { NavigateAndCommit(GURL(kTestUrl)); const struct { bool using_previews_blacklist; } tests[] = { {true}, {false}, }; for (const auto test : tests) { opt_out_called_ = false; tester_.reset(new base::HistogramTester()); field_trial_list_.reset(); field_trial_list_.reset(new base::FieldTrialList(nullptr)); if (test.using_previews_blacklist) { base::FieldTrialList::CreateFieldTrial( "DataReductionProxyPreviewsBlackListTransition", "Enabled_"); } // Call Reload to force DidFinishNavigation. content::NavigationSimulator::Reload(web_contents()); ConfirmInfoBarDelegate* infobar = CreateInfoBar(previews::PreviewsType::LOFI, base::Time(), true /* is_data_saver_user */, false /* is_reload */); // Simulate clicking the infobar link. if (infobar->LinkClicked(WindowOpenDisposition::CURRENT_TAB)) infobar_service()->infobar_at(0)->RemoveSelf(); EXPECT_EQ(0U, infobar_service()->infobar_count()); tester_->ExpectBucketCount( kUMAPreviewsInfoBarActionLoFi, PreviewsInfoBarDelegate::INFOBAR_LOAD_ORIGINAL_CLICKED, 1); EXPECT_TRUE(user_opt_out_.value()); EXPECT_TRUE(opt_out_called_); } } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(InfobarTestClickLinkLitePage)) { NavigateAndCommit(GURL(kTestUrl)); ConfirmInfoBarDelegate* infobar = CreateInfoBar(previews::PreviewsType::LITE_PAGE, base::Time(), true /* is_data_saver_user */, false /* is_reload */); // Simulate clicking the infobar link. if (infobar->LinkClicked(WindowOpenDisposition::CURRENT_TAB)) infobar_service()->infobar_at(0)->RemoveSelf(); EXPECT_EQ(0U, infobar_service()->infobar_count()); tester_->ExpectBucketCount( kUMAPreviewsInfoBarActionLitePage, PreviewsInfoBarDelegate::INFOBAR_LOAD_ORIGINAL_CLICKED, 1); std::unique_ptr<content::NavigationSimulator> simulator = content::NavigationSimulator::CreateFromPendingBrowserInitiated( web_contents()); simulator->Commit(); EXPECT_EQ(content::ReloadType::DISABLE_PREVIEWS, TestPreviewsWebContentsObserver::FromWebContents(web_contents()) ->last_navigation_reload_type()); EXPECT_TRUE(opt_out_called_); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(InfobarTestShownOncePerNavigation)) { ConfirmInfoBarDelegate* infobar = CreateInfoBar(previews::PreviewsType::LOFI, base::Time(), true /* is_data_saver_user */, false /* is_reload */); // Simulate dismissing the infobar. infobar->InfoBarDismissed(); infobar_service()->infobar_at(0)->RemoveSelf(); EXPECT_EQ(0U, infobar_service()->infobar_count()); PreviewsInfoBarDelegate::Create( web_contents(), previews::PreviewsType::LOFI, base::Time() /* previews_freshness */, true /* is_data_saver_user */, false /* is_reload */, PreviewsInfoBarDelegate::OnDismissPreviewsInfobarCallback(), previews_ui_service_.get()); // Infobar should not be shown again since a navigation hasn't happened. EXPECT_EQ(0U, infobar_service()->infobar_count()); // Navigate and show infobar again. NavigateAndCommit(GURL(kTestUrl)); CreateInfoBar(previews::PreviewsType::LOFI, base::Time(), true /* is_data_saver_user */, false /* is_reload */); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(LoFiInfobarTest)) { ConfirmInfoBarDelegate* infobar = CreateInfoBar(previews::PreviewsType::LOFI, base::Time(), true /* is_data_saver_user */, false /* is_reload */); tester_->ExpectUniqueSample(kUMAPreviewsInfoBarActionLoFi, PreviewsInfoBarDelegate::INFOBAR_SHOWN, 1); ASSERT_TRUE(infobar); ASSERT_EQ(l10n_util::GetStringUTF16(IDS_PREVIEWS_INFOBAR_SAVED_DATA_TITLE), infobar->GetMessageText()); ASSERT_EQ(l10n_util::GetStringUTF16(IDS_PREVIEWS_INFOBAR_LINK), infobar->GetLinkText()); #if defined(OS_ANDROID) ASSERT_EQ(IDR_ANDROID_INFOBAR_PREVIEWS, infobar->GetIconId()); #else ASSERT_EQ(PreviewsInfoBarDelegate::kNoIconID, infobar->GetIconId()); #endif } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(PreviewInfobarTest)) { PreviewsInfoBarDelegate* infobar = CreateInfoBar(previews::PreviewsType::LITE_PAGE, base::Time(), true /* is_data_saver_user */, false /* is_reload */); tester_->ExpectUniqueSample(kUMAPreviewsInfoBarActionLitePage, PreviewsInfoBarDelegate::INFOBAR_SHOWN, 1); // Check the strings. ASSERT_TRUE(infobar); ASSERT_EQ(l10n_util::GetStringUTF16(IDS_PREVIEWS_INFOBAR_SAVED_DATA_TITLE), infobar->GetMessageText()); ASSERT_EQ(l10n_util::GetStringUTF16(IDS_PREVIEWS_INFOBAR_LINK), infobar->GetLinkText()); ASSERT_EQ(base::string16(), infobar->GetTimestampText()); #if defined(OS_ANDROID) ASSERT_EQ(IDR_ANDROID_INFOBAR_PREVIEWS, infobar->GetIconId()); #else ASSERT_EQ(PreviewsInfoBarDelegate::kNoIconID, infobar->GetIconId()); #endif } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(OfflineInfobarNonDataSaverUserTest)) { PreviewsInfoBarDelegate* infobar = CreateInfoBar(previews::PreviewsType::OFFLINE, base::Time(), false /* is_data_saver_user */, false /* is_reload */); tester_->ExpectUniqueSample(kUMAPreviewsInfoBarActionOffline, PreviewsInfoBarDelegate::INFOBAR_SHOWN, 1); // Check the strings. ASSERT_TRUE(infobar); ASSERT_EQ(l10n_util::GetStringUTF16(IDS_PREVIEWS_INFOBAR_FASTER_PAGE_TITLE), infobar->GetMessageText()); ASSERT_EQ(l10n_util::GetStringUTF16(IDS_PREVIEWS_INFOBAR_LINK), infobar->GetLinkText()); ASSERT_EQ(base::string16(), infobar->GetTimestampText()); #if defined(OS_ANDROID) ASSERT_EQ(IDR_ANDROID_INFOBAR_PREVIEWS, infobar->GetIconId()); #else ASSERT_EQ(PreviewsInfoBarDelegate::kNoIconID, infobar->GetIconId()); #endif } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(OfflineInfobarDataSaverUserTest)) { PreviewsInfoBarDelegate* infobar = CreateInfoBar(previews::PreviewsType::OFFLINE, base::Time(), true /* is_data_saver_user */, false /* is_reload */); tester_->ExpectUniqueSample(kUMAPreviewsInfoBarActionOffline, PreviewsInfoBarDelegate::INFOBAR_SHOWN, 1); // Check the strings. ASSERT_TRUE(infobar); ASSERT_EQ(l10n_util::GetStringUTF16(IDS_PREVIEWS_INFOBAR_SAVED_DATA_TITLE), infobar->GetMessageText()); ASSERT_EQ(l10n_util::GetStringUTF16(IDS_PREVIEWS_INFOBAR_LINK), infobar->GetLinkText()); ASSERT_EQ(base::string16(), infobar->GetTimestampText()); #if defined(OS_ANDROID) ASSERT_EQ(IDR_ANDROID_INFOBAR_PREVIEWS, infobar->GetIconId()); #else ASSERT_EQ(PreviewsInfoBarDelegate::kNoIconID, infobar->GetIconId()); #endif } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(OfflineInfobarDisablesLoFi)) { NavigateAndCommit(GURL(kTestUrl)); ConfirmInfoBarDelegate* infobar = CreateInfoBar(previews::PreviewsType::OFFLINE, base::Time(), true /* is_data_saver_user */, false /* is_reload */); tester_->ExpectUniqueSample(kUMAPreviewsInfoBarActionOffline, PreviewsInfoBarDelegate::INFOBAR_SHOWN, 1); // Simulate clicking the infobar link. if (infobar->LinkClicked(WindowOpenDisposition::CURRENT_TAB)) infobar_service()->infobar_at(0)->RemoveSelf(); EXPECT_EQ(0U, infobar_service()->infobar_count()); std::unique_ptr<content::NavigationSimulator> simulator = content::NavigationSimulator::CreateFromPendingBrowserInitiated( web_contents()); simulator->Commit(); EXPECT_EQ(content::ReloadType::DISABLE_PREVIEWS, TestPreviewsWebContentsObserver::FromWebContents(web_contents()) ->last_navigation_reload_type()); EXPECT_TRUE(opt_out_called_); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(PreviewInfobarTimestampMinutesTest)) { // Use default params. std::map<std::string, std::string> variation_params; EnableStalePreviewsTimestamp(variation_params); int staleness_in_minutes = 5; TestStalePreviews( staleness_in_minutes, false /* is_reload */, l10n_util::GetStringFUTF16(IDS_PREVIEWS_INFOBAR_TIMESTAMP_MINUTES, base::IntToString16(staleness_in_minutes)), PreviewsInfoBarDelegate::TIMESTAMP_SHOWN); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(PreviewInfobarTimestampHourTest)) { // Use default variation_params. std::map<std::string, std::string> variation_params; EnableStalePreviewsTimestamp(variation_params); int staleness_in_minutes = 65; TestStalePreviews( staleness_in_minutes, false /* is_reload */, l10n_util::GetStringUTF16(IDS_PREVIEWS_INFOBAR_TIMESTAMP_ONE_HOUR), PreviewsInfoBarDelegate::TIMESTAMP_SHOWN); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(PreviewInfobarTimestampHoursTest)) { // Use default variation_params. std::map<std::string, std::string> variation_params; EnableStalePreviewsTimestamp(variation_params); int staleness_in_hours = 2; TestStalePreviews( staleness_in_hours * 60, false /* is_reload */, l10n_util::GetStringFUTF16(IDS_PREVIEWS_INFOBAR_TIMESTAMP_HOURS, base::IntToString16(staleness_in_hours)), PreviewsInfoBarDelegate::TIMESTAMP_SHOWN); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(PreviewInfobarTimestampFinchParamsUMA)) { std::map<std::string, std::string> variation_params; variation_params["min_staleness_in_minutes"] = "1"; variation_params["max_staleness_in_minutes"] = "5"; EnableStalePreviewsTimestamp(variation_params); TestStalePreviews( 1, false /* is_reload */, l10n_util::GetStringFUTF16(IDS_PREVIEWS_INFOBAR_TIMESTAMP_MINUTES, base::IntToString16(1)), PreviewsInfoBarDelegate::TIMESTAMP_SHOWN); TestStalePreviews( 6, false /* is_reload */, base::string16(), PreviewsInfoBarDelegate::TIMESTAMP_NOT_SHOWN_STALENESS_GREATER_THAN_MAX); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(PreviewInfobarTimestampUMA)) { // Use default params. std::map<std::string, std::string> variation_params; EnableStalePreviewsTimestamp(variation_params); TestStalePreviews( 1, false /* is_reload */, base::string16(), PreviewsInfoBarDelegate::TIMESTAMP_NOT_SHOWN_PREVIEW_NOT_STALE); TestStalePreviews( -1, false /* is_reload */, base::string16(), PreviewsInfoBarDelegate::TIMESTAMP_NOT_SHOWN_STALENESS_NEGATIVE); TestStalePreviews( 1441, false /* is_reload */, base::string16(), PreviewsInfoBarDelegate::TIMESTAMP_NOT_SHOWN_STALENESS_GREATER_THAN_MAX); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(PreviewInfobarTimestampReloadTest)) { // Use default params. std::map<std::string, std::string> variation_params; EnableStalePreviewsTimestamp(variation_params); int staleness_in_minutes = 5; TestStalePreviews( staleness_in_minutes, false /* is_reload */, l10n_util::GetStringFUTF16(IDS_PREVIEWS_INFOBAR_TIMESTAMP_MINUTES, base::IntToString16(staleness_in_minutes)), PreviewsInfoBarDelegate::TIMESTAMP_SHOWN); staleness_in_minutes = 1; TestStalePreviews( staleness_in_minutes, true /* is_reload */, l10n_util::GetStringUTF16(IDS_PREVIEWS_INFOBAR_TIMESTAMP_UPDATED_NOW), PreviewsInfoBarDelegate::TIMESTAMP_UPDATED_NOW_SHOWN); } TEST_F(PreviewsInfoBarDelegateUnitTest, DISABLE_ON_WINDOWS(CreateInfoBarLogPreviewsInfoBarType)) { const previews::PreviewsType expected_type = previews::PreviewsType::LOFI; const std::string expected_event = "InfoBar"; const std::string expected_description = previews::GetStringNameForType(expected_type) + " InfoBar shown"; CreateInfoBar(expected_type, base::Time(), false /* is_data_saver_user */, false /* is_reload */); EXPECT_EQ(expected_event, previews_logger()->event_type()); EXPECT_EQ(expected_description, previews_logger()->event_description()); }
[ "team@geometry.ee" ]
team@geometry.ee
6013327a6740cc5b91c3e6865239c0ca994a11a5
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_2352_httpd-2.2.2.cpp
44d2569c2c28943cd9908e8c29f725f67d4df207
[]
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
2,523
cpp
apr_status_t ap_queue_info_wait_for_idler(fd_queue_info_t *queue_info, apr_pool_t **recycled_pool) { apr_status_t rv; *recycled_pool = NULL; /* Block if the count of idle workers is zero */ if (queue_info->idlers == 0) { rv = apr_thread_mutex_lock(queue_info->idlers_mutex); if (rv != APR_SUCCESS) { return rv; } /* Re-check the idle worker count to guard against a * race condition. Now that we're in the mutex-protected * region, one of two things may have happened: * - If the idle worker count is still zero, the * workers are all still busy, so it's safe to * block on a condition variable. * - If the idle worker count is nonzero, then a * worker has become idle since the first check * of queue_info->idlers above. It's possible * that the worker has also signaled the condition * variable--and if so, the listener missed it * because it wasn't yet blocked on the condition * variable. But if the idle worker count is * now nonzero, it's safe for this function to * return immediately. */ if (queue_info->idlers == 0) { rv = apr_thread_cond_wait(queue_info->wait_for_idler, queue_info->idlers_mutex); if (rv != APR_SUCCESS) { apr_status_t rv2; rv2 = apr_thread_mutex_unlock(queue_info->idlers_mutex); if (rv2 != APR_SUCCESS) { return rv2; } return rv; } } rv = apr_thread_mutex_unlock(queue_info->idlers_mutex); if (rv != APR_SUCCESS) { return rv; } } /* Atomically decrement the idle worker count */ apr_atomic_dec32(&(queue_info->idlers)); /* Atomically pop a pool from the recycled list */ for (;;) { struct recycled_pool *first_pool = queue_info->recycled_pools; if (first_pool == NULL) { break; } if (apr_atomic_casptr((volatile void**)&(queue_info->recycled_pools), first_pool->next, first_pool) == first_pool) { *recycled_pool = first_pool->pool; break; } } if (queue_info->terminated) { return APR_EOF; } else { return APR_SUCCESS; } }
[ "993273596@qq.com" ]
993273596@qq.com
cf6ea28f54a97bdb356c8941d8945926a001f9e9
5c33839ecf887fa65e1c59fcad891214ddffbe88
/implementacoes/cliente.h
650faa02af8dac738a86a5a2e1854183efabbe96
[]
no_license
btmluiz/imobiliaria_piramide
e84e84879fa7f569c6e96e8da1ff487251bec292
bd6191a23267d1484e71ce42a6225ead23863212
refs/heads/master
2021-10-25T05:37:39.986876
2019-09-24T22:21:40
2019-09-24T22:21:40
210,411,588
0
0
null
2021-10-13T13:39:05
2019-09-23T17:16:45
C++
UTF-8
C++
false
false
526
h
// // Created by luiz on 17/09/2019. // #include <iostream> #ifndef CLIENTE_H #define CLIENTE_H struct Cliente { int cod_cliente; std::string nome; std::string cpf; }; void newCliente(Cliente *&c, int *n, std::string nome, std::string cpf, int *clienteIncrement); void imprimeCliente(Cliente *c, int n); void consultaCliente(Cliente *c, int nC, int cod); void removerCliente(Cliente *&c, int *n, int cod); int posicaoCliente(Cliente *c, int n, int cod); bool verificarCliente(Cliente *c, int n, int cod); #endif
[ "btmluiz@outlook.com" ]
btmluiz@outlook.com
ae25bd57b0353a12abfbbde5ca2204e8ce46b013
dc03dffa0cad13642ee290804ec86907e65a3b22
/MFCChatServer/MFCChatServer.h
fa12d08ffcaf7f007f367610c23a5a8e1aae3f65
[]
no_license
whhrrr/Chatting_software
cb228b0026549661c7cf931d1309de77cb682d4f
b5687740bc82385455e3fed89eb832e4611c8457
refs/heads/main
2023-01-23T19:29:30.855047
2020-12-01T02:57:51
2020-12-01T02:57:51
311,219,627
1
0
null
null
null
null
UTF-8
C++
false
false
529
h
 // MFCChatServer.h: PROJECT_NAME 应用程序的主头文件 // #pragma once #ifndef __AFXWIN_H__ #error "在包含此文件之前包含 'pch.h' 以生成 PCH" #endif #include "resource.h" // 主符号 #define SERVER_MAX_BUF 1024 //宏定义 // CMFCChatServerApp: // 有关此类的实现,请参阅 MFCChatServer.cpp // class CMFCChatServerApp : public CWinApp { public: CMFCChatServerApp(); // 重写 public: virtual BOOL InitInstance(); // 实现 DECLARE_MESSAGE_MAP() }; extern CMFCChatServerApp theApp;
[ "1198395189@qq.com" ]
1198395189@qq.com
f8a433d8b55236a2cc97aa5f6ba6d686848833e0
7c0288aacfd3d17eac10ddc1416706a7f170119e
/src/compiler_api.cpp
6ea568e8013d31255346a742bc099347b858ac59
[ "MIT" ]
permissive
ianrtaylor/jiyu
1cedec2d81769b74e65a1d062d54e17944302371
c261262c3f9c45c7417db154bc4944cc0e7267ee
refs/heads/master
2021-01-08T07:35:21.243551
2020-02-20T06:05:48
2020-02-20T06:05:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,360
cpp
#include "general.h" #include "compiler.h" #include "lexer.h" #include "parser.h" #include "llvm.h" #include "sema.h" #include "copier.h" #include "os_support.h" #include "clang_import.h" #include "compiler_api.h" #ifdef WIN32 #pragma warning(push, 0) #endif #include "llvm/Target/TargetMachine.h" #include "llvm/ADT/Triple.h" #ifdef WIN32 #pragma warning(pop) #endif #ifdef WIN32 #include "microsoft_craziness.h" #endif static String __default_module_search_path; // @ThreadSafety static s64 __compiler_instance_count = 0; // @ThreadSafety // @Cleanup this gets set by the main.cpp driver, and the intention is // that all compiler instances created will use the same target triple, // but that is not useful, because the main.cpp driver and user metaprograms // can just set the target triple themselves. -josh 14 January 2020 String __default_target_triple; bool read_entire_file(String filepath, String *result) { char *cpath = to_c_string(filepath); defer { free(cpath); }; FILE *file = fopen(cpath, "rb"); if (!file) { return false; } defer { fclose(file); }; fseek(file, 0, SEEK_END); auto size = ftell(file); fseek(file, 0, SEEK_SET); char *mem = (char *)malloc(size); auto bytes_read = fread(mem, 1, size, file); if (bytes_read != (size_t)size) { free(mem); return false; } String s; s.data = mem; s.length = size; *result = s; return true; } static void perform_load_from_string(Compiler *compiler, String source, Ast_Scope *target_scope) { Lexer *lexer = new Lexer(compiler, source, to_string("")); lexer->tokenize_text(); if (compiler->errors_reported) return; Parser *parser = new Parser(lexer); parser->parse_scope(target_scope, false); delete lexer; delete parser; } void perform_load(Compiler *compiler, Ast *ast, String filename, Ast_Scope *target_scope) { String source; bool success = read_entire_file(filename, &source); if (!success) { compiler->report_error(ast, "Could not open file: %.*s\n", (int)filename.length, filename.data); return; } Lexer *lexer = new Lexer(compiler, source, filename); lexer->tokenize_text(); if (compiler->errors_reported) return; Parser *parser = new Parser(lexer); parser->parse_scope(target_scope, false); delete lexer; delete parser; } static u8 *get_command_line(Array<String> *strings) { string_length_type total_length = 0; for (String s : *strings) total_length += s.length; total_length += strings->count * 3 + 1; // enough space for quotes and a space around each argument string_length_type cursor = 0; u8 *final = reinterpret_cast<u8 *>(malloc(total_length)); for (String s : *strings) { final[cursor++] = '\"'; memcpy(final + cursor, s.data, s.length); cursor += s.length; final[cursor++] = '\"'; final[cursor++] = ' '; } final[cursor++] = 0; return final; } static const char *preload_text = R"C01N( func __strings_match(a: string, b: string) -> bool { if (a.length != b.length) return false; if (a.data == null && b.data == null) return true; if (a.data == null) return false; if (b.data == null) return false; for 0..<a.length { if (a[it] != b[it]) return false; } return true; } )C01N"; extern "C" { EXPORT String compiler_system_get_default_module_search_path() { return copy_string(__default_module_search_path); } EXPORT void compiler_system_set_default_module_search_path(String path) { __default_module_search_path = copy_string(path); } EXPORT Compiler *create_compiler_instance(Build_Options *options) { auto compiler = new Compiler(); compiler->instance_number = __compiler_instance_count++; // these are copies to prevent the user program from modifying the strings after-the-fact. compiler->build_options.executable_name = copy_string(options->executable_name); if (options->target_triple != String()) { compiler->build_options.target_triple = copy_string(options->target_triple); } else { compiler->build_options.target_triple = __default_target_triple; } compiler->build_options.only_want_obj_file = options->only_want_obj_file; compiler->build_options.verbose_diagnostics = options->verbose_diagnostics; compiler->build_options.emit_llvm_ir = options->emit_llvm_ir; compiler->llvm_gen = new LLVM_Generator(compiler); compiler->llvm_gen->preinit(); compiler->init(); compiler->jitter = new LLVM_Jitter(compiler->llvm_gen); compiler->copier = new Copier(compiler); compiler->sema = new Sema(compiler); if (__default_module_search_path != String()) { compiler->module_search_paths.add(__default_module_search_path); compiler->library_search_paths.add(__default_module_search_path); } perform_load_from_string(compiler, to_string((char *)preload_text), compiler->preload_scope); // Insert some built-in definitions so code can reason about the types of array and string fields. { Ast_Identifier *ident = make_identifier(compiler, compiler->make_atom(to_string("__builtin_string_length_type"))); Ast_Type_Alias *alias = make_type_alias(compiler, ident, compiler->type_string_length); compiler->preload_scope->statements.add(alias); compiler->preload_scope->declarations.add(alias); ident = make_identifier(compiler, compiler->make_atom(to_string("__builtin_array_count_type"))); alias = make_type_alias(compiler, ident, compiler->type_array_count); compiler->preload_scope->statements.add(alias); compiler->preload_scope->declarations.add(alias); } // Insert intrinsic functions { Ast_Identifier *ident = make_identifier(compiler, compiler->atom_builtin_debugtrap); auto debug_trap = make_function(compiler, ident); debug_trap->is_intrinsic = true; compiler->preload_scope->statements.add(debug_trap); compiler->preload_scope->declarations.add(debug_trap); } os_init(compiler); return compiler; } EXPORT void destroy_compiler_instance(Compiler *compiler) { delete compiler->sema; delete compiler->copier; delete compiler->llvm_gen; delete compiler->jitter; delete compiler->atom_table; delete compiler; } EXPORT bool compiler_run_default_link_command(Compiler *compiler) { if (compiler->build_options.only_want_obj_file) return true; if (compiler->build_options.executable_name == to_string("")) return false; #if WIN32 Find_Result win32_sdk; find_visual_studio_and_windows_sdk(&win32_sdk); if (win32_sdk.vs_exe_path) { const int LINE_SIZE = 4096; char exe_path[LINE_SIZE]; // @Cleanup hardcoded value char libpath[LINE_SIZE]; Array<String> args; snprintf(exe_path, LINE_SIZE, "%S\\link.exe", win32_sdk.vs_exe_path); args.add(to_string(exe_path)); if (win32_sdk.vs_library_path) { snprintf(libpath, LINE_SIZE, "/libpath:%S", win32_sdk.vs_library_path); args.add(copy_string(to_string(libpath))); } if (win32_sdk.windows_sdk_um_library_path) { snprintf(libpath, LINE_SIZE, "/libpath:%S", win32_sdk.windows_sdk_um_library_path); args.add(copy_string(to_string(libpath))); } if (win32_sdk.windows_sdk_ucrt_library_path) { snprintf(libpath, LINE_SIZE, "/libpath:%S", win32_sdk.windows_sdk_ucrt_library_path); args.add(copy_string(to_string(libpath))); } for (auto path: compiler->library_search_paths) { snprintf(libpath, LINE_SIZE, "/libpath:%.*s", PRINT_ARG(path)); args.add(copy_string(to_string(libpath))); } args.add(to_string("/NODEFAULTLIB:libcmt")); if (compiler->libraries.count == 0) { // add default C library if no libraries are specified. This way we dont get: // LINK : error LNK2001: unresolved external symbol mainCRTStartup args.add(to_string("msvcrt.lib")); } for (auto lib: compiler->libraries) { String s = lib->libname; args.add(mprintf("%.*s.lib", PRINT_ARG(s))); } args.add(to_string("/nologo")); args.add(to_string("/DEBUG")); String exec_name = compiler->build_options.executable_name; String obj_name = mprintf("%.*s.o", PRINT_ARG(exec_name)); convert_to_back_slashes(obj_name); args.add(obj_name); for (auto obj: compiler->user_supplied_objs) { auto temp = copy_string(obj); // @Leak convert_to_back_slashes(temp); args.add(obj); } String output_name = exec_name; char executable_name[LINE_SIZE]; snprintf(executable_name, LINE_SIZE, "/OUT:%.*s.exe", PRINT_ARG(output_name)); convert_to_back_slashes(executable_name + 1); args.add(to_string(executable_name)); // args.add(to_string("/Fe:")); // args.add(compiler->executable_name); auto cmd_line = get_command_line(&args); if (compiler->build_options.verbose_diagnostics) printf("Linker line: %s\n", cmd_line); // system((char *)cmd_line); STARTUPINFOA startup; memset(&startup, 0, sizeof(STARTUPINFOA)); startup.cb = sizeof(STARTUPINFOA); startup.dwFlags = STARTF_USESTDHANDLES; startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); startup.hStdError = GetStdHandle(STD_ERROR_HANDLE); PROCESS_INFORMATION process_info; CreateProcessA(nullptr, (char *) cmd_line, nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &process_info); WaitForSingleObject(process_info.hProcess, INFINITE); free(cmd_line); free(obj_name.data); } #else // @Incomplete should use the execpve family Array<String> args; args.add(to_string("ld")); String exec_name = compiler->build_options.executable_name; String obj_name = mprintf("%.*s.o", exec_name.length, exec_name.data); args.add(obj_name); for (auto obj: compiler->user_supplied_objs) { args.add(obj); } auto triple = compiler->llvm_gen->TargetMachine->getTargetTriple(); if (triple.isOSLinux()) { // CRT files // these seem to be GCC specific // auto crtbegin = compiler->find_file_in_library_search_paths(to_string("crtbegin.o")); // @Leak // auto crtend = compiler->find_file_in_library_search_paths(to_string("crtend.o")); // @Leak auto crti = compiler->find_file_in_library_search_paths(to_string("crti.o")); // @Leak auto crtn = compiler->find_file_in_library_search_paths(to_string("crtn.o")); // @Leak auto crt1 = compiler->find_file_in_library_search_paths(to_string("crt1.o")); // @Leak if (compiler->build_options.verbose_diagnostics) { // if (!crtbegin.item1) printf("Could not find crtbegin.\n"); // if (!crtend.item1) printf("Could not find crtend.\n"); if (!crti.item1) printf("Could not find crti.o.\n"); if (!crtn.item1) printf("Could not find crtn.o.\n"); if (!crt1.item1) printf("Could not find crt1.o.\n"); } // if (crtbegin.item1) args.add(crtbegin.item2); // if (crtend.item1) args.add(crtend.item2); if (crti.item1) args.add(crti.item2); if (crtn.item1) args.add(crtn.item2); if (crt1.item1) args.add(crt1.item2); args.add(to_string("--eh-frame-hdr")); // dynamic linker args.add(to_string("-dynamic-linker")); // @TODO clang also checks if the user supplied arguments to use hardfloats. Maybe we can query that through TargetMachine.. auto arch = triple.getArch(); // @TODO aarch64 and others. // @TODO MUSL using namespace llvm; if (triple.isARM() || triple.isThumb()) { bool hardfloats = (triple.getEnvironment() == Triple::GNUEABIHF); String linker_name = to_string("/lib/ld-linux.so.3"); if (hardfloats) linker_name = to_string("/lib/ld-linux-armhf.so.3"); args.add(linker_name); } else if (arch == Triple::x86_64) { // @TODO this probably isnt correct if you're compiling 32-bit programs on 64-bit OS. String linker_string = to_string("/lib64/ld-linux-x86-64.so.2"); args.add(linker_string); } else { if (compiler->build_options.verbose_diagnostics) { printf("Could not determine the dynamic linker needed for this platform.\n"); } } } args.add(to_string("-o")); args.add(compiler->build_options.executable_name); for (auto path: compiler->library_search_paths) { args.add(to_string("-L")); args.add(path); } for (auto lib: compiler->libraries) { if (lib->is_framework) { args.add(to_string("-framework")); args.add(lib->libname); } else { String s = lib->libname; args.add(mprintf("-l%.*s", s.length, s.data)); // @Leak } } auto cmd_line = get_command_line(&args); if (compiler->build_options.verbose_diagnostics) printf("Linker line: %s\n", cmd_line); system((char *)cmd_line); free(cmd_line); free(obj_name.data); if (triple.isOSDarwin()) { args.reset(); args.add(to_string("dsymutil")); args.add(exec_name); auto cmd_line = get_command_line(&args); if (compiler->build_options.verbose_diagnostics) printf("dsymutil line: %s\n", cmd_line); system((char *)cmd_line); free(cmd_line); } #endif // @TODO make sure we successfully launch the link command and that it returns a success code return true; } EXPORT bool compiler_load_file(Compiler *compiler, String filename) { perform_load(compiler, nullptr, filename, compiler->global_scope); return compiler->errors_reported == 0; } EXPORT bool compiler_load_string(Compiler *compiler, String source) { perform_load_from_string(compiler, source, compiler->global_scope); return compiler->errors_reported == 0; } EXPORT bool compiler_typecheck_program(Compiler *compiler) { compiler->resolve_directives(); if (compiler->errors_reported) return false; assert(compiler->directive_queue.count == 0); compiler->sema->typecheck_scope(compiler->preload_scope); compiler->sema->typecheck_scope(compiler->global_scope); for (auto import: compiler->loaded_imports) { // assert(import->imported_scope->type_info); compiler->sema->typecheck_scope(import->imported_scope); } // set metaprogram status if main is marked @metaprogram if (!compiler->errors_reported && !compiler->build_options.only_want_obj_file) { auto expr = compiler->sema->find_declaration_for_atom_in_scope(compiler->global_scope, compiler->atom_main); if (!expr) { compiler->report_error((Token *)nullptr, "No function 'main' found in global scope. Aborting.\n"); return false; } if (expr->type != AST_FUNCTION) { compiler->report_error(expr, "Expected a function named 'main' in global scope, but got something else.\n"); return false; } Ast_Function *function = static_cast<Ast_Function *>(expr); if (function->is_marked_metaprogram) compiler->is_metaprogram = true; function->is_exported = true; // main() must be exported by default } return compiler->errors_reported == 0; } EXPORT bool compiler_generate_llvm_module(Compiler *compiler) { compiler->llvm_gen->init(); for (auto decl: compiler->global_decl_emission_queue) { assert(!decl->is_let); assert(compiler->is_toplevel_scope(decl->identifier->enclosing_scope)); compiler->llvm_gen->emit_global_variable(decl); } for (auto &function : compiler->function_emission_queue) { compiler->llvm_gen->emit_function(function); } return compiler->errors_reported == 0; } EXPORT bool compiler_emit_object_file(Compiler *compiler) { compiler->llvm_gen->finalize(); return compiler->errors_reported == 0; } EXPORT bool compiler_jit_program(Compiler *compiler) { compiler->jitter->init(); return compiler->errors_reported == 0; } EXPORT void *compiler_jit_lookup_symbol(Compiler *compiler, String symbol_name) { return compiler->jitter->lookup_symbol(symbol_name); } EXPORT void compiler_add_library_search_path(Compiler *compiler, String path) { compiler->library_search_paths.add(copy_string(path)); // @Leak @Deduplicate } EXPORT void compiler_add_module_search_path(Compiler *compiler, String path) { compiler->module_search_paths.add(copy_string(path)); // @Leak @Deduplicate } EXPORT void compiler_add_compiled_object_for_linking(Compiler *compiler, String path) { compiler->user_supplied_objs.add(copy_string(path)); } }
[ "joshuahuelsman@gmail.com" ]
joshuahuelsman@gmail.com
d34bebdf5c719f3c42435471abca4c770d9af1b0
4cb7c6b30bac9a7b3265203ae8ed8f0de2f2cbd2
/Source/GameServer/SceneManager.cpp
c4fc5bdb53d97b311070cb3ce02c60da241e1f5c
[]
no_license
Peakchen/HMX-Server
3c2ee091f148cf1f329260daf027e1e8d9650111
310bb39d6fcb5abbbb44fc5337458abdf1bea7da
refs/heads/master
2021-01-09T06:24:05.568717
2017-01-17T13:24:43
2017-01-17T13:24:43
null
0
0
null
null
null
null
GB18030
C++
false
false
23,274
cpp
#include "GameServer_PCH.h" /** * \brief SceneManager的实现 * * 这个类暂时没有用到 */ #include "ScenesServer.h" std::map<WORD, stRangMap*> RangMapData; std::vector<DWORD> BmapBaseID; //using namespace Cmd::Session; using namespace Zebra; ///SceneManager的唯一实例 SceneManager *SceneManager::sm(new SceneManager()); /** * \brief 生成一个唯一ID * * \param tempid 输出:取得的ID * \return 是否成功 */ bool SceneManager::getUniqeID(QWORD &tempid) { tempid=sceneUniqeID->get(); return (tempid!=sceneUniqeID->invalid()); } /** * \brief 释放唯一ID * * \param tempid 要释放的ID */ void SceneManager::putUniqeID(const QWORD &tempid) { sceneUniqeID->put(tempid); } /** * \brief 生成一个队伍唯一ID * * \param tempid 输出:取得的ID * \return 是否成功 */ bool SceneManager::getTeamID(DWORD &tempid) { tempid=sceneTeamID->get(); return (tempid!=sceneTeamID->invalid()); } /** * \brief 释放队伍唯一ID * * \param tempid 要释放的ID */ void SceneManager::putTeamID(const DWORD &tempid) { sceneTeamID->put(tempid); } /** * \brief 构造函数 * */ SceneManager::SceneManager() { inited=false; newzone=false; //ScenTeamMap.clear(); } /** * \brief 析构函数 * */ SceneManager::~SceneManager() { //if(!ScenTeamMap.empty()) //{ // std::map<DWORD, TeamManager*>::iterator iter; // for(iter=ScenTeamMap.begin(); iter!=ScenTeamMap.end(); iter++) // { // delete iter->second; // } // ScenTeamMap.clear(); //} final(); } /** * \brief 得到SceneManager的指针 * 如果指针为0则进行初始化 * */ SceneManager & SceneManager::getInstance() { if (sm==NULL) sm=new SceneManager(); return *sm; } /** * \brief 删除SceneManager * */ void SceneManager::delInstance() { if (sm!=NULL) { sm->final(); SAFE_DELETE(sm); } } /** * \brief 释放所有已经加载的地图 * */ void SceneManager::final() { if (inited) { inited=false; unloadAllScene(); } } /** * \brief 初始化 * 加载所有地图 * */ bool SceneManager::init() { if (inited) return inited; //为每个场景服务器生成不相交叉的场景临时ID分配器,最小的从10000开始,每个有49998个ID可用 DWORD firstTempID = 10000+(NetService::getMe().getServerID()%100)*50000; sceneUniqeID = new zUniqueDWORDID(firstTempID,firstTempID+49998); ////sky 生成不相交的场景队伍临时ID分配器最小从10000开始,每个有4998个ID可用 //firstTempID = 500000+(ScenesService::getInstance().getServerID()%100)*5000; //sceneTeamID=new zUniqueDWORDID(firstTempID,firstTempID+4998); //// 初始化所有地图 zXMLParser parser; if (parser.initFile(Zebra::global["confdir"] + "scenesinfo.xml")) { xmlNodePtr root = parser.getRootNode("ScenesInfo"); xmlNodePtr countryNode = parser.getChildNode(root, "countryinfo"); if (countryNode) { xmlNodePtr subnode = parser.getChildNode(countryNode,"country"); while(subnode) { if (strcmp((char*)subnode->name,"country") == 0) { CountryInfo info; bzero(&info,sizeof(info)); parser.getNodePropNum(subnode,"id",&info.id,sizeof(info.id)); parser.getNodePropStr(subnode,"name",info.name,sizeof(info.name)); parser.getNodePropNum(subnode,"mapID",&info.mapid,sizeof(info.mapid)); parser.getNodePropNum(subnode,"function",&info.function,sizeof(info.function)); Zebra::logger->info("加载国家名称(%u,%s,%u,%u)",info.id,info.name,info.mapid,info.function); country_info.insert(CountryMap_value_type(info.id,info)); } subnode = parser.getNextNode(subnode,NULL); } } xmlNodePtr mapNode=parser.getChildNode(root,"mapinfo"); if (mapNode) { xmlNodePtr subnode = parser.getChildNode(mapNode,"map"); while(subnode) { if (strcmp((char*)subnode->name,"map") == 0) { MapInfo info; bzero(&info,sizeof(info)); parser.getNodePropNum(subnode,"mapID",&info.id,sizeof(info.id)); parser.getNodePropStr(subnode,"name",info.name,sizeof(info.name)); parser.getNodePropStr(subnode,"fileName",info.filename,sizeof(info.filename)); parser.getNodePropNum(subnode,"backto",&info.backto,sizeof(info.backto)); parser.getNodePropNum(subnode,"backtocity",&info.backtoCity,sizeof(info.backtoCity)); parser.getNodePropNum(subnode,"foreignerbackto",&info.foreignbackto,sizeof(info.foreignbackto)); parser.getNodePropNum(subnode,"countrydarebackto",&info.countrydarebackto, sizeof(info.countrydarebackto)); parser.getNodePropNum(subnode,"countrydefbackto",&info.countrydefbackto, sizeof(info.countrydefbackto)); parser.getNodePropNum(subnode,"pklevel",&info.pklevel, sizeof(info.pklevel)); parser.getNodePropNum(subnode,"commoncountrybackto",&info.commoncountrybackto,sizeof(info.commoncountrybackto)); parser.getNodePropNum(subnode,"commonuserbackto",&info.commonuserbackto,sizeof(info.commonuserbackto)); parser.getNodePropNum(subnode,"backtodare",&info.backtodare,sizeof(info.backtodare)); parser.getNodePropNum(subnode,"function",&info.function,sizeof(info.function)); parser.getNodePropNum(subnode,"level",&info.level,sizeof(info.level)); parser.getNodePropNum(subnode,"exprate",&info.exprate,sizeof(info.exprate)); map_info.insert(MapMap_value_type(info.id,info)); } subnode = parser.getNextNode(subnode,NULL); } } xmlNodePtr serverNode=parser.getChildNode(root,"server"); while (serverNode) { int id = 0; parser.getNodePropNum(serverNode,"id",&id,sizeof(id)); if (NetService::getMe().getServerID() == id) { int mapCount=0; xmlNodePtr countryNode=parser.getChildNode(serverNode,"country"); while(countryNode) { DWORD countryid=0; parser.getNodePropNum(countryNode,"id",&countryid,sizeof(countryid)); xmlNodePtr mapNode=parser.getChildNode(countryNode,"map"); while(mapNode) { //加载地图 DWORD mapid = 0; if (!parser.getNodePropNum(mapNode,"mapID", &mapid,sizeof(mapid))) { Zebra::logger->error("得到地图编号失败"); return inited; } Scene *newScene = loadScene(Scene::STATIC, countryid, mapid); // 注册地图 if (newScene) { printf("向session发送注册消息(%s-%d-%d)\n",newScene->name,newScene->id,newScene->tempid); Zebra::logger->info("加载%s(%d,%d)成功",newScene->name,newScene->id,newScene->tempid); S2WRegisterScene regscene; regscene.sceneid = newScene->id; //Zebra::logger->info("[地图真实ID]:%d",loaded->id&0x0FFF); regscene.sceneTempID=newScene->tempid; regscene.mapid = mapid; strncpy(regscene.name,newScene->name,MAX_NAMESIZE); strncpy(regscene.fileName,newScene->getFileName(),MAX_NAMESIZE); regscene.dwCountryID = countryid; regscene.byLevel = newScene->getLevel(); NetService::getMe().getSessionMgr().sendToWs(&regscene, regscene.GetPackLength()); mapCount++; } else { return inited; } mapNode=parser.getNextNode(mapNode,"map"); } countryNode=parser.getNextNode(countryNode,"country"); } Zebra::logger->info("ScenesServer id=%d加载%d张地图.",id,mapCount); } else{ Zebra::logger->info("skip id=%d != %d.",id, NetService::getMe().getServerID()); } serverNode=parser.getNextNode(serverNode,"server"); } inited=true; } else Zebra::logger->warn("SceneManager 解析配置文件失败."); //刷新玉如意需要的地图信息 freshEverySceneField(); return inited; } /** * \brief 根据名字的到场景指针的回调 * 方法是遍历所有scene并比较名字 * */ class GetSceneByFileName:public SceneCallBack { public: ///找到的scene指针 Scene *ret; ///要找的场景名字 const char *name; /** * \brief 构造函数 * * * \param name 要查找的场景名字 * \return */ GetSceneByFileName(const char *name) : ret(NULL),name(name) {}; /** * \brief 执行查找的方法 * * * \param scene 场景指针 * \return 是否继续查找 */ bool exec(Scene *scene) { if (strncmp(scene->getFileName(),name,MAX_NAMESIZE)==0) { ret=scene; return false; } else return true; } }; /** * \brief 根据文件名字找到场景指针 * * \param name 要找的场景名字 * \return 要找的场景指针,失败返回0 */ Scene * SceneManager::getSceneByFileName( const char * name) { GetSceneByFileName gsfn(name); execEveryScene(gsfn); return gsfn.ret; } /** * \brief 根据名字找到场景指针 * * \param name 要找的场景名字 * \return 要找的场景指针,失败返回0 */ Scene * SceneManager::getSceneByName( const char * name) { rwlock.rdlock(); Scene *ret =(Scene *)getEntryByName(name); rwlock.unlock(); return ret; } /** * \brief 根据领事ID找到场景指针 * * \param tempid 要找的场景的临时id * \return 要找的场景指针,失败返回0 */ Scene * SceneManager::getSceneByTempID( DWORD tempid) { rwlock.rdlock(); Scene * ret = (Scene *)getEntryByTempID(tempid); rwlock.unlock(); return ret; } /** * \brief 根据id找到场景指针 * * \param id 要找的场景id * \return 要找的场景指针,失败返回0 */ Scene * SceneManager::getSceneByID( DWORD id) { rwlock.rdlock(); Scene * ret = (Scene *)getEntryByID(id); rwlock.unlock(); return ret; } DWORD SceneManager::getMapId(DWORD countryid,DWORD mapid) { MapMap_iter map_iter = map_info.find(mapid); if (map_iter == map_info.end()) { return 0; } CountryMap_iter country_iter = country_info.find(countryid); if (country_iter == country_info.end()) { return 0; } return (country_iter->second.id << 16) + map_iter->second.id; } /** * \brief 加载一个地图 * * \param type 地图类型,静态/动态 * \param countryid 国家id * \param mapid 地图id * \return 新加载的场景指针 */ Scene * SceneManager::loadScene(int type/*Scene::SceneType type*/,DWORD countryid,DWORD mapid) { Zebra::logger->info("SceneManager::loadScene type=%d,countryid=%d,mapid=%d",type,countryid,mapid); zEntry *s=NULL; switch(type) { case 0://Scene::STATIC: s=new StaticScene(); break; //case 1://Scene::GANG: // s=new GangScene(); break; default: Zebra::logger->error("未知场景类型"); return false; } rwlock.wrlock(); bool ret=((Scene *)s)->init(countryid,mapid); if (ret) { ret=addEntry(s); if (!ret) Zebra::logger->error("SceneManager::loadScene addEntry[%s]失败.",s->name); else Zebra::logger->info("SceneManager::loadScene[%s]成功",s->name); } else Zebra::logger->error("SceneManager::loadScene init[%s]失败.",s->name); rwlock.unlock(); if (!ret) { SAFE_DELETE(s); } return (Scene *)s; } /** * \brief 动态加载一个地图 * * \param type 地图类型,静态/动态 * \param countryid 国家id * \param baseid 地图源id * \return 新加载的场景指针 */ Scene * SceneManager::loadBattleScene(DWORD baseid) { if(baseid == 0) return NULL; zEntry *s=NULL; //s=new GangScene(); //std::map<WORD, stRangMap*>::iterator iter; //iter = RangMapData.find(baseid); //if(iter == RangMapData.end()) // return NULL; //DWORD countryid = iter->second->GetCountryid(); //DWORD mapid = 0; //if(!iter->second->getUniqeID(mapid)) //{ // printf("%d 类型战场分配已到最大限制!无法再分配", baseid); // return NULL; //} //rwlock.wrlock(); //bool ret = ((GangScene*)s)->GangSceneInit(countryid, baseid, mapid); ////sky 配置战场基本数据 ////((GangScene*)s)->InitData(); //if (ret) //{ // ret=addEntry(s); // if (!ret) // Zebra::logger->error("SceneManager::loadScene addEntry[%s]失败.",s->name); // else // Zebra::logger->info("SceneManager::loadScene[%s]成功",s->name); //} //else // Zebra::logger->error("SceneManager::loadScene init[%s]失败.",s->name); //rwlock.unlock(); //if (!ret) //{ // SAFE_DELETE(s); //} return (Scene *)s; } /** * \brief 根据名字卸载一张地图 * * \param name 要卸载的地图名字 */ void SceneManager::unloadScene(std::string &name) { zEntry * ret=NULL; rwlock.wrlock(); if (zEntryName::find(name.c_str(),ret)) removeEntry(ret); SAFE_DELETE(ret); rwlock.unlock(); Zebra::logger->debug("SceneManager::unloadScene"); } /** * \brief 根据场景指针卸载一张地图 * * \param scene 要卸载的地图指针 */ void SceneManager::unloadScene(Scene * &scene) { if (scene==NULL) return; rwlock.wrlock(); removeEntry((zEntry *)scene); SAFE_DELETE(scene); rwlock.unlock(); Zebra::logger->debug("SceneManager::unloadScene"); } /** * \brief 卸载全部地图 * */ void SceneManager::unloadAllScene() { zEntry * ret=NULL; rwlock.wrlock(); while(zEntryName::findOne(ret)) { removeEntry(ret); SAFE_DELETE(ret); } rwlock.unlock(); Zebra::logger->debug("SceneManager::unloadAllScene"); } /** * \brief 检查并删除设置为remove的场景 * 方法是遍历所有场景,如果设置了remove标志,则清除所有npc和物件,然后删除场景 * 该方法在场景主循环中执行 * */ void SceneManager::checkUnloadOneScene() { for(zEntryTempID::hashmap::iterator it=zEntryTempID::ets.begin();it!=zEntryTempID::ets.end();it++) { Scene *scene = (Scene *)it->second; if (scene->getRunningState() == SCENE_RUNNINGSTATE_REMOVE) { Zebra::logger->debug("卸载场景%s",scene->name); SceneNpcManager::getMe().removeNpcInOneScene(scene); scene->removeSceneObjectInOneScene(); unloadScene(scene); return ; } } } struct EveryMapExec : public execEntry<SceneManager::MapInfo> { Scene *_scene; EveryMapExec(Scene *s):_scene(s) { } bool exec(SceneManager::MapInfo *info) { if (info->function & 0x2) { char buf[MAX_NAMESIZE + 1]; bzero(buf,sizeof(buf)); if (SceneManager::getInstance().buildMapName(_scene->getCountryID(),info->name,buf)) { _scene->addMainMapName(buf); } } if (info->function & 0x20) { char buf[MAX_NAMESIZE + 1]; bzero(buf,sizeof(buf)); if (SceneManager::getInstance().buildMapName(_scene->getCountryID(),info->name,buf)) { _scene->addIncMapName(buf); } } return true; } }; void SceneManager::freshEverySceneField() { struct getAllMapExec :public SceneCallBack { Scene *_old_scene; getAllMapExec(Scene *s):_old_scene(s) { } bool exec(Scene *scene) { //Zebra::logger->debug("%d,%d,%d,%s",scene->getCountryID(),_old_scene->getCountryID(),scene->isMainCity(),scene->getFileName()); //if (/*scene != _old_scene && */_old_scene->isMainCity() && scene->getCountryID() == _old_scene->getCountryID() && scene->isField() && _old_scene->getWayPoint(scene->getFileName())) //{ // _old_scene->addFieldMapName(scene->name); //} return true; } }; struct EverySceneExec :public SceneCallBack { bool exec(Scene *scene) { scene->clearMainMapName(); EveryMapExec exec1(scene); SceneManager::getInstance().execEveryMap(exec1); scene->clearFieldMapName(); getAllMapExec exec(scene); SceneManager::getInstance().execEveryScene(exec); return true; } }; EverySceneExec exec; SceneManager::getInstance().execEveryScene(exec); } /** * \brief 对每个场景执行回调函数 * * \param callback 要执行的回调函数 */ void SceneManager::execEveryScene(SceneCallBack &callback) { for(zEntryTempID::hashmap::iterator it=zEntryTempID::ets.begin();it!=zEntryTempID::ets.end();it++) { if (!callback.exec((Scene *)it->second)) { //mlock.unlock(); return; } } } /** * \brief 根据国家名字得到国家id * * \param name 要得到id的国家名字 * \return 找到的id,失败返回0 */ DWORD SceneManager::getCountryIDByCountryName(const char *name) { SceneManager::CountryMap_iter country_iter = SceneManager::getInstance().country_info.begin(); for(; country_iter != SceneManager::getInstance().country_info.end() ; country_iter ++) { if (strcmp(name,country_iter->second.name) == 0) { return country_iter->first; } } return 0; } /** * \brief 对每个国家配置执行回调函数 * * \param callback 要执行的回调函数 */ /* void SceneManager::execEveryMap(MapCallBack &callback) { SceneManager::MapMap_iter map_iter = SceneManager::getInstance().map_info.begin(); for(; map_iter != SceneManager::getInstance().map_info.end() ; map_iter ++) { callback.exec(map_iter->second); } } // */ /** * \brief 根据国家id得到国家名字 * * \param id 要找的国家id * \return 找到的国家名字,失败返回0 */ const char * SceneManager::getCountryNameByCountryID(DWORD id) { SceneManager::CountryMap_iter country_iter = SceneManager::getInstance().country_info.begin(); for(; country_iter != SceneManager::getInstance().country_info.end() ; country_iter ++) { if (country_iter->first == id) { return country_iter->second.name; } } return 0; } /** * \brief 根据地图名字得到地图id * * \param name 要找的地图名字 * \return 找到的id,失败返回0 */ DWORD SceneManager::getMapIDByMapName(const char *name) { const char *p = strstr(name,"·"); if (p) p += strlen("·"); else p = name; SceneManager::MapMap_iter map_iter = SceneManager::getInstance().map_info.begin(); for(; map_iter != SceneManager::getInstance().map_info.end() ; map_iter ++) { if (strcmp(p,map_iter->second.name) == 0) { return map_iter->first; } } return 0; } /** * \brief 根据国家id和地图id组成场景name * */ bool SceneManager::buildMapName(DWORD countryid,DWORD mapid,char *out) { const char *c = getCountryNameByCountryID(countryid); const char *m = map_info[mapid].name; if (c && m) { sprintf(out,"%s·%s",c,m); return true; } return false; } /** * \brief 根据国家id和地图name组成场景name * */ bool SceneManager::buildMapName(DWORD countryid,const char *in,char *out) { const char *c = getCountryNameByCountryID(countryid); if (c && in) { sprintf(out,"%s·%s",c,in); return true; } return false; } /** * \brief 根据国家id和地图id组成场景id * */ DWORD SceneManager::buildMapID(DWORD countryid,DWORD mapid) { return (countryid << 16) + mapid; } bool SceneManager::isNewZoneConfig() { return newzone && (!newzon_vec.empty()); } void SceneManager::setNewZoneConfig(bool type) { newzone=type; if (newzone==false) { newzon_vec.clear(); } } void SceneManager::addNewZonePos(DWORD x,DWORD y) { newzon_vec.push_back(std::make_pair(x,y)); } SceneManager::NewZoneVec &SceneManager::queryNewZonePos() { return newzon_vec; } bool SceneManager::randzPosNewZone(Scene *intoScene,zPos &findedPos) { bool founded=false; int i=0; while(!founded && i < (int)newzon_vec.size()) { int which = randBetween(0,newzon_vec.size() - 1); zPos initPos; int x = randBetween(0,10); int y = randBetween(0,10); initPos.x =newzon_vec[which].first + 5 - x; initPos.y =newzon_vec[which].second + 5 - y; founded = intoScene->findPosForUser(initPos,findedPos); } return founded; } //TeamManager* SceneManager::GetMapTeam(DWORD TeamID) //{ // if(ScenTeamMap.empty() || ScenTeamMap[TeamID] == 0) // return NULL; // else // return ScenTeamMap[TeamID]; //} //bool SceneManager::SceneNewTeam(SceneUser *pUser) //{ // if (pUser->TeamThisID == 0) // { // //sky 计算出队伍唯一ID // DWORD teamid; // if(!getTeamID(teamid)) // { // Channel::sendSys(pUser,Cmd::INFO_TYPE_GAME,"分配队伍唯一ID失败!队伍建立失败!"); // return false; // } // // TeamManager * team = new TeamManager(); // if(team == NULL) // { // Zebra::logger->debug("内存不足!组队失败"); // putTeamID(teamid); // return false; // } // // if (team->addMemberByTempID(pUser,pUser->tempid)) // { // team->setTeamtempId(teamid); // team->setLeader(pUser->tempid); // // ScenTeamMap[teamid] = team; // // pUser->TeamThisID = teamid; // // Cmd::stAddTeamMemberUserCmd ret; // ret.dwTeamID = teamid; // ret.dwHeadID = pUser->tempid; // ret.data.dwTempID = pUser->tempid; // ret.data.dwMaxHealth = pUser->charstate.maxhp; // ret.data.dwHealth = pUser->charbase.hp; // ret.data.dwMaxMp = pUser->charstate.maxmp; // ret.data.dwMp = pUser->charbase.mp; // ret.data.wdFace = pUser->charbase.face; // strncpy(ret.data.pstrName,pUser->name,MAX_NAMESIZE); // ret.data.byHead = true; // pUser->sendCmdToMe(&ret,sizeof(ret)); // // pUser->team_mode = Cmd::TEAM_HONOR; // pUser->reSendMyMapData(); // //session队伍 // ScenTeamMap[teamid]->addMemberToSession(pUser->name); // // return true; // } // } // // return false; //} // //bool SceneManager::SceneNewTeam(Cmd::Session::t_Team_Data* send) //{ // std::map<DWORD, TeamManager*>::iterator iter; // iter = ScenTeamMap.find(send->dwTeamThisID); // // if(iter != ScenTeamMap.end()) // return true; // // TeamManager * team = new TeamManager(); // if(team == NULL) // { // Zebra::logger->debug("内存不足!跨场景建立新队伍失败"); // return false; // } // // team->setTeamtempId(send->dwTeamThisID); // // SceneUser * leader = SceneUserManager::getMe().getUserByID(send->LeaderID); // // if(leader) // team->setLeader(leader->tempid); // else // team->setLeader( 0 ); // // for(int i=0; i<send->dwSize; i++) // { // bool bleaber; // if(send->Member->dwID == send->LeaderID) // bleaber = true; // else // bleaber = false; // // team->addWAwayMember(&(send->Member[i])); // } // // ScenTeamMap[send->dwTeamThisID] = team; // // return true; //} //sky 通知Session也删除队伍管理器的队伍 //bool SceneManager::SceneDelTeam(DWORD TeamID) //{ // std::map<DWORD, TeamManager*>::iterator iter; // iter = ScenTeamMap.find(TeamID); // // if(iter != ScenTeamMap.end()) // { // /*if(iter->second) // { // iter->second->deleteTeam(); // delete iter->second; // } // // ScenTeamMap.erase(iter); // // putTeamID(TeamID);*/ // // //sky 告诉Session删除队伍 // Cmd::Session::t_Team_DelTeam rev; // rev.TeamThisID = TeamID; // sessionClient->sendCmd(&rev, sizeof(Cmd::Session::t_Team_DelTeam)); // } // // return true; //} // ////sky 删除当前场景的队伍管理器里的队伍 //bool SceneManager::DelMapTeam(DWORD TeamID) //{ // std::map<DWORD, TeamManager*>::iterator iter; // iter = ScenTeamMap.find(TeamID); // // if(iter != ScenTeamMap.end()) // { // if(iter->second) // { // iter->second->deleteTeam(); // delete iter->second; // } // // ScenTeamMap.erase(iter); // // putTeamID(TeamID); // } // // return true; //} // //void SceneManager::TeamRollItme() //{ // std::map<DWORD, TeamManager*>::iterator iter; // for(iter=ScenTeamMap.begin(); iter!=ScenTeamMap.end(); iter++) // { // TeamManager * team = iter->second; // // if(team) // { // if(team->bRoll) // team->RollItem_A(); // } // } //}
[ "huangzuduan@qq.com" ]
huangzuduan@qq.com
51fbe02c0e29f381dbaa6fabfd901d084ff1aad5
bb5474b59b5fc0be8bcc3f02ac5b29b54f025c1e
/helloworld/helloworld.cpp
ad8ede833eea3b21bc562473848d64323b60bd92
[]
no_license
suzuren/gamelearning
15165185388b62c14b8e9e64019a8d6d891e5e84
317036868ad85177f8658bf71e8dbad7131e98cb
refs/heads/master
2021-05-10T11:02:29.467047
2021-01-29T09:15:32
2021-01-29T09:15:32
118,399,936
1
0
null
null
null
null
UTF-8
C++
false
false
102
cpp
#include <stdio.h> int main(int argc, const char** argv) { printf("hello world!\n"); return 0; }
[ "[2528751462@qq.com]" ]
[2528751462@qq.com]
cbad27bc828b87b034f9c28a3521c16f545664c4
4105c0cc18a9c8a2a8c5111967bd5f77ad435ce1
/381.谁拿了最多奖学金.cpp
3bb7e73317a6eb12ad7e09de8356064340f5a6ec
[]
no_license
Corsair-cxs/HZOJ
aadb9c1ae9fac59eaf917f279b69d52d8a0c35e4
46c5af0f369e6e0dd14ea1afbf93cd0f7e641c40
refs/heads/master
2023-03-04T03:02:14.396339
2021-02-18T06:45:16
2021-02-18T06:45:16
339,945,680
0
0
null
null
null
null
UTF-8
C++
false
false
2,907
cpp
/************************************************************************* > File Name: 381.谁拿了最多奖学金.cpp <<<<<<< HEAD > Author: ChenXiansen > Mail: 1494089474@qq.com > Created Time: Wed 21 Oct 2020 10:19:48 PM CST ************************************************************************/ #include <iostream> using namespace std; struct max_stu { string name; int num; }; int main() { max_stu Max_stu; Max_stu.num = -1; int n; string name; int score_avg, class_com, paper_cnt, money, sum_money = 0; char stu_carde, stu_west; cin >> n; while (n--) { money = 0; cin >> name >> score_avg >> class_com >> stu_carde >> stu_west >> paper_cnt; if (score_avg > 80 && paper_cnt > 0) { money += 8000; } if (score_avg > 85 && class_com > 80) { money += 4000; } if (score_avg > 90) { money += 2000; } if (score_avg > 85 && stu_west == 'Y') { money += 1000; } if (class_com > 80 && stu_carde == 'Y') { money += 850; } sum_money += money; if (money > Max_stu.num) { Max_stu.name = name; Max_stu.num = money; } //cout << n << ": " << money << " SUM: " << sum_money << endl; } cout << Max_stu.name << endl << Max_stu.num << endl << sum_money << endl; ======= > Author: ChenXiansen > Mail: 1494089474@qq.com > Created Time: Sun 20 Sep 2020 02:22:28 PM CST ************************************************************************/ #include<iostream> #include<string> #include<algorithm> using namespace std; struct STU { string name; int L_score; int C_score; int off; int west; int paper; int all; int num; }; int n, ans; STU stu[100]; int func(int x) { if (stu[x].L_score > 80 && stu[x].paper > 0) { stu[x].all += 8000; } if (stu[x].L_score > 85 && stu[x].C_score > 80) { stu[x].all += 4000; } if (stu[x].L_score > 90) { stu[x].all += 2000; } if (stu[x].L_score > 85 && stu[x].west) { stu[x].all += 1000; } if (stu[x].C_score > 80 && stu[x].off) { stu[x].all += 850; } return stu[x].all; } bool cmp(STU a, STU b) { if (a.all == b.all) { return a.num < b.num; } return a.all > b.all; } int main() { cin >> n; for (int i = 0; i < n; i++) { stu[i].num = i; cin >> stu[i].name >> stu[i].L_score >> stu[i].C_score; char t; cin >> t; stu[i].off = (t == 'Y') ? 1 : 0; cin >> t; stu[i].west = (t == 'Y') ? 1 : 0; cin >> stu[i].paper; ans += func(i); } sort(stu, stu + n, cmp); cout << stu[0].name << endl << stu[0].all << endl << ans << endl; >>>>>>> 2fb271d062ecc6f3e245a81259a3a701ac4656c7 return 0; }
[ "cxs@localhost.localdomain" ]
cxs@localhost.localdomain
1b01a02348eec29f7d531a4734ea83de597c70a1
3adb77a56a8aa998b5d29c152c7a3797bff8e7a1
/doc/snippets/GlmIntegration.cpp
189754cbc6eb472ecba54308fd25d116493ec73e
[ "MIT" ]
permissive
pilgarlicx/magnum-integration
30af5abef65c78da36450825ba2397d1775ee9fc
789f8132842536f077548bc4f2d2c3685e9f491e
refs/heads/master
2023-06-23T23:16:51.261902
2021-07-24T17:32:20
2021-07-24T17:37:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,995
cpp
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Magnum/Magnum.h" #include "Magnum/Math/Matrix3.h" #include "Magnum/GlmIntegration/Integration.h" #if GLM_VERSION < 96 #define GLM_FORCE_RADIANS /* Otherwise 0.9.5 spits a lot of loud messages :/ */ #endif #include "Magnum/GlmIntegration/GtcIntegration.h" #if GLM_VERSION >= 990 #define GLM_ENABLE_EXPERIMENTAL /* WTF, GLM! */ #endif #include "Magnum/GlmIntegration/GtxIntegration.h" using namespace Magnum; using namespace Magnum::Math::Literals; int main() { { /* The include is already above, so doing it again here should be harmless */ /* [namespace] */ #include <Magnum/GlmIntegration/Integration.h> glm::vec3 a{1.0f, 2.0f, 3.0f}; Vector3 b(a); auto c = Matrix4::rotation(35.0_degf, Vector3(a)); /* [namespace] */ static_cast<void>(c); } { /* [Integration] */ glm::vec3 a{1.0f, 2.0f, 3.0f}; Vector3 b(a); glm::mat3 c = glm::mat3(Matrix3::rotation(35.0_degf)); Debug{} << glm::lowp_ivec3{1, 42, -3}; // prints ivec3(1, 42, -3) /* [Integration] */ static_cast<void>(b); static_cast<void>(c); } #if GLM_VERSION >= 97 { /* [GtcIntegration] */ Quaterniond a = Quaterniond::rotation(35.0_deg, Vector3d::xAxis()); glm::dquat b(a); Debug{} << glm::mediump_quat{4.0f, 1.0f, 2.0f, 3.0f}; // prints quat(4.000000, {1.000000, 2.000000, 3.000000}) /* [GtcIntegration] */ static_cast<void>(b); } { /* [GtxIntegration] */ DualQuaternion a = DualQuaternion::translation({1.0f, 2.0f, 3.0f}); glm::dualquat b(a); Debug{} << glm::highp_ddualquat{{4.0, 1.0, 2.0, 3.0}, {8.0, 5.0, 6.0, 7.0}}; // prints ddualquat((4.000000, {1.000000, 2.000000, 3.000000}), // (8.000000, {5.000000, 6.000000, 7.000000})) /* [GtxIntegration] */ static_cast<void>(b); } #endif }
[ "mosra@centrum.cz" ]
mosra@centrum.cz
c1bb381ee21996d8942a5cec474b173499ff4eec
e1c08aee9e5166436d731794f19d993be6333cbc
/Custom_Template/Game/BoxCollider.h
12c3fc67549178781589523488082f9695a82a9b
[]
no_license
Lijmer/Custom_Template
6aeb02190add46f0e446ce042d36c100a461ba62
97e9064b56e50106b6fe9048f99008a82fe30099
refs/heads/master
2020-06-02T04:16:53.226001
2014-04-22T22:07:49
2014-04-22T22:07:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
287
h
#ifndef INCLUDED_BOX_COLLIDER_H #define INCLUDED_BOX_COLLIDER_H #include "Collider.h" class BoxCollider : public Collider { public: BoxCollider(engine::Transform&, game::GameObject&); virtual ~BoxCollider(); private: float m_width, height; }; #endif//INCLUDED_BOX_COLLIDER_H
[ "130802@nhtv.nl" ]
130802@nhtv.nl
5a9087be3aa06ddf74cdd96d3a8d48c47e4c025d
7f8111145926d6aae3586c53e963eccc5d3a8e5b
/1036.cpp
b4d06a6d879b13a350baf427526445af319c56a3
[]
no_license
b2utyyomi/PAT-Advanced-Level-Code
3338a96e9c74ae682d65c27743b8d03ca9a79621
af9cb3c56690e7d19646dbed29692bacd5697eda
refs/heads/master
2020-03-26T21:27:21.049374
2018-09-05T15:30:48
2018-09-05T15:30:48
145,389,393
1
0
null
null
null
null
UTF-8
C++
false
false
1,169
cpp
/********************** author: yomi date: 18.3.27 ps: **********************/ #include <iostream> #include <string> #include <cmath> using namespace std; int main() { int n; cin >> n; int flag1 = 0, flag2 = 0; string name, sex, major, n1, n2, m1, m2, diff; int mark; int maxk = 0, mink=200; for(int i=0; i<n; i++){ cin >> name >> sex >> major >> mark; if(sex == "M" && mark < mink){ mink = mark; n1 = name; m1 = major; flag1 = 1; } else if(sex == "F" && mark > maxk){ maxk = mark; n2 = name; m2 = major; flag2 = 1; } } if(flag1 && flag2){ cout << n2 << ' ' << m2 << endl; cout << n1 << ' ' << m1 << endl; cout << abs(maxk-mink); } else if(flag1){ cout << "Absent" << endl; cout << n1 << ' ' << m1 << endl; cout << "NA"; } else if(flag2){ cout << n2 << ' ' << m2 << endl; cout << "Absent" << endl; cout << "NA"; } return 0; } /** 3 Joe M Math990112 89 Mike M CS991301 100 Mary F EE990830 95 */
[ "3264986610@qq.com" ]
3264986610@qq.com
2e116f4be0943c30182ea173d499022a6bcdc70f
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/StepVisual_HArray1OfInvisibleItem.hxx
b98e2b8c482a9b4649a669c4c757742cf592a6e8
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
2,938
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _StepVisual_HArray1OfInvisibleItem_HeaderFile #define _StepVisual_HArray1OfInvisibleItem_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_StepVisual_HArray1OfInvisibleItem_HeaderFile #include <Handle_StepVisual_HArray1OfInvisibleItem.hxx> #endif #ifndef _StepVisual_Array1OfInvisibleItem_HeaderFile #include <StepVisual_Array1OfInvisibleItem.hxx> #endif #ifndef _MMgt_TShared_HeaderFile #include <MMgt_TShared.hxx> #endif #ifndef _Standard_Integer_HeaderFile #include <Standard_Integer.hxx> #endif class Standard_RangeError; class Standard_DimensionMismatch; class Standard_OutOfRange; class Standard_OutOfMemory; class StepVisual_InvisibleItem; class StepVisual_Array1OfInvisibleItem; class StepVisual_HArray1OfInvisibleItem : public MMgt_TShared { public: StepVisual_HArray1OfInvisibleItem(const Standard_Integer Low,const Standard_Integer Up); StepVisual_HArray1OfInvisibleItem(const Standard_Integer Low,const Standard_Integer Up,const StepVisual_InvisibleItem& V); void Init(const StepVisual_InvisibleItem& V) ; Standard_Integer Length() const; Standard_Integer Lower() const; Standard_Integer Upper() const; void SetValue(const Standard_Integer Index,const StepVisual_InvisibleItem& Value) ; const StepVisual_InvisibleItem& Value(const Standard_Integer Index) const; StepVisual_InvisibleItem& ChangeValue(const Standard_Integer Index) ; const StepVisual_Array1OfInvisibleItem& Array1() const; StepVisual_Array1OfInvisibleItem& ChangeArray1() ; DEFINE_STANDARD_RTTI(StepVisual_HArray1OfInvisibleItem) protected: private: StepVisual_Array1OfInvisibleItem myArray; }; #define ItemHArray1 StepVisual_InvisibleItem #define ItemHArray1_hxx <StepVisual_InvisibleItem.hxx> #define TheArray1 StepVisual_Array1OfInvisibleItem #define TheArray1_hxx <StepVisual_Array1OfInvisibleItem.hxx> #define TCollection_HArray1 StepVisual_HArray1OfInvisibleItem #define TCollection_HArray1_hxx <StepVisual_HArray1OfInvisibleItem.hxx> #define Handle_TCollection_HArray1 Handle_StepVisual_HArray1OfInvisibleItem #define TCollection_HArray1_Type_() StepVisual_HArray1OfInvisibleItem_Type_() #include <TCollection_HArray1.lxx> #undef ItemHArray1 #undef ItemHArray1_hxx #undef TheArray1 #undef TheArray1_hxx #undef TCollection_HArray1 #undef TCollection_HArray1_hxx #undef Handle_TCollection_HArray1 #undef TCollection_HArray1_Type_ // other Inline functions and methods (like "C++: function call" methods) #endif
[ "litao1009@gmail.com" ]
litao1009@gmail.com
c7404922d21c3796b3bacc159b8e3480c3817ebb
6c57b1f26dabd8bb24a41471ced5e0d1ac30735b
/BB/src/Sensor/Net/ForecastSensor.cpp
2004e6892cdcadfdb6d3d1802e8bea9d74a2dfdb
[]
no_license
hadzim/bb
555bb50465fbd604c56c755cdee2cce796118322
a6f43a9780753242e5e9f2af804c5233af4a920e
refs/heads/master
2021-01-21T04:54:53.835407
2016-06-06T06:31:55
2016-06-06T06:31:55
17,916,029
0
0
null
null
null
null
UTF-8
C++
false
false
3,131
cpp
/* * ForecastSensor.cpp * * Created on: Feb 1, 2013 * Author: root */ #include "BB/Sensor/Net/ForecastSensor.h" #include <Poco/SAX/SAXParser.h> #include <Poco/SAX/InputSource.h> #include "Poco/Net/HTTPClientSession.h" #include "Poco/Net/HTTPRequest.h" #include "Poco/Net/HTTPResponse.h" #include <Poco/Net/HTTPCredentials.h> #include "Poco/StreamCopier.h" #include "Poco/NullStream.h" #include "Poco/Path.h" #include "Poco/URI.h" #include "Poco/Exception.h" #include <iostream> #include "ForecastParser.h" #include <Poco/Delegate.h> #include "ForecastParser.h" #include <sstream> #include "BB/Configuration.h" #include "TBS/Log.h" namespace BB { ForecastSensor::ForecastSensor(std::string name, std::string url_) : name(name), url(url_ + "forecast.xml") { std::cout << "create url: " << url << std::endl; } ForecastSensor::~ForecastSensor() { } std::string ForecastSensor::getName(){ return name; } void ForecastSensor::parse() { r.clear(); try { std::cout << "get url: " << url << std::endl; //http://www.yr.no/place/Czech_Republic/Central_Bohemia/%C4%8Cerven%C3%A9_Pe%C4%8Dky/forecast_hour_by_hour.xml Poco::URI uri(url); std::string path(uri.getPathAndQuery()); Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort()); Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_0); Poco::Net::HTTPResponse response; session.sendRequest(request); std::istream& rs = session.receiveResponse(response); std::cout << response.getStatus() << " " << response.getReason() << std::endl; if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK) { throw Poco::Exception("Cannot get remote data"); } //Poco::StreamCopier::copyStream(rs, std::cout); Poco::XML::InputSource src(rs); ForecastParser handler; handler.Forecast += Poco::delegate(this, &ForecastSensor::onData); Poco::XML::SAXParser parser; parser.setContentHandler(&handler); try { std::cout << "parse" << std::endl; parser.parse(&src); } catch (Poco::Exception& e) { std::cerr << e.displayText() << std::endl; } handler.Forecast -= Poco::delegate(this, &ForecastSensor::onData); } catch (Poco::Exception& exc) { std::cerr << exc.displayText() << std::endl; } } void ForecastSensor::onData(ForecastData & data){ std::stringstream str; str << "w:" << data.wind << ";"; str << "i:" << data.img << ";"; str << "p:" << data.precipitation << ";"; str << "t:" << data.temperature << ";"; str << "n:" << data.info << ";"; SensorData s( SensorData::ForecastTemperature, Configuration::getSensorName(SensorData::ForecastTemperature, name), name, SensorData::UnitTemperature, data.date, SensorData::Sensor_Ok, data.temperature, str.str() ); LINFO("Forecast") << "Read forecast: " << s << LE; r.push_back(s); } ForecastSensor::Requests ForecastSensor::getRequests(){ this->parse(); return r; } int ForecastSensor::getPeriodInMs(){ //each 4 hours return 1000*60*60*4;//1000*60*60*2; //60*4; } } /* namespace BB */
[ "jan.vana@tbs-biometrics.com" ]
jan.vana@tbs-biometrics.com
e5a06d2399521fa862ca9235d54eb38340853280
8ed345320d1454e53ef5c35aadde92183a64dc02
/VisualXabsl/src/XabslEngine/WorldState.h
292b2ea3ccca84304751f79e0e00664c73b14114
[]
no_license
mrtndwrd/crax
d551dfbc17f9fa83f281216e7ee3d2b3fdac7b66
eb6cb18ec57fbdf1b54a4452684c11077f7bb1da
refs/heads/master
2021-01-01T17:33:12.337636
2012-06-27T22:06:16
2012-06-27T22:06:16
38,489,318
0
0
null
null
null
null
ISO-8859-2
C++
false
false
1,130
h
/* WorldState based on Martin Lötzsch' ASCII-soccer example */ #ifndef __WorldState_h_ #define __WorldState_h_ //#include "../Xabsl/XabslEngine/XabslSymbols.h" #include "Tools/xabsl/Xabsl/XabslEngine/XabslEngine.h" class WorldState { public: WorldState(); // the player indexing works like a ring buffer. // E.g. x[0] is for the acticve player, x[1] for the previously actice player etc. /* x, y The robot's location. */ double x; double y; /* updates the world state for a single player */ void update(double x, double y); // TODO: I don't think I'll need this: //void reset(); // resets the positions static WorldState* theInstance; // TODO: Don't think this is needed either: /* the dynamically assigned player role */ //enum PlayerRole { defender, midfielder, striker } playerRole[4]; static double getX(); // a function for the symbol "x" static double getY(); // a function for the symbol "y" void printWorld(xabsl::ErrorHandler& errorHandler); // prints the field containing debug informations }; #endif //__WorldState_h_
[ "Waard@localhost" ]
Waard@localhost
22e8c11895f7498956855b6210ae8ab6e39daed8
d7d23af0aec244a31d9179697473fc44eef9e5a9
/Configure.cpp
9ddf8032d13bb69b5af04a0e7023421c90f9bb71
[]
no_license
zhuzhenping/CTPConverter
4e9855038bf507eef6e33531c8302a7d8e9b8384
8aeeb740f442279c83c6d3e5608884b0b6118684
refs/heads/master
2020-12-24T07:03:57.437681
2015-11-02T03:18:20
2015-11-02T03:18:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,175
cpp
#include <Configure.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> //#include <comhelper.h> #include <iostream> /// 构造函数 Configure::Configure() { } /// 从环境变量中读取配置信息 void Configure::loadFromEnvironment() { /// 服务器地址 this->frontAddress = getenv("CTP_FRONT_ADDRESS"); assert(this->frontAddress); ///经纪公司代码 this->brokerID = getenv("CTP_BROKER_ID"); assert(this->brokerID); ///用户代码 this->userID = getenv("CTP_USER_ID"); assert(this->userID); ///密码 this->password = getenv("CTP_PASSWORD"); assert(this->password); /// 请求通信管道 this->requestPipe = getenv("CTP_REQUEST_PIPE"); assert(this->requestPipe); /// 返回消息管道 this->responsePipe = getenv("CTP_RESPONSE_PIPE"); assert(this->responsePipe); /// 回调信息管道 this->pushbackPipe = getenv("CTP_PUSHBACK_PIPE"); assert(this->pushbackPipe); /// 广播信息管道 this->publishPipe = getenv("CTP_PUBLISH_PIPE"); assert(this->publishPipe); } /// 从命令行读取配置信息 void Configure::loadFromCommandLine(CommandOption commandOption){ /// 服务器地址 char * frontAddress = commandOption.get("--FrontAddress"); assert(frontAddress != NULL); this->frontAddress = frontAddress; ///经纪公司代码 char * brokerID = commandOption.get("--BrokerID"); assert(brokerID != NULL); this->brokerID = brokerID; ///用户代码 char * userID = commandOption.get("--UserID"); assert(userID != NULL); this->userID = userID; ///密码 char * password = commandOption.get("--Password"); assert(password != NULL); this->password = password; /// 请求通信管道 char * requestPipe = commandOption.get("--RequestPipe"); assert(requestPipe != NULL); this->requestPipe = requestPipe; /// 返回通信管道 char * responsePipe = commandOption.get("--ResponsePipe"); assert(responsePipe != NULL); this->responsePipe = responsePipe; /// 回调信息管道 char * pushbackPipe = commandOption.get("--PushbackPipe"); assert(pushbackPipe != NULL); this->pushbackPipe = pushbackPipe; /// 广播信息管道 char * publishPipe = commandOption.get("--PublishPipe"); assert(publishPipe != NULL); this->publishPipe = publishPipe; } /// 构造函数 MdConfigure::MdConfigure() { } void MdConfigure::loadInstrumentIDList(){ // 确保文件存在 assert(fileExists(this->instrumentIDConfigFile)); // 读取文件内容,并解析数据 Json::Reader jsonReader; Json::Value instrumentIDList; std::string fileContent = fileReadAll(this->instrumentIDConfigFile); assert(jsonReader.parse(fileContent,instrumentIDList)); // 确保不超出品种数组的长度 assert(instrumentIDList.size()>0); assert(instrumentIDList.size()<INSTRUMENT_ARRAY_SIZE); // 读取品种订阅列表转化位ctp md api要求的格式 for (unsigned int i = 0; i < instrumentIDList.size(); i++){ const char * instrumentID = instrumentIDList[i].asString().c_str(); instrumentIDArray[i] = (char *) malloc(strlen(instrumentID)+1); strcpy(instrumentIDArray[i],instrumentID); } instrumentCount = instrumentIDList.size(); } /// 从环境变量中读取配置信息 void MdConfigure::loadFromEnvironment(){ /// 服务器地址 this->frontAddress = getenv("CTP_MD_FRONT_ADDRESS"); assert(this->frontAddress); ///经纪公司代码 this->brokerID = getenv("CTP_BROKER_ID"); assert(this->brokerID); ///用户代码 this->userID = getenv("CTP_USER_ID"); assert(this->userID); ///密码 this->password = getenv("CTP_PASSWORD"); assert(this->password); /// 请求通信管道 this->requestPipe = getenv("CTP_REQUEST_PIPE"); assert(this->requestPipe); /// 请求通信管道 //this->responsePipe = getenv("CTP_RESPONSE_PIPE"); //assert(this->responsePipe); /// 回调信息管道 this->pushbackPipe = getenv("CTP_PUSHBACK_PIPE"); assert(this->pushbackPipe); /// 广播信息管道 this->publishPipe = getenv("CTP_PUBLISH_PIPE"); assert(this->publishPipe); // 读取品种列表配置文件 //this->instrumentIDConfigFile = getenv("CTP_INSTRUMENT_ID_CONFIG_FILE"); //assert(this->instrumentIDConfigFile != NULL); //assert(fileExists(this->instrumentIDConfigFile)); //loadInstrumentIDList(); } /// 从命令行读取配置信息 void MdConfigure::loadFromCommandLine(CommandOption commandOption){ /// 服务器地址 char * frontAddress = commandOption.get("--FrontAddress"); assert(frontAddress != NULL); this->frontAddress = frontAddress; ///经纪公司代码 char * brokerID = commandOption.get("--BrokerID"); assert(brokerID != NULL); this->brokerID = brokerID; ///用户代码 char * userID = commandOption.get("--UserID"); assert(userID != NULL); this->userID = userID; ///密码 char * password = commandOption.get("--Password"); assert(password != NULL); this->password = password; /// 请求通信管道 char * requestPipe = commandOption.get("--RequestPipe"); assert(requestPipe != NULL); this->requestPipe = requestPipe; // /// 请求通信管道 // char * responsePipe = commandOption.get("--ResponsePipe"); // assert(responsePipe != NULL); // this->responsePipe = responsePipe; /// 回调信息管道 char * pushbackPipe = commandOption.get("--PushbackPipe"); assert(pushbackPipe != NULL); this->pushbackPipe = pushbackPipe; /// 广播信息管道 char * publishPipe = commandOption.get("--PublishPipe"); assert(publishPipe != NULL); this->publishPipe = publishPipe; /// 品种列表配置文件 //char * instrumentIDConfigFile = commandOption.get("--InstrumentIDConfigFile"); //assert(instrumentIDConfigFile != NULL); //assert(fileExists(instrumentIDConfigFile)); //this->instrumentIDConfigFile = instrumentIDConfigFile; //loadInstrumentIDList(); }
[ "xmduhan@gmail.com" ]
xmduhan@gmail.com
2353baa4c3737196c17aef49817eb8da6950d55b
64e4fabf9b43b6b02b14b9df7e1751732b30ad38
/src/chromium/gen/gen_combined/gpu/ipc/common/gpu_feature_info.mojom.cc
239ba37f11ef637ea5cc79e5a6bda7be93b33910
[ "BSD-3-Clause" ]
permissive
ivan-kits/skia-opengl-emscripten
8a5ee0eab0214c84df3cd7eef37c8ba54acb045e
79573e1ee794061bdcfd88cacdb75243eff5f6f0
refs/heads/master
2023-02-03T16:39:20.556706
2020-12-25T14:00:49
2020-12-25T14:00:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,878
cc
// Copyright 2013 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. #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" #elif defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4056) #pragma warning(disable:4065) #pragma warning(disable:4756) #endif #include "gpu/ipc/common/gpu_feature_info.mojom.h" #include <math.h> #include <stdint.h> #include <utility> #include "base/location.h" #include "base/logging.h" #include "base/run_loop.h" #include "base/task/common/task_annotator.h" #include "mojo/public/cpp/bindings/lib/message_internal.h" #include "mojo/public/cpp/bindings/lib/serialization_util.h" #include "mojo/public/cpp/bindings/lib/unserialized_message_context.h" #include "mojo/public/cpp/bindings/lib/validate_params.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/interfaces/bindings/interface_control_messages.mojom.h" #include "gpu/ipc/common/gpu_feature_info.mojom-params-data.h" #include "gpu/ipc/common/gpu_feature_info.mojom-shared-message-ids.h" #include "gpu/ipc/common/gpu_feature_info.mojom-import-headers.h" #ifndef GPU_IPC_COMMON_GPU_FEATURE_INFO_MOJOM_JUMBO_H_ #define GPU_IPC_COMMON_GPU_FEATURE_INFO_MOJOM_JUMBO_H_ #include "gpu/ipc/common/gpu_feature_info_struct_traits.h" #endif namespace gpu { namespace mojom { WebglPreferences::WebglPreferences() : anti_aliasing_mode(), msaa_sample_count(), max_active_webgl_contexts(), max_active_webgl_contexts_on_worker() {} WebglPreferences::WebglPreferences( gpu::AntialiasingMode anti_aliasing_mode_in, uint32_t msaa_sample_count_in, uint32_t max_active_webgl_contexts_in, uint32_t max_active_webgl_contexts_on_worker_in) : anti_aliasing_mode(std::move(anti_aliasing_mode_in)), msaa_sample_count(std::move(msaa_sample_count_in)), max_active_webgl_contexts(std::move(max_active_webgl_contexts_in)), max_active_webgl_contexts_on_worker(std::move(max_active_webgl_contexts_on_worker_in)) {} WebglPreferences::~WebglPreferences() = default; bool WebglPreferences::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { return Data_::Validate(data, validation_context); } GpuFeatureInfo::GpuFeatureInfo() : status_values(), enabled_gpu_driver_bug_workarounds(), disabled_extensions(), disabled_webgl_extensions(), webgl_preferences(), applied_gpu_blacklist_entries(), applied_gpu_driver_bug_list_entries() {} GpuFeatureInfo::GpuFeatureInfo( const std::vector<gpu::GpuFeatureStatus>& status_values_in, const std::vector<int32_t>& enabled_gpu_driver_bug_workarounds_in, const std::string& disabled_extensions_in, const std::string& disabled_webgl_extensions_in, const gpu::WebglPreferences& webgl_preferences_in, const std::vector<uint32_t>& applied_gpu_blacklist_entries_in, const std::vector<uint32_t>& applied_gpu_driver_bug_list_entries_in) : status_values(std::move(status_values_in)), enabled_gpu_driver_bug_workarounds(std::move(enabled_gpu_driver_bug_workarounds_in)), disabled_extensions(std::move(disabled_extensions_in)), disabled_webgl_extensions(std::move(disabled_webgl_extensions_in)), webgl_preferences(std::move(webgl_preferences_in)), applied_gpu_blacklist_entries(std::move(applied_gpu_blacklist_entries_in)), applied_gpu_driver_bug_list_entries(std::move(applied_gpu_driver_bug_list_entries_in)) {} GpuFeatureInfo::~GpuFeatureInfo() = default; bool GpuFeatureInfo::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { return Data_::Validate(data, validation_context); } } // namespace mojom } // namespace gpu namespace mojo { // static bool StructTraits<::gpu::mojom::WebglPreferences::DataView, ::gpu::mojom::WebglPreferencesPtr>::Read( ::gpu::mojom::WebglPreferences::DataView input, ::gpu::mojom::WebglPreferencesPtr* output) { bool success = true; ::gpu::mojom::WebglPreferencesPtr result(::gpu::mojom::WebglPreferences::New()); if (!input.ReadAntiAliasingMode(&result->anti_aliasing_mode)) success = false; result->msaa_sample_count = input.msaa_sample_count(); result->max_active_webgl_contexts = input.max_active_webgl_contexts(); result->max_active_webgl_contexts_on_worker = input.max_active_webgl_contexts_on_worker(); *output = std::move(result); return success; } // static bool StructTraits<::gpu::mojom::GpuFeatureInfo::DataView, ::gpu::mojom::GpuFeatureInfoPtr>::Read( ::gpu::mojom::GpuFeatureInfo::DataView input, ::gpu::mojom::GpuFeatureInfoPtr* output) { bool success = true; ::gpu::mojom::GpuFeatureInfoPtr result(::gpu::mojom::GpuFeatureInfo::New()); if (!input.ReadStatusValues(&result->status_values)) success = false; if (!input.ReadEnabledGpuDriverBugWorkarounds(&result->enabled_gpu_driver_bug_workarounds)) success = false; if (!input.ReadDisabledExtensions(&result->disabled_extensions)) success = false; if (!input.ReadDisabledWebglExtensions(&result->disabled_webgl_extensions)) success = false; if (!input.ReadWebglPreferences(&result->webgl_preferences)) success = false; if (!input.ReadAppliedGpuBlacklistEntries(&result->applied_gpu_blacklist_entries)) success = false; if (!input.ReadAppliedGpuDriverBugListEntries(&result->applied_gpu_driver_bug_list_entries)) success = false; *output = std::move(result); return success; } } // namespace mojo #if defined(__clang__) #pragma clang diagnostic pop #elif defined(_MSC_VER) #pragma warning(pop) #endif
[ "trofimov_d_a@magnit.ru" ]
trofimov_d_a@magnit.ru
952283ec47db8f4fc2336aa15327957c0248ebd8
1bf8b46afad5402fe6fa74293b464e1ca5ee5fd7
/Demo/Shenmue3SDK/SDK/FP_Ground_Grass_classes.h
86f3e7213d9b474e808c87b0f81f45629707bbc4
[]
no_license
LemonHaze420/ShenmueIIISDK
a4857eebefc7e66dba9f667efa43301c5efcdb62
47a433b5e94f171bbf5256e3ff4471dcec2c7d7e
refs/heads/master
2021-06-30T17:33:06.034662
2021-01-19T20:33:33
2021-01-19T20:33:33
214,824,713
4
0
null
null
null
null
UTF-8
C++
false
false
638
h
#pragma once // Name: S3Demo, Version: 0.90.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass FP_Ground_Grass.FP_Ground_Grass_C // 0x0000 (0x0088 - 0x0088) class UFP_Ground_Grass_C : public UFootprintTypeBase_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass FP_Ground_Grass.FP_Ground_Grass_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "35783139+LemonHaze420@users.noreply.github.com" ]
35783139+LemonHaze420@users.noreply.github.com
389f9e47c1b9b7026eaba58c276bf7e9bd92bf0d
3da7e2b82e693d67c619ca9c5fd790103d19d947
/TSH/mexHamDisSMP.cpp
0703d25b7e5310c05217fbc302f10059d4cef7b5
[]
no_license
wmYOLANDA/LDPSH
a84a7b4785e48adb8b84a3ced2e461d74b092bc6
434975c0adec47437e52b3f7c58c78ca4de6a7d1
refs/heads/master
2021-09-04T21:46:11.129190
2018-01-22T13:03:40
2018-01-22T13:03:40
118,455,145
0
1
null
null
null
null
WINDOWS-1252
C++
false
false
3,145
cpp
#define DLL_EXPORT_SYM #include <mex.h> #include <math.h> #define IN_TrainData prhs[0] #define IN_TrainBData prhs[1] #define IN_PairsNum prhs[2] #define IN_Index prhs[3] #define IN_Flag prhs[4] #define OUT_HammingDistance plhs[0] #define OUT_EuclideanDistance plhs[1] #define PI 3.1415926 typedef unsigned char byte; void ComputeHammingDistance(byte* pBData, int* pIndex, double* hammingDis, int nNumData, int nBytes, int nPairsNum) { for (int i = 0; i < nPairsNum; i++) { hammingDis[i] = 0; for (int k = 0; k < nBytes; k++) { byte tmp = (pBData[pIndex[i * 2] * nBytes + k] ^ pBData[pIndex[i * 2 + 1] * nBytes + k]); while (tmp) { hammingDis[i]++; tmp &= tmp - 1; } } } } void ComputeEuclideanDistance(double* pData, int* pIndex, double* euclideanDis, int nNumData, int nDim, int nPairsNum) { for (int i = 0; i < nPairsNum; i++) { euclideanDis[i] = 0; for (int k = 0; k < nDim; k++) euclideanDis[i] += (pData[pIndex[i * 2] * nDim + k] - pData[pIndex[i * 2 + 1] * nDim + k]) * (pData[pIndex[i * 2] * nDim + k] - pData[pIndex[i * 2 + 1] * nDim + k]); euclideanDis[i] = sqrt(euclideanDis[i]); } } void ComputeNormalizedAngleDistance(double* pData, int* pIndex, double* euclideanDis, int nNumData, int nDim, int nPairsNum) { for (int i = 0; i < nPairsNum; i++) { double inProd = 0; double uNorm = 0; double vNorm = 0; for (int k = 0; k < nDim; k++) { inProd += pData[pIndex[i * 2] * nDim + k] * pData[pIndex[i * 2 + 1] * nDim + k]; uNorm += pData[pIndex[i * 2] * nDim + k] * pData[pIndex[i * 2] * nDim + k]; vNorm += pData[pIndex[i * 2 + 1] * nDim + k] * pData[pIndex[i * 2 + 1] * nDim + k]; } euclideanDis[i] = acos(inProd / sqrt(uNorm * vNorm)) / PI; } } void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { byte* pBData = (byte*)mxGetPr(IN_TrainBData); const int nNumData = (int)mxGetN(IN_TrainBData); const int nBytes = (int)mxGetM(IN_TrainBData); double* pData = (double*)mxGetPr(IN_TrainData); const int nDim = (int)mxGetM(IN_TrainData); const int nPairsNum = (int)mxGetScalar(IN_PairsNum); int* pIndex = (int*)mxGetPr(IN_Index); const int flag = (int)mxGetScalar(IN_Flag); printf("nNumData: %d,\tnBits: %d, \tnDim: %d\n", nNumData, nBytes, nDim); OUT_HammingDistance = mxCreateDoubleMatrix(nPairsNum, 1, mxREAL); double* hammingDis = (double*)mxGetPr(OUT_HammingDistance); OUT_EuclideanDistance = mxCreateDoubleMatrix(nPairsNum, 1, mxREAL); double* euclideanDis = (double*)mxGetPr(OUT_EuclideanDistance); // ¼ÆËãHamming¾àÀë ComputeHammingDistance(pBData, pIndex, hammingDis, nNumData, nBytes, nPairsNum); // ¼ÆËãEuclidean¾àÀë if (flag == 1) ComputeEuclideanDistance(pData, pIndex, euclideanDis, nNumData, nDim, nPairsNum); if (flag == 2) ComputeNormalizedAngleDistance(pData, pIndex, euclideanDis, nNumData, nDim, nPairsNum); return; }
[ "wmyolanda@outlook.com" ]
wmyolanda@outlook.com
219424604e1045051dc59162776dc4d9bd856a93
ee802ac37234e6111ed4427bad36676a112e252c
/beagle/src/worker.cxx
dc407c8d481524d6f517617b103004194df6b77d
[]
no_license
atfienberg/italian-testbeam-daq
b80ecada20c50de9f7cf7fbec3d5f716ca613e05
9a8c713c7b10e77327f1d5f0098d3c170b6cef6c
refs/heads/master
2021-01-18T11:10:33.080004
2016-07-02T01:43:32
2016-07-02T01:43:32
50,057,441
0
0
null
null
null
null
UTF-8
C++
false
false
853
cxx
#include <iostream> #include <string> #include <zmq.hpp> using namespace std; string do_work() { cout << "starting work" << endl; sleep(5); cout << "done with work" << endl; return "work done"; } int main(int argc, char const *argv[]) { zmq::context_t context(1); zmq::socket_t sock(context, ZMQ_REP); sock.connect("tcp://127.0.0.1:6670"); while (true) { cout << "waiting for work request" << endl; zmq::message_t recv_msg; sock.recv(&recv_msg); string msg_str((char *)recv_msg.data(), (char *)recv_msg.data() + recv_msg.size()); cout << "received work request : " << msg_str << endl; msg_str = do_work(); // reply zmq::message_t reply_msg(msg_str.begin(), msg_str.end()); sock.send(reply_msg); cout << "reply sent" << endl; cout << "-----" << endl; } return 0; }
[ "uw.muon.dropbox@gmail.com" ]
uw.muon.dropbox@gmail.com
b4cc0917006e33c1881f5dbac52eec036cd5378e
17aa3e0f6bf81271b1e36f53e10070ba834edb3c
/AIZU_ONLINE_JUDGE/c++/dynamic_array.cpp
97c230807740126d324820651f246ef39d1a18ce
[]
no_license
9ryuuuuu/hobby
dd44590cf30dff341e62d293a48567e404fc5c5f
7aad7eb1546a7f6d71e6ba9229fd412fb53d3e4e
refs/heads/master
2020-04-27T23:36:51.168087
2019-04-02T08:27:29
2019-04-02T08:27:29
174,782,824
0
0
null
null
null
null
UTF-8
C++
false
false
1,406
cpp
#include <iostream> using namespace std; void arr_1(); void arr_2(); void arr_3(); int main() { // arr_1(); // arr_2(); arr_3(); } void arr_3() { int n = 3; int ***arr = new int **[n]; for (int i = 0; i < n; i++) { arr[i] = new int *[n]; for (int j = 0; j < n; j++) { arr[i][j] = new int[n]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { arr[i][j][k] = i * 100 + j * 10 + k; cout << arr[i][j][k] << endl; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { delete[] arr[i][j]; } delete[] arr[i]; } delete[] arr; } void arr_2() { int n = 3; int **arr = new int *[n]; for (int i = 0; i < n; i++) { arr[i] = new int[n]; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = i * 10 + j; cout << arr[i][j] << endl; } } for (int i = 0; i < n; i++) { delete[] arr[i]; } delete[] arr; } void arr_1() { int n = 10; int *arr; arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = i; cout << arr[i] << endl; } delete[] arr; }
[ "ruiakirab@gmail.com" ]
ruiakirab@gmail.com
2b95628ee8dc14c0f63df4fd8e7994cbfde881cf
2e222de5e03b948e5692f0011b6e38aa6067551b
/av/media/libvoicecall/libwebrtc_neteq/src/modules/audio_coding/neteq4/neteq.cc
f9a0583f8389b84169f3dee8c02a9e0b33b69d61
[]
no_license
cnping/Framework_V3
2df169e82aad2a898f4128f186ff88cc48249a4a
558bbd2175a46cb83c1a65af7146e8f5918f4bac
refs/heads/master
2021-01-12T20:48:36.792426
2015-11-13T01:22:52
2015-11-13T01:22:52
48,948,388
3
3
null
2016-01-03T14:23:08
2016-01-03T14:23:07
null
UTF-8
C++
false
false
2,881
cc
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_coding/neteq4/interface/neteq.h" #include "modules/audio_coding/neteq4/accelerate.h" #include "modules/audio_coding/neteq4/buffer_level_filter.h" #include "modules/audio_coding/neteq4/decoder_database.h" #include "modules/audio_coding/neteq4/delay_manager.h" #include "modules/audio_coding/neteq4/delay_peak_detector.h" #include "modules/audio_coding/neteq4/dtmf_buffer.h" #include "modules/audio_coding/neteq4/dtmf_tone_generator.h" #include "modules/audio_coding/neteq4/expand.h" #include "modules/audio_coding/neteq4/neteq_impl.h" #include "modules/audio_coding/neteq4/packet_buffer.h" #include "modules/audio_coding/neteq4/payload_splitter.h" #include "modules/audio_coding/neteq4/preemptive_expand.h" #include "modules/audio_coding/neteq4/timestamp_scaler.h" namespace webrtc { // Creates all classes needed and inject them into a new NetEqImpl object. // Return the new object. NetEq* NetEq::Create(int sample_rate_hz) { BufferLevelFilter* buffer_level_filter = new BufferLevelFilter; DecoderDatabase* decoder_database = new DecoderDatabase; DelayPeakDetector* delay_peak_detector = new DelayPeakDetector; DelayManager* delay_manager = new DelayManager(kMaxNumPacketsInBuffer, delay_peak_detector); DtmfBuffer* dtmf_buffer = new DtmfBuffer(sample_rate_hz); DtmfToneGenerator* dtmf_tone_generator = new DtmfToneGenerator; PacketBuffer* packet_buffer = new PacketBuffer(kMaxNumPacketsInBuffer, kMaxBytesInBuffer); PayloadSplitter* payload_splitter = new PayloadSplitter; TimestampScaler* timestamp_scaler = new TimestampScaler(*decoder_database); AccelerateFactory* accelerate_factory = new AccelerateFactory; ExpandFactory* expand_factory = new ExpandFactory; PreemptiveExpandFactory* preemptive_expand_factory = new PreemptiveExpandFactory; return new NetEqImpl(sample_rate_hz, buffer_level_filter, decoder_database, delay_manager, delay_peak_detector, dtmf_buffer, dtmf_tone_generator, packet_buffer, payload_splitter, timestamp_scaler, accelerate_factory, expand_factory, preemptive_expand_factory); } } // namespace webrtc
[ "978935078@qq.com" ]
978935078@qq.com
8726542691f9ee60f380b04ba753ad8279025da6
6a9a16900b2591d24af967f8de920c029727d6dc
/trunk/src/wzy/utilities/exception.cpp
29ed5238bb3a337916b361e2946353d16a400012
[]
no_license
hpohl/wheezy
37979bd4e2631cf960162772a18e845df2e9cf40
800a415b5ce7e438b4a871df9a7f985bd6d51ba1
refs/heads/master
2021-01-01T19:56:23.240293
2012-07-05T20:27:38
2012-07-05T20:27:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
113
cpp
#include <wzy/utilities/exception.hpp> namespace wzy { AbstractException::~AbstractException() noexcept { } }
[ "henning@still-hidden.de" ]
henning@still-hidden.de
a98752fd306c383cd4fa993c2a612ee8003f8ed6
81e61f91f06f2544b22fb890aa5fa49646d27da7
/Source/GeneticCommon/AutomatDecisionTreeStatic.hpp
1ea4b7e6b09a0dfc9ca4f7c9bc4b7dea055ebff7
[]
no_license
artem-bochkarev/master-work
ffa978570dfded90e4ef8eb0ac5c6016cb98d5de
057fd2b7248a1e513723cfce2743a5a495071bd9
refs/heads/master
2020-05-20T00:22:51.486014
2014-06-18T05:09:02
2014-06-18T05:09:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,788
hpp
#pragma once #include "AutomatDecisionTreeStatic.h" #include "Tools\binFunc.hpp" #include <boost\assert.hpp> #ifdef _DEBUG //#define DEBUG_TREE #endif template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::CAutomatDecisionTreeStatic() { memset(buffer, 0, sizeof(COUNTERS_TYPE)*(bufferSize)); buffer[0] = 666; buffer[1] = 666; buffer[2] = 666; buffer[3] = 666; } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::CAutomatDecisionTreeStatic(CAntCommon<COUNTERS_TYPE>* pAntCommon) :pAntCommon(pAntCommon) { memset(buffer, 0, sizeof(COUNTERS_TYPE)*(bufferSize)); buffer[0] = 666; buffer[1] = 666; buffer[2] = 666; buffer[3] = 666; } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::CAutomatDecisionTreeStatic(const CAutomatDecisionTreeStatic& automat) :pAntCommon(automat.pAntCommon) { memcpy(buffer, automat.buffer, bufferSize*sizeof(COUNTERS_TYPE)); } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::~CAutomatDecisionTreeStatic() { } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>& CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::operator = (const CAutomatDecisionTreeStatic& automat) { pAntCommon = automat.pAntCommon; memcpy(buffer, automat.buffer, bufferSize*sizeof(COUNTERS_TYPE)); return *this; } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> void CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::generateRandom(CRandom* rand) { for (size_t i = 0; i < STATES_COUNT; ++i) { std::set<size_t> was; nextFreePosition(i); addRandomNode(rand, i, 0, was, 1); #ifdef DEBUG_TREE const COUNTERS_TYPE* treePtr = buffer + commonDataSize + i*TREE_SIZE; size_t treeSize = getRealTreeSize(treePtr); std::set<size_t> oldWas; size_t oldDepth; for (size_t j = 0; j< treeSize; ++j) getDepthAndWas(treePtr, j, oldDepth, oldWas); #endif } buffer[0] = rand->nextUINT() % STATES_COUNT; } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> size_t CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::nextFreePosition(size_t stateNumber) { size_t result = 0; if (m_freePositions.find(stateNumber) != m_freePositions.end()) result = m_freePositions[stateNumber]; m_freePositions[stateNumber] = result + 1; return result; } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> void CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::addRandomNode (CRandom* rand, size_t stateNumber, size_t position, std::set<size_t>& was, size_t curDepth) { size_t a = rand->nextUINT() & 255; COUNTERS_TYPE* curPtr = buffer + commonDataSize + stateNumber*TREE_SIZE + NODE_SIZE * position; BOOST_ASSERT(curDepth <= MAX_DEPTH); if ( curDepth == MAX_DEPTH || (a > 200)) { //make a leaf *curPtr = 0; ++curPtr; *curPtr = pAntCommon->randomState(rand); ++curPtr; *curPtr = pAntCommon->randomAction(rand); } else { //make node std::set<size_t> free; for (size_t i = 1; i <= INPUT_PARAMS_COUNT; ++i) free.insert(i); for (size_t a : was) free.erase(a); size_t choosed = rand->nextUINT() % free.size(); size_t k = 0; size_t newVal = 0; for (size_t a : free) { if (k == choosed) { newVal = a; break; } ++k; } *curPtr = newVal; ++curPtr; was.insert(newVal); size_t left = nextFreePosition(stateNumber); *curPtr = left; ++curPtr; addRandomNode(rand, stateNumber, left, was, curDepth + 1); size_t right = nextFreePosition(stateNumber); *curPtr = right; ++curPtr; addRandomNode(rand, stateNumber, right, was, curDepth + 1); was.erase(newVal); } } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> COUNTERS_TYPE CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::getNextState(COUNTERS_TYPE currentState, const std::vector<INPUT_TYPE>& input) const { return getNextStateAction(currentState, input).first; } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> COUNTERS_TYPE CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::getAction(COUNTERS_TYPE currentState, const std::vector<INPUT_TYPE>& input) const { return getNextStateAction(currentState, input).second; } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> std::pair<COUNTERS_TYPE, COUNTERS_TYPE> CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::getNextStateAction(COUNTERS_TYPE currentState, const std::vector<INPUT_TYPE>& input) const { const COUNTERS_TYPE* treePtr = buffer + commonDataSize + currentState*TREE_SIZE; size_t position = 0; size_t depth = 0; while (depth < MAX_DEPTH) { const COUNTERS_TYPE* curPtr = treePtr + position*NODE_SIZE; if (*curPtr == 0) break; if (input[(*curPtr) - 1]) position = curPtr[1]; else position = curPtr[2]; ++depth; } BOOST_ASSERT(treePtr[position*NODE_SIZE] == 0); std::pair<COUNTERS_TYPE, COUNTERS_TYPE> res; res.first = treePtr[position*NODE_SIZE + 1]; res.second = treePtr[position*NODE_SIZE + 2]; return res; } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> COUNTERS_TYPE CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::getStartState() const { return buffer[0]; } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> void CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::getDepthAndWas(size_t curPos, size_t curDepth, std::set<size_t>& curWas, const COUNTERS_TYPE* treePtr, size_t newPosition, size_t& resultDepth, std::set<size_t>& resultWas) const { if (curPos == newPosition) { resultWas = curWas; resultDepth = curDepth; } else { BOOST_ASSERT(curPos >= 0); BOOST_ASSERT(curPos*NODE_SIZE <= TREE_SIZE); if (treePtr[curPos*NODE_SIZE] == 0) return; BOOST_ASSERT(curDepth < MAX_DEPTH); curWas.insert(curPos); getDepthAndWas(treePtr[curPos*NODE_SIZE + 1], curDepth + 1, curWas, treePtr, newPosition, resultDepth, resultWas); getDepthAndWas(treePtr[curPos*NODE_SIZE + 2], curDepth + 1, curWas, treePtr, newPosition, resultDepth, resultWas); curWas.erase(curPos); } } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> void CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::getDepthAndWas(const COUNTERS_TYPE* treePtr, size_t newPosition, size_t& depth, std::set<size_t>& was) const { std::set<size_t> tempWas; getDepthAndWas(0, 1, tempWas, treePtr, newPosition, depth, was); } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> size_t CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::getRealTreeSize(size_t curPos, const COUNTERS_TYPE* treePtr) const { BOOST_ASSERT(curPos*NODE_SIZE <= TREE_SIZE); if (treePtr[curPos*NODE_SIZE] == 0) return 1; return 1 + getRealTreeSize(treePtr[curPos*NODE_SIZE + 1], treePtr) + getRealTreeSize(treePtr[curPos*NODE_SIZE + 2], treePtr); } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> size_t CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::getRealTreeSize(const COUNTERS_TYPE* treePtr) const { return getRealTreeSize(0, treePtr); } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> size_t CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::recreateTree(size_t curPos, size_t stateNumber, const COUNTERS_TYPE* treePtr, size_t nodePosition, COUNTERS_TYPE* tempTree, size_t& newPosition ) { size_t newPos = nextFreePosition(stateNumber); tempTree[newPos*NODE_SIZE] = treePtr[curPos*NODE_SIZE]; if (curPos == nodePosition) { newPosition = newPos; if (treePtr[curPos*NODE_SIZE] > 0) { tempTree[newPos*NODE_SIZE] = 0; tempTree[newPos*NODE_SIZE + 1] = 0; tempTree[newPos*NODE_SIZE + 2] = 0; } } else if (treePtr[curPos*NODE_SIZE] > 0) { tempTree[newPos*NODE_SIZE + 1] = recreateTree(treePtr[curPos*NODE_SIZE + 1], stateNumber, treePtr, nodePosition, tempTree, newPosition); tempTree[newPos*NODE_SIZE + 2] = recreateTree(treePtr[curPos*NODE_SIZE + 2], stateNumber, treePtr, nodePosition, tempTree, newPosition); } return newPos; } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> size_t CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::recreateTree(size_t stateNumber, const COUNTERS_TYPE* treePtr, size_t nodePosition, COUNTERS_TYPE* tempTree) { m_freePositions[stateNumber] = 0; size_t newPos; recreateTree(0, stateNumber, treePtr, nodePosition, tempTree, newPos); return newPos; } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> void CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::mutate(CRandom* rand) { size_t stateNumber = rand->nextUINT() % STATES_COUNT; COUNTERS_TYPE* treePtr = buffer + commonDataSize + stateNumber*TREE_SIZE; size_t treeSize = getRealTreeSize( treePtr ); size_t nodePosition = rand->nextUINT() % treeSize; #ifdef DEBUG_TREE std::set<size_t> oldWas; size_t oldDepth; getDepthAndWas(treePtr, nodePosition, oldDepth, oldWas); #endif COUNTERS_TYPE tempTree[TREE_SIZE]; memset(tempTree, 0, TREE_SIZE * sizeof(COUNTERS_TYPE)); size_t newPosition = recreateTree(stateNumber, treePtr, nodePosition, tempTree); memcpy(treePtr, tempTree, TREE_SIZE * sizeof(COUNTERS_TYPE)); std::set<size_t> was; size_t depth; getDepthAndWas(treePtr, newPosition, depth, was); #ifdef DEBUG_TREE BOOST_ASSERT(oldDepth == depth); #endif addRandomNode(rand, stateNumber, newPosition, was, depth); } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> size_t CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::getHeight(const COUNTERS_TYPE* fatherTreePtr, size_t fatherNode) const { if (fatherTreePtr[fatherNode*NODE_SIZE] == 0) return 0; else return 1 + std::max(getHeight(fatherTreePtr, fatherTreePtr[fatherNode*NODE_SIZE + 1]), getHeight(fatherTreePtr, fatherTreePtr[fatherNode*NODE_SIZE + 2])); } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> void CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::addSubTree(size_t stateNumber, COUNTERS_TYPE* dstTreePtr, size_t node, const COUNTERS_TYPE* srcTreePtr, size_t srcNode, size_t depth) { BOOST_ASSERT(depth <= MAX_DEPTH); memcpy(dstTreePtr + NODE_SIZE*node, srcTreePtr + NODE_SIZE*srcNode, NODE_SIZE * sizeof(COUNTERS_TYPE)); if (srcTreePtr[srcNode * NODE_SIZE] > 0) { dstTreePtr[node*NODE_SIZE + 1] = nextFreePosition(stateNumber); dstTreePtr[node*NODE_SIZE + 2] = nextFreePosition(stateNumber); addSubTree(stateNumber, dstTreePtr, dstTreePtr[node*NODE_SIZE + 1], srcTreePtr, srcTreePtr[srcNode * NODE_SIZE + 1], depth + 1); addSubTree(stateNumber, dstTreePtr, dstTreePtr[node*NODE_SIZE + 2], srcTreePtr, srcTreePtr[srcNode * NODE_SIZE + 2], depth + 1); } } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> void CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::crossover(const CAutomat* mother, const CAutomat* father, CRandom* rand) { const CAutomatDecisionTreeStatic* motherPtr = static_cast<const CAutomatDecisionTreeStatic*>(mother); const CAutomatDecisionTreeStatic* fatherPtr = static_cast<const CAutomatDecisionTreeStatic*>(father); pAntCommon = motherPtr->pAntCommon; for (size_t stateNumber = 0; stateNumber < STATES_COUNT; ++stateNumber) { COUNTERS_TYPE* childTreePtr = buffer + commonDataSize + stateNumber*TREE_SIZE; const COUNTERS_TYPE* motherTreePtr = motherPtr->buffer + commonDataSize + stateNumber*TREE_SIZE; const COUNTERS_TYPE* fatherTreePtr = fatherPtr->buffer + commonDataSize + stateNumber*TREE_SIZE; size_t motherSize = getRealTreeSize(motherTreePtr), fatherSize = getRealTreeSize(fatherTreePtr); size_t motherNode = rand->nextUINT() % motherSize, fatherNode = rand->nextUINT() % fatherSize; std::set<size_t> was; size_t motherDepth, fatherHeight; getDepthAndWas(motherTreePtr, motherNode, motherDepth, was); fatherHeight = getHeight(fatherTreePtr, fatherNode); size_t counter = 0; while (motherDepth + fatherHeight > MAX_DEPTH) { fatherNode = rand->nextUINT() % fatherSize; fatherHeight = getHeight(fatherTreePtr, fatherNode); ++counter; if (counter % 100 == 0) BOOST_ASSERT(false); } m_freePositions[stateNumber] = 0; size_t childNode = recreateTree(stateNumber, motherTreePtr, motherNode, childTreePtr); #ifdef DEBUG_TREE const COUNTERS_TYPE* treePtr = buffer + commonDataSize + stateNumber*TREE_SIZE; size_t treeSize = getRealTreeSize(treePtr); std::set<size_t> oldWas; size_t oldDepth; for (size_t j = 0; j< treeSize; ++j) getDepthAndWas(childTreePtr, j, oldDepth, oldWas); #endif size_t savedPosition = m_freePositions[stateNumber]; m_freePositions[stateNumber] = savedPosition; addSubTree(stateNumber, childTreePtr, childNode, fatherTreePtr, fatherNode, motherDepth); #ifdef DEBUG_TREE getDepthAndWas(childTreePtr, childNode, oldDepth, oldWas); BOOST_ASSERT(oldDepth == motherDepth); #endif //checkTree(childTreePtr, 0); #ifdef DEBUG_TREE for (size_t j = 0; j< treeSize; ++j) getDepthAndWas(childTreePtr, j, oldDepth, oldWas); #endif } if ((rand->nextUINT() & 255) > 127) buffer[0] = motherPtr->buffer[0]; else buffer[0] = fatherPtr->buffer[0]; } template<typename COUNTERS_TYPE, typename INPUT_TYPE, size_t MAX_DEPTH, size_t INPUT_PARAMS_COUNT, size_t STATES_COUNT> size_t CAutomatDecisionTreeStatic<COUNTERS_TYPE, INPUT_TYPE, MAX_DEPTH, INPUT_PARAMS_COUNT, STATES_COUNT>::getBufferOffset() const { int* a = buffer; int* b = (int*)this; int c = a - b; return c; }
[ "artem.bochkarev@gmail.com" ]
artem.bochkarev@gmail.com
43c4843dd15b25466df5f6957376c367daae2c78
579482e8e0843ca832cbf2907d8c6e34ed6bd87d
/avsys2012/week5_audioRMSandZeroCrossingPitch/src/testApp.h
42224e7b1cc7cefe60a911609fad39e4cab894b2
[]
no_license
firmread/avsys2013
46fd5f2ed9c5053cc1f7aa5415b1feee59aa0f9e
1d079cc9a8164b7ac1fa4a8e3112f4c986c59214
refs/heads/master
2020-05-20T09:31:24.633510
2013-04-16T13:49:15
2013-04-16T13:49:15
8,830,629
1
0
null
null
null
null
UTF-8
C++
false
false
904
h
#pragma once #include "ofMain.h" class testApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed (int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); void audioIn(float * input, int bufferSize, int nChannels); ofSoundStream soundStream; float volume; // via RMS float pitch; // via zero crossings float volumeSmoothSlow; // via RMS float pitchSmoothSlow; // via zero crossings bool bSignOflastValue; // was the last sample + or - float sampleSmooth; };
[ "litchirhythm@gmail.com" ]
litchirhythm@gmail.com
59279bc9547ee3d1cffbdb1308bedbb46c911664
7efe08063fd383640455cc709ef04c889b8ebc42
/src/zmq/zmqutil.cpp
f07a4ae9fd3c5d7160b34f36155dd681f5272582
[ "MIT" ]
permissive
litecoin-project/litecoin
0d55434c63e41409f3c69b43199a9cb6bd256a83
5ac781487cc9589131437b23c69829f04002b97e
refs/heads/master
2023-09-05T21:38:55.634991
2023-04-24T04:08:34
2023-05-12T06:47:49
4,646,198
4,040
4,600
MIT
2023-07-29T19:58:50
2012-06-13T04:18:26
C++
UTF-8
C++
false
false
378
cpp
// Copyright (c) 2014-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <zmq/zmqutil.h> #include <logging.h> #include <zmq.h> void zmqError(const char* str) { LogPrint(BCLog::ZMQ, "zmq: Error: %s, errno=%s\n", str, zmq_strerror(errno)); }
[ "d@domob.eu" ]
d@domob.eu
3f5837e6dc998fd4b27036ce0f8727e0efc63849
25d2e23145f4a3302642b8b1f4b95b5f6cb32d6a
/Legacy/621/Final/AlajarDll/PageSource.cpp
c1bd277914e3bf68851123f27c6245cb621937cf
[]
no_license
mfeingol/almonaster
3b167043b29144e96d50e620f03d1015bc74c4a3
57caeda258bc4bce60e37f61e122b791767147e7
refs/heads/master
2023-01-11T07:57:28.278474
2023-01-03T23:45:48
2023-01-03T23:53:09
223,525,538
1
0
null
null
null
null
UTF-8
C++
false
false
42,168
cpp
// PageSource.cpp: implementation of the PageSource class. // ////////////////////////////////////////////////////////////////////// // // HttpObjects.dll: a component of Alajar 1.0 // Copyright (C) 1998 Max Attar Feingold (maf6@cornell.edu) // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "PageSource.h" #include "HttpRequest.h" #include "HttpResponse.h" #include "HttpServer.h" #include "Osal/Algorithm.h" #include <stdio.h> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// PageSource::AccessControlElement::AccessControlElement() { } int PageSource::AccessControlElement::Initialize (const char* pszName, bool bWildCard) { pszString = String::StrDup (pszName); if (pszString == NULL && !String::IsBlank (pszName)) { return ERROR_OUT_OF_MEMORY; } stLength = String::StrLen (pszName), bHasWildCard = bWildCard; return OK; } PageSource::AccessControlElement::~AccessControlElement() { if (pszString != NULL) { OS::HeapFree (pszString); } } PageSource::PageSource (HttpServer* pHttpServer) { m_pHttpServer = pHttpServer; m_pszName = NULL; m_pszLibraryName = NULL; m_pszConfigFileName = NULL; m_pPageSource = NULL; m_pcfConfig = NULL; m_bRestart = false; m_bScrewed = false; m_bShutdown = false; m_bIsDefault = false; m_iNumRefs = 1; // AddRef m_iNumThreads = 0; m_bFilterGets = false; m_atAuthType = AUTH_NONE; m_iDigestNonceLifetime = 0; Reset(); } int PageSource::Init() { int iErrCode; iErrCode = m_mLogMutex.Initialize(); if (iErrCode != OK) { return iErrCode; } iErrCode = m_mReportMutex.Initialize(); if (iErrCode != OK) { return iErrCode; } iErrCode = m_mShutdownLock.Initialize(); if (iErrCode != OK) { return iErrCode; } iErrCode = m_mLock.Initialize(); if (iErrCode != OK) { return iErrCode; } iErrCode = m_mCounterLock.Initialize(); if (iErrCode != OK) { return iErrCode; } m_pcfConfig = Config::CreateInstance(); if (m_pcfConfig == NULL) { return ERROR_OUT_OF_MEMORY; } return OK; } void PageSource::Reset() { m_bLocked = false; m_bBrowsingAllowed = false; m_bDefaultFile = false; m_bOverrideGet = false; m_bOverridePost = false; m_bIsDefault = false; m_atAuthType = AUTH_NONE; memset (m_pbOverrideError, 0, sizeof (m_pbOverrideError)); memset (m_ppCachedFile, 0, sizeof (m_ppCachedFile)); m_bUseSSI = false; m_bUsePageSourceLibrary = false; m_bUseLogging = false; m_bUseCommonLogFormat = false; m_pszDefaultFile = NULL; m_pPageSource = NULL; m_bFilterGets = false; Time::ZeroTime (&m_tLogTime); Time::ZeroTime (&m_tReportTime); } PageSource::~PageSource() { Clean(); if (m_pcfConfig != NULL) { m_pcfConfig->Release(); } if (m_pszLibraryName != NULL) { OS::HeapFree (m_pszLibraryName); } if (m_pszName != NULL) { delete [] m_pszName; } if (m_pszConfigFileName != NULL) { OS::HeapFree (m_pszConfigFileName); } } void PageSource::Clean() { if (m_pPageSource != NULL) { m_pPageSource->OnFinalize(); m_pPageSource->Release(); m_pPageSource = NULL; } for (unsigned int i = 0; i < NUM_STATUS_CODES; i ++) { if (m_ppCachedFile[i] != NULL) { m_ppCachedFile[i]->Release(); } } if (m_pszDefaultFile != NULL) { OS::HeapFree (m_pszDefaultFile); } m_cfCounterFile.Close(); // Clear security lists ClearACEList (&m_llAllowIPAddressList); ClearACEList (&m_llDenyIPAddressList); ClearACEList (&m_llAllowUserAgentList); ClearACEList (&m_llDenyUserAgentList); // Clear GET filters ClearACEList (&m_llDenyGetExts); ClearACEList (&m_llAllowReferer); // Close files m_fLogFile.Close(); m_fReportFile.Close(); } void PageSource::ClearACEList (ACEList* pllList) { ListIterator<AccessControlElement*> liIt; while (pllList->PopFirst (&liIt)) { delete liIt.GetData(); } pllList->Clear(); } // // IObject // unsigned int PageSource::AddRef() { return Algorithm::AtomicIncrement (&m_iNumRefs); } unsigned int PageSource::Release() { unsigned int iNumRefs = Algorithm::AtomicDecrement (&m_iNumRefs); if (iNumRefs == 0) { delete this; } return iNumRefs; } int PageSource::QueryInterface (const Uuid& iidInterface, void** ppInterface) { if (iidInterface == IID_IObject) { *ppInterface = (void*) static_cast<IObject*> (this); AddRef(); return OK; } if (iidInterface == IID_IPageSourceControl) { *ppInterface = (void*) static_cast<IPageSourceControl*> (this); AddRef(); return OK; } if (iidInterface == IID_IPageSource) { *ppInterface = (void*) static_cast<IPageSource*> (this); AddRef(); return OK; } if (iidInterface == IID_ILog) { *ppInterface = (void*) static_cast<ILog*> (this); AddRef(); return OK; } if (iidInterface == IID_IReport) { *ppInterface = (void*) static_cast<IReport*> (this); AddRef(); return OK; } *ppInterface = NULL; return ERROR_NO_INTERFACE; } /////////////// // Configure // /////////////// int PageSource::Restart() { m_mShutdownLock.Wait(); if (m_bShutdown || m_bRestart) { m_mShutdownLock.Signal(); return ERROR_FAILURE; } m_bRestart = true; // Start a new thread that restarts us Thread tRestart; int iErrCode = tRestart.Start (PageSource::RestartPageSource, this); m_mShutdownLock.Signal(); return iErrCode; } bool PageSource::IsRestarting() { return m_bRestart; } bool PageSource::IsWorking() { return !m_bScrewed; } // pszLibraryName -> full name of the dll // pszNameSpace -> Prefix of the functions in the dll // pszPageSourceName -> Name of the page source int PageSource::Initialize (const char* pszLibraryName, const char* pszClsid) { if (m_pszLibraryName == NULL && pszLibraryName != NULL) { m_pszLibraryName = String::StrDup (pszLibraryName); if (m_pszLibraryName == NULL) { return ERROR_OUT_OF_MEMORY; } } if (pszLibraryName == NULL || pszClsid == NULL) { return ERROR_FAILURE; } // Get the clsid Uuid uuidClsid; int iErrCode = OS::UuidFromString (pszClsid, &uuidClsid); if (iErrCode != OK) { return iErrCode; } // Load the library iErrCode = m_libPageSource.Open (pszLibraryName); if (iErrCode != OK) { return iErrCode; } // Get the export Fxn_CreateInstance pCreateInstance = (Fxn_CreateInstance) m_libPageSource.GetExport ("CreateInstance"); if (pCreateInstance == NULL) { m_libPageSource.Close(); return ERROR_FAILURE; } // Call CreateInstance iErrCode = pCreateInstance (uuidClsid, IID_IPageSource, (void**) &m_pPageSource); if (iErrCode != OK) { m_libPageSource.Close(); return iErrCode; } // Open report and log iErrCode = OpenReport(); if (iErrCode != OK) { m_libPageSource.Close(); return iErrCode; } iErrCode = OpenLog(); if (iErrCode != OK) { m_libPageSource.Close(); return iErrCode; } // Initialize underlying PageSource return OnInitialize (m_pHttpServer, this); } static const char* g_pszSeparator = ";"; int PageSource::SetAccess (ACEList* pllAccessList, const char* pszAccessList) { Assert (pszAccessList != NULL); char* pszCopy = (char*) StackAlloc (strlen (pszAccessList) + 1); strcpy (pszCopy, pszAccessList); char* pszTemp = strtok (pszCopy, g_pszSeparator); while (pszTemp != NULL) { int iErrCode; bool bWildCard = false; AccessControlElement* paceInsert = new AccessControlElement(); if (paceInsert == NULL) { return ERROR_OUT_OF_MEMORY; } char* pszStar = strstr (pszTemp, "*"); if (pszStar != NULL) { *pszStar = '\0'; bWildCard = true; } iErrCode = paceInsert->Initialize (pszTemp, bWildCard); if (iErrCode != OK) { return iErrCode; } if (!pllAccessList->PushLast (paceInsert)) { delete paceInsert; return ERROR_OUT_OF_MEMORY; } pszTemp = strtok (NULL, g_pszSeparator); } return OK; } //////////////////////// // Configuration data // //////////////////////// bool PageSource::IsDefault() { return m_bIsDefault; } const char* PageSource::GetName() { return m_pszName; } IConfigFile* PageSource::GetConfigFile() { Assert (m_pcfConfig != NULL); m_pcfConfig->AddRef(); return m_pcfConfig; } IReport* PageSource::GetReport() { return this; } ILog* PageSource::GetLog() { return this; } const char* PageSource::GetBasePath() { return m_pszBasePath; } const char* PageSource::GetDefaultFile() { return m_pszDefaultFile; } ICachedFile* PageSource::GetErrorFile (HttpStatus sStatus) { if (m_ppCachedFile[sStatus] != NULL) { m_ppCachedFile[sStatus]->AddRef(); } return m_ppCachedFile[sStatus]; } bool PageSource::AllowDirectoryBrowsing() { return m_bBrowsingAllowed; } bool PageSource::UseDefaultFile() { return m_bDefaultFile; } HttpAuthenticationType PageSource::GetAuthenticationType() { return m_atAuthType; } Seconds PageSource::GetDigestAuthenticationNonceLifetime() { return m_iDigestNonceLifetime; } const char* PageSource::GetAuthenticationRealm (IHttpRequest* pHttpRequest) { if (m_pPageSource == NULL) return NULL; return m_pPageSource->GetAuthenticationRealm (pHttpRequest); } bool PageSource::OverrideGet() { return m_bOverrideGet; } bool PageSource::OverridePost() { return m_bOverridePost; } bool PageSource::OverrideError (HttpStatus sStatus) { return m_pbOverrideError[sStatus]; } bool PageSource::UsePageSourceLibrary() { return m_bUsePageSourceLibrary; } bool PageSource::UseSSI() { return m_bUseSSI; } bool PageSource::UseLogging() { return m_bUseLogging; } bool PageSource::UseCommonLogFormat() { return m_bUseCommonLogFormat; } ConfigFile* PageSource::GetCounterFile() { return &m_cfCounterFile; } bool PageSource::IsIPAddressAllowedAccess (const char* pszIPAddress) { return IsAllowedAccess (m_llAllowIPAddressList, m_llDenyIPAddressList, pszIPAddress); } bool PageSource::IsUserAgentAllowedAccess (const char* pszUserAgent) { return IsAllowedAccess (m_llAllowUserAgentList, m_llDenyUserAgentList, pszUserAgent); } bool PageSource::IsAllowedAccess (const ACEList& llAllowList, const ACEList& llDenyList, const char* pszString) { if (llAllowList.GetNumElements() > 0) { return IsStringInACEList (llAllowList, pszString); } if (llDenyList.GetNumElements() > 0) { return !IsStringInACEList (llDenyList, pszString); } return true; } bool PageSource::IsGetAllowed (HttpRequest* pHttpRequest) { // If we're not filtering, allow if (!m_bFilterGets) { return true; } // Get the file requested const char* pszFileName = pHttpRequest->GetFileName(); // Allow null file requests, whatever that means if (pszFileName == NULL) { return true; } // Get the extension - find the last dot and skip it const char* pszExt = strrchr (pszFileName, '.'); if (pszExt == NULL) { // No extension, so allow return true; } pszExt ++; // See if it's a file extension of interest. If not, allow if (!IsStringInACEList (m_llDenyGetExts, pszExt)) { return true; } // Get the referer const char* pszReferer = pHttpRequest->GetReferer(); // Deny null referers if (pszReferer == NULL) { return false; } // See if it's an allowed referer. If so, allow if (IsStringInACEList (m_llAllowReferer, pszReferer)) { return true; } // Deny return false; } bool PageSource::IsStringInACEList (const ACEList& llList, const char* pszString) { ListIterator<AccessControlElement*> liIt; while (llList.GetNextIterator (&liIt)) { AccessControlElement* pAce = liIt.GetData(); if (pAce->bHasWildCard) { if (String::StrniCmp (pAce->pszString, pszString, pAce->stLength) == 0) { return true; } } else { if (String::StriCmp (pAce->pszString, pszString) == 0) { return true; } } } return false; } ///////////// // Methods // ///////////// bool PageSource::Enter() { Algorithm::AtomicIncrement (&m_iNumThreads); if (!m_bLocked) { return false; } Algorithm::AtomicDecrement (&m_iNumThreads); m_mLock.Wait(); Algorithm::AtomicIncrement (&m_iNumThreads); return true; } void PageSource::Exit (bool bLocked) { if (bLocked) { m_mLock.Signal(); } Algorithm::AtomicDecrement (&m_iNumThreads); } // IPageSource int PageSource::OnInitialize (IHttpServer* pHttpServer, IPageSourceControl* pControl) { return m_pPageSource->OnInitialize (pHttpServer, pControl); } int PageSource::OnFinalize() { if (m_pPageSource == NULL) { return OK; } int iErrCode = m_pPageSource->OnFinalize(); SafeRelease (m_pPageSource); return iErrCode; } int PageSource::OnBasicAuthenticate (IHttpRequest* pHttpRequest, bool* pbAuthenticated) { bool bLocked = Enter(); int iErrCode = m_pPageSource->OnBasicAuthenticate (pHttpRequest, pbAuthenticated); Exit (bLocked); return iErrCode; } int PageSource::OnDigestAuthenticate (IHttpRequest* pHttpRequest, bool* pbAuthenticated) { bool bLocked = Enter(); int iErrCode = m_pPageSource->OnDigestAuthenticate (pHttpRequest, pbAuthenticated); Exit (bLocked); return iErrCode; } int PageSource::OnGet (IHttpRequest* pHttpRequest, IHttpResponse* pHttpResponse) { bool bLocked = Enter(); int iErrCode = m_pPageSource->OnGet (pHttpRequest, pHttpResponse); Exit (bLocked); return iErrCode; } int PageSource::OnPost (IHttpRequest* pHttpRequest, IHttpResponse* pHttpResponse) { bool bLocked = Enter(); int iErrCode = m_pPageSource->OnPost (pHttpRequest, pHttpResponse); Exit (bLocked); return iErrCode; } int PageSource::OnError (IHttpRequest* pHttpRequest, IHttpResponse* pHttpResponse) { if (m_pPageSource == NULL) return OK; bool bLocked = Enter(); int iErrCode = m_pPageSource->OnError (pHttpRequest, pHttpResponse); Exit (bLocked); return iErrCode; } int PageSource::Configure (const char* pszConfigFileName, String* pstrErrorMessage) { char* pszRhs; size_t stLength; if (m_pszConfigFileName == NULL && pszConfigFileName != NULL) { m_pszConfigFileName = String::StrDup (pszConfigFileName); if (m_pszConfigFileName == NULL) { *pstrErrorMessage = "The server is out of memory"; return ERROR_OUT_OF_MEMORY; } } // Open PageSource config file int iErrCode = m_pcfConfig->Open (m_pszConfigFileName) != OK; if (iErrCode != OK) { *pstrErrorMessage = "The config file was invalid"; return iErrCode; } // The pagesource's name is the name of the file sans the last extension if (m_pszName == NULL) { pszRhs = strrchr (m_pszConfigFileName, '.'); const char* pszStart = strrchr (m_pszConfigFileName, '/'); if (pszStart == NULL) { pszStart = m_pszConfigFileName; } else { pszStart ++; } stLength = pszRhs - pszStart; m_pszName = new char [stLength + 1]; if (m_pszName == NULL) { *pstrErrorMessage = "The server is out of memory"; return ERROR_OUT_OF_MEMORY; } strncpy (m_pszName, pszStart, stLength); m_pszName[stLength] = '\0'; if (*m_pszName == '\0') { *pstrErrorMessage = "The page source didn't have a valid name"; return ERROR_FAILURE; } } m_bIsDefault = strcmp (m_pszName, "Default") == 0; // // Error files // char pszErrorFile [OS::MaxFileNameLength]; // 401File if (m_pcfConfig->GetParameter ("401File", &pszRhs) == OK && pszRhs == NULL) { *pstrErrorMessage = "The 401File value could not be read"; return ERROR_FAILURE; } else { if (File::ResolvePath (pszRhs, pszErrorFile) == ERROR_FAILURE) { *pstrErrorMessage = (String) "Error: The 401File value was invalid:" + pszRhs; return ERROR_FAILURE; } m_ppCachedFile[HTTP_401] = CachedFile::CreateInstance(); if (m_ppCachedFile[HTTP_401]->Open (pszErrorFile) != OK) { m_ppCachedFile[HTTP_401]->Release(); m_ppCachedFile[HTTP_401] = NULL; *pstrErrorMessage = (String) "The 401File " + pszErrorFile + " could not be opened"; return ERROR_FAILURE; } } // 403File if (m_pcfConfig->GetParameter ("403File", &pszRhs) == OK && pszRhs == NULL) { *pstrErrorMessage = "The 403File value could not be read"; return ERROR_FAILURE; } else { if (File::ResolvePath (pszRhs, pszErrorFile) == ERROR_FAILURE) { *pstrErrorMessage = (String) "Error: The 403File value was invalid:" + pszRhs; return ERROR_FAILURE; } m_ppCachedFile[HTTP_403] = CachedFile::CreateInstance(); if (m_ppCachedFile[HTTP_403]->Open (pszErrorFile) != OK) { m_ppCachedFile[HTTP_403]->Release(); m_ppCachedFile[HTTP_403] = NULL; *pstrErrorMessage = (String) "The 403File " + pszErrorFile + " could not be opened"; return ERROR_FAILURE; } } // 404File if (m_pcfConfig->GetParameter ("404File", &pszRhs) == OK && pszRhs == NULL) { *pstrErrorMessage = "The 404File value could not be read"; return ERROR_FAILURE; } else { if (File::ResolvePath (pszRhs, pszErrorFile) == ERROR_FAILURE) { *pstrErrorMessage = (String) "Error: The 404File value was invalid:" + pszRhs; return ERROR_FAILURE; } m_ppCachedFile[HTTP_404] = CachedFile::CreateInstance(); if (m_ppCachedFile[HTTP_404]->Open (pszErrorFile) != OK) { m_ppCachedFile[HTTP_404]->Release(); m_ppCachedFile[HTTP_404] = NULL; *pstrErrorMessage = (String) "The 404File " + pszErrorFile + " could not be opened"; return ERROR_FAILURE; } } // 500File if (m_pcfConfig->GetParameter ("500File", &pszRhs) == OK && pszRhs == NULL) { *pstrErrorMessage = "The 500File value could not be read"; return ERROR_FAILURE; } else { if (File::ResolvePath (pszRhs, pszErrorFile) == ERROR_FAILURE) { *pstrErrorMessage = (String) "Error: The 500File value was invalid:" + pszRhs; return ERROR_FAILURE; } m_ppCachedFile[HTTP_500] = CachedFile::CreateInstance(); if (m_ppCachedFile[HTTP_500]->Open (pszErrorFile) != OK) { m_ppCachedFile[HTTP_500]->Release(); m_ppCachedFile[HTTP_500] = NULL; *pstrErrorMessage = (String) "The 500File " + pszErrorFile + " could not be opened"; return ERROR_FAILURE; } } // 501File if (m_pcfConfig->GetParameter ("501File", &pszRhs) == OK && pszRhs == NULL) { *pstrErrorMessage = "The 501File value could not be read"; return ERROR_FAILURE; } else { if (File::ResolvePath (pszRhs, pszErrorFile) == ERROR_FAILURE) { *pstrErrorMessage = (String) "Error: The 501File value was invalid:" + pszRhs; return ERROR_FAILURE; } m_ppCachedFile[HTTP_501] = CachedFile::CreateInstance(); if (m_ppCachedFile[HTTP_501]->Open (pszErrorFile) != OK) { m_ppCachedFile[HTTP_501]->Release(); m_ppCachedFile[HTTP_501] = NULL; *pstrErrorMessage = (String) "The 501File " + pszErrorFile + " could not be opened"; return ERROR_FAILURE; } } // Override401 if (m_pcfConfig->GetParameter ("Override401", &pszRhs) == OK && pszRhs != NULL) { m_pbOverrideError[HTTP_401] = atoi (pszRhs) != 0; } else { *pstrErrorMessage = "The Override401 value could not be read"; return ERROR_FAILURE; } // Override403 if (m_pcfConfig->GetParameter ("Override403", &pszRhs) == OK && pszRhs != NULL) { m_pbOverrideError[HTTP_403] = atoi (pszRhs) != 0; } else { *pstrErrorMessage = "The Override403 value could not be read"; return ERROR_FAILURE; } // Override404 if (m_pcfConfig->GetParameter ("Override404", &pszRhs) == OK && pszRhs != NULL) { m_pbOverrideError[HTTP_404] = atoi (pszRhs) != 0; } else { *pstrErrorMessage = "The Override404 value could not be read"; return ERROR_FAILURE; } // AllowDirectoryBrowsing if (m_pcfConfig->GetParameter ("AllowDirectoryBrowsing", &pszRhs) == OK && pszRhs != NULL) { m_bBrowsingAllowed = atoi (pszRhs) != 0; } else { *pstrErrorMessage = "The AllowDirectoryBrowsing value could not be read"; return ERROR_FAILURE; } // BasePath if (m_pcfConfig->GetParameter ("BasePath", &pszRhs) == OK && pszRhs != NULL) { if (File::ResolvePath (pszRhs, m_pszBasePath) == ERROR_FAILURE) { *pstrErrorMessage = (String) "Error: The BasePath value was invalid:" + pszRhs; return ERROR_FAILURE; } if (!File::DoesDirectoryExist (m_pszBasePath) && File::CreateDirectory (m_pszBasePath) != OK) { *pstrErrorMessage = (String) "Error: The BasePath directory " + m_pszBasePath + " could not be created"; return ERROR_FAILURE; } } else { *pstrErrorMessage = "The BasePath value could not be read"; return ERROR_FAILURE; } // Add terminating slash if (m_pszBasePath [strlen (m_pszBasePath) - 1] != '/') { strcat (m_pszBasePath, "/"); } // DefaultFile if (m_pcfConfig->GetParameter ("DefaultFile", &pszRhs) == OK && pszRhs != NULL) { m_pszDefaultFile = String::StrDup (pszRhs); if (m_pszDefaultFile == NULL) { *pstrErrorMessage = "The server is out of memory"; return ERROR_OUT_OF_MEMORY; } } else { *pstrErrorMessage = "The DefaultFile value could not be read"; return ERROR_FAILURE; } // UseDefaultFile if (m_pcfConfig->GetParameter ("UseDefaultFile", &pszRhs) == OK && pszRhs != NULL) { m_bDefaultFile = atoi (pszRhs) != 0; } else { *pstrErrorMessage = "The UseDefaultFile value could not be read"; return ERROR_FAILURE; } // UseSSI /* if (m_pcfConfig->GetParameter ("UseSSI", &pszRhs) == OK && pszRhs != NULL) { m_bUseSSI = atoi (pszRhs) != 0; } else { *pstrErrorMessage = "The UseSSI value could not be read"; return ERROR_FAILURE; } */ // Set up counter file sprintf (pszErrorFile, "%s/%s.counters", m_pHttpServer->GetCounterPath(), m_pszName); iErrCode = m_cfCounterFile.Open (pszErrorFile); if (iErrCode != OK && iErrCode != WARNING) { *pstrErrorMessage = "Error: Could not open the counter file"; return ERROR_FAILURE; } iErrCode = OK; // UseLogging if (m_pcfConfig->GetParameter ("UseLogging", &pszRhs) == OK && pszRhs != NULL) { m_bUseLogging = atoi (pszRhs) != 0; } else { *pstrErrorMessage = "The UseLogging value could not be read"; return ERROR_FAILURE; } if (m_bUseLogging) { // UseCommonLogFormat if (m_pcfConfig->GetParameter ("UseCommonLogFormat", &pszRhs) == OK && pszRhs != NULL) { m_bUseCommonLogFormat = atoi (pszRhs) != 0; } else { *pstrErrorMessage = "The UseCommonLogFormat value could not be read"; return ERROR_FAILURE; } } // OnlyAllowIPAddressAccess if (m_pcfConfig->GetParameter ("OnlyAllowIPAddressAccess", &pszRhs) != OK) { *pstrErrorMessage = "The OnlyAllowIPAddressAccess value could not be read"; return ERROR_FAILURE; } if (!String::IsBlank (pszRhs)) { iErrCode = SetAccess (&m_llAllowIPAddressList, pszRhs); if (iErrCode != OK) { *pstrErrorMessage = "The OnlyAllowIPAddressAccess list could not be processed"; return iErrCode; } } else { // DenyIPAddressAccess if (m_pcfConfig->GetParameter ("DenyIPAddressAccess", &pszRhs) != OK) { *pstrErrorMessage = "The DenyIPAddressAccess value could not be read"; return ERROR_FAILURE; } if (!String::IsBlank (pszRhs)) { iErrCode = SetAccess (&m_llDenyIPAddressList, pszRhs); if (iErrCode != OK) { *pstrErrorMessage = "The DenyIPAddressAccess list could not be processed"; return iErrCode; } } } // OnlyAllowUserAgentAccess if (m_pcfConfig->GetParameter ("OnlyAllowUserAgentAccess", &pszRhs) != OK) { *pstrErrorMessage = "The OnlyAllowUserAgentAccess value could not be read"; return ERROR_FAILURE; } if (!String::IsBlank (pszRhs)) { iErrCode = SetAccess (&m_llAllowUserAgentList, pszRhs); if (iErrCode != OK) { *pstrErrorMessage = "The OnlyAllowUserAgentAccess list could not be processed"; return iErrCode; } } else { // DenyUserAgentAccess if (m_pcfConfig->GetParameter ("DenyUserAgentAccess", &pszRhs) != OK) { *pstrErrorMessage = "The DenyUserAgentAccess value could not be read"; return ERROR_FAILURE; } if (!String::IsBlank (pszRhs)) { iErrCode = SetAccess (&m_llDenyUserAgentList, pszRhs); if (iErrCode != OK) { *pstrErrorMessage = "The DenyUserAgentAccess list could not be processed"; return iErrCode; } } } // FilterGets iErrCode = m_pcfConfig->GetParameter ("FilterGets", &pszRhs); if (iErrCode != OK) { *pstrErrorMessage = "Could not read the FilterGets value from the configuration file"; return iErrCode; } m_bFilterGets = atoi (pszRhs) != 0; if (m_bFilterGets) { // FilterGetExtensions iErrCode = m_pcfConfig->GetParameter ("FilterGetExtensions", &pszRhs); if (iErrCode != OK) { *pstrErrorMessage = "Could not read the FilterGetExtensions value from the configuration file"; return iErrCode; } if (!String::IsBlank (pszRhs)) { iErrCode = SetAccess (&m_llDenyGetExts, pszRhs); if (iErrCode != OK) { *pstrErrorMessage = "The FilterGetExtensions list could not be processed"; return iErrCode; } } // FilterGetExtensions iErrCode = m_pcfConfig->GetParameter ("FilterGetAllowReferers", &pszRhs); if (iErrCode != OK) { *pstrErrorMessage = "Could not read the FilterGetAllowReferers value from the configuration file"; return iErrCode; } if (!String::IsBlank (pszRhs)) { iErrCode = SetAccess (&m_llAllowReferer, pszRhs); if (iErrCode != OK) { *pstrErrorMessage = "The FilterGetAllowReferers list could not be processed"; return iErrCode; } } } // UsePageSourceLibrary if (m_pcfConfig->GetParameter ("UsePageSourceLibrary", &pszRhs) == OK && pszRhs != NULL) { m_bUsePageSourceLibrary = atoi (pszRhs) != 0; } else { *pstrErrorMessage = "The UsePageSourceLibrary value could not be read"; return ERROR_FAILURE; } if (m_bUsePageSourceLibrary) { // OverrideGet if (m_pcfConfig->GetParameter ("OverrideGet", &pszRhs) == OK && pszRhs != NULL) { m_bOverrideGet = atoi (pszRhs) != 0; } else { *pstrErrorMessage = "The OverrideGet value could not be read"; return ERROR_FAILURE; } // OverridePost if (m_pcfConfig->GetParameter ("OverridePost", &pszRhs) == OK && pszRhs != NULL) { m_bOverridePost = atoi (pszRhs) != 0; } else { *pstrErrorMessage = "The OverridePost value could not be read"; return ERROR_FAILURE; } // UseAuthentication if (m_pcfConfig->GetParameter ("UseAuthentication", &pszRhs) == OK && pszRhs != NULL) { if (_stricmp (pszRhs, "basic") == 0) { m_atAuthType = AUTH_BASIC; } else if (_stricmp (pszRhs, "digest") == 0) { m_atAuthType = AUTH_DIGEST; } else if (_stricmp (pszRhs, "none") == 0) { m_atAuthType = AUTH_NONE; } else { *pstrErrorMessage = "The UseAuthentication value is invalid"; return ERROR_FAILURE; } } else { *pstrErrorMessage = "The UseAuthentication value could not be read"; return ERROR_FAILURE; } if (m_atAuthType == AUTH_DIGEST) { if (m_pcfConfig->GetParameter ("DigestAuthenticationNonceLifetime", &pszRhs) == OK && pszRhs != NULL) { m_iDigestNonceLifetime = atoi (pszRhs); if (m_iDigestNonceLifetime < 1) { *pstrErrorMessage = "The DigestAuthenticationNonceLifetime value is invalid"; return ERROR_FAILURE; } } else { *pstrErrorMessage = "The DigestAuthenticationNonceLifetime value could not be read"; return ERROR_FAILURE; } } // Library char* pszLibrary; if (m_pcfConfig->GetParameter ("PageSourceLibrary", &pszLibrary) != OK || pszLibrary == NULL) { *pstrErrorMessage = "The PageSourceLibrary value could not be read"; return ERROR_FAILURE; } char* pszClsid; if (m_pcfConfig->GetParameter ("PageSourceClsid", &pszClsid) != OK || pszClsid == NULL) { *pstrErrorMessage = "The PageSourceClsid value could not be read"; return ERROR_FAILURE; } // Load library size_t stPageSourcePathLen = strlen (m_pHttpServer->GetPageSourcePath()); char* pszLibName = (char*) StackAlloc (stPageSourcePathLen + strlen (pszLibrary) + 2); strcpy (pszLibName, m_pHttpServer->GetPageSourcePath()); strcat (pszLibName, "/"); strcat (pszLibName, pszLibrary); iErrCode = Initialize (pszLibName, pszClsid); if (iErrCode != OK) { *pstrErrorMessage = "The PageSource did not initialize properly."; return iErrCode; } } return iErrCode; } int PageSource::RestartPageSource (void* pVoid) { PageSource* pThis = (PageSource*) pVoid; // Take the lock pThis->m_mShutdownLock.Wait(); if (!pThis->m_bShutdown) { // Wait until we have zero callers while (pThis->m_iNumThreads > 0) { OS::Sleep (100); } // Reencarnation pThis->Clean(); // Delete everything stateful pThis->Reset(); // Set everything to original null state pThis->m_pcfConfig->Close(); String strErrorMessage; int iErrCode = pThis->Configure (NULL, &strErrorMessage); if (iErrCode != OK) { pThis->m_bScrewed = true; pThis->WriteReport ((String) "Error restarting page source. " + strErrorMessage); } else { pThis->m_bScrewed = false; } } // Not restarting anymore pThis->m_bRestart = false; pThis->m_mShutdownLock.Signal(); // If the restart failed, we just have to wait for another call to Restart() return OK; } int PageSource::Shutdown() { if (_stricmp (m_pszName, "Default") == 0 || _stricmp (m_pszName, "Admin") == 0) { return ERROR_FAILURE; } m_mShutdownLock.Wait(); if (m_bShutdown) { m_mShutdownLock.Signal(); return ERROR_FAILURE; } m_bShutdown = true; m_bRestart = false; m_mShutdownLock.Signal(); return m_pHttpServer->DeletePageSource (m_pszName); } void PageSource::LockWithNoThreads() { m_bLocked = true; m_mShutdownLock.Wait(); m_mLock.Wait(); // Spin until no threads while (m_iNumThreads > 0) { OS::Sleep (100); } m_mShutdownLock.Signal(); } void PageSource::LockWithSingleThread() { m_bLocked = true; m_mShutdownLock.Wait(); m_mLock.Wait(); // Spin until 1 thread while (m_iNumThreads > 1) { OS::Sleep (100); } m_mShutdownLock.Signal(); } void PageSource::ReleaseLock() { m_mLock.Signal(); m_bLocked = false; } unsigned int PageSource::IncrementCounter (const char* pszName) { unsigned int iNewValue; char* pszOldValue, pszNewValue [256]; // Lock m_mCounterLock.WaitWriter(); // Read old value if (m_cfCounterFile.GetParameter (pszName, &pszOldValue) == OK && pszOldValue != NULL) { iNewValue = atoi (pszOldValue) + 1; } else { iNewValue = 1; } // Assign new value m_cfCounterFile.SetParameter (pszName, _itoa (iNewValue + 1, pszNewValue, 10)); // Unlock m_mCounterLock.SignalWriter(); return iNewValue; } unsigned int PageSource::GetCounterValue (const char* pszName) { int iErrCode; unsigned int iValue; char* pszValue; // Read value m_mCounterLock.WaitReader(); iErrCode = m_cfCounterFile.GetParameter (pszName, &pszValue); m_mCounterLock.SignalReader(); if (iErrCode == OK && pszValue != NULL) { iValue = atoi (pszValue); } else { iValue = 0; } return iValue; } void PageSource::GetReportFileName (char pszFileName[OS::MaxFileNameLength]) { int iSec, iMin, iHour, iDay, iMonth, iYear; char pszMonth[20], pszDay[20]; DayOfWeek day; Time::GetDate (m_tReportTime, &iSec, &iMin, &iHour, &day, &iDay, &iMonth, &iYear); sprintf (pszFileName, "%s/%s_%i_%s_%s.report", m_pHttpServer->GetReportPath(), m_pszName, iYear, String::ItoA (iMonth, pszMonth, 10, 2), String::ItoA (iDay, pszDay, 10, 2)); } void PageSource::GetLogFileName (char pszFileName[OS::MaxFileNameLength]) { int iSec, iMin, iHour, iDay, iMonth, iYear; char pszMonth[20], pszDay[20]; DayOfWeek day; Time::GetDate (m_tLogTime, &iSec, &iMin, &iHour, &day, &iDay, &iMonth, &iYear); sprintf (pszFileName, "%s/%s_%i_%s_%s.log", m_pHttpServer->GetLogPath(), m_pszName, iYear, String::ItoA (iMonth, pszMonth, 10, 2), String::ItoA (iDay, pszDay, 10, 2)); } void PageSource::LogMessage (const char* pszMessage) { // All log file operations are best effort UTCTime tNow; Time::GetTime (&tNow); m_mLogMutex.Wait(); if (HttpServer::DifferentDays (m_tLogTime, tNow)) { OpenLog(); } if (m_fLogFile.IsOpen()) { m_fLogFile.Write (pszMessage); m_fLogFile.WriteEndLine(); } m_mLogMutex.Signal(); } int PageSource::OpenLog() { Time::GetTime (&m_tLogTime); char pszFileName [OS::MaxFileNameLength]; GetLogFileName (pszFileName); m_fLogFile.Close(); return m_fLogFile.OpenAppend (pszFileName); } void PageSource::ReportMessage (const char* pszMessage) { // All log file operations are best effort UTCTime tNow; Time::GetTime (&tNow); m_mReportMutex.Wait(); if (HttpServer::DifferentDays (m_tReportTime, tNow)) { OpenReport(); } // Add date and time DayOfWeek weekDay; int iSec, iMin, iHour, iDay, iMonth, iYear; Time::GetDate (tNow, &iSec, &iMin, &iHour, &weekDay, &iDay, &iMonth, &iYear); char pszDate [64]; snprintf ( pszDate, sizeof (pszDate), "[%.4d-%.2d-%.2d %.2d:%.2d:%.2d] ", iYear, iMonth, iDay, iHour, iMin, iSec ); m_fReportFile.Write (pszDate); m_fReportFile.Write (pszMessage); m_fReportFile.WriteEndLine(); m_mReportMutex.Signal(); } int PageSource::OpenReport() { Time::GetTime (&m_tReportTime); char pszFileName [OS::MaxFileNameLength]; GetReportFileName (pszFileName); m_fReportFile.Close(); return m_fReportFile.OpenAppend (pszFileName); } size_t PageSource::GetFileTail (File& fFile, Mutex& mMutex, const UTCTime& tTime, char* pszBuffer, size_t stNumChars) { UTCTime tZero; Time::ZeroTime (&tZero); size_t stFilePtr; *pszBuffer = '\0'; if (tTime == tZero) { return 0; } size_t stRetVal = 0; mMutex.Wait(); if (fFile.GetFilePointer (&stFilePtr) == OK) { if (stNumChars > stFilePtr) { stNumChars = stFilePtr; } if (fFile.SetFilePointer (stFilePtr - stNumChars) == OK) { if (fFile.Read (pszBuffer, stNumChars, &stRetVal) == OK) { pszBuffer[stRetVal] = '\0'; } fFile.SetFilePointer (stFilePtr); } } mMutex.Signal(); return stRetVal; } // ILog size_t PageSource::GetLogTail (char* pszBuffer, size_t stNumChars) { return GetFileTail (m_fLogFile, m_mLogMutex, m_tLogTime, pszBuffer, stNumChars); } // IReport int PageSource::WriteReport (const char* pszMessage) { size_t stLength = String::StrLen (pszMessage); if (stLength > MAX_LOG_MESSAGE) { return ERROR_INVALID_ARGUMENT; } ::LogMessage* plmMessage = m_pHttpServer->GetLogMessage(); if (plmMessage == NULL) { return ERROR_OUT_OF_MEMORY; } plmMessage->lmtMessageType = REPORT_MESSAGE; plmMessage->pPageSource = this; AddRef(); memcpy (plmMessage->pszText, pszMessage, stLength + 1); int iErrCode = m_pHttpServer->PostMessage (plmMessage); if (iErrCode != OK) { // Otherwise, the LogMessage instance owns the reference Release(); m_pHttpServer->FreeLogMessage (plmMessage); } return iErrCode; } size_t PageSource::GetReportTail (char* pszBuffer, size_t stNumChars) { return GetFileTail (m_fReportFile, m_mReportMutex, m_tReportTime, pszBuffer, stNumChars); }
[ "9204f08b50a98ce38b138b6abea8393a28df75c8xFrFtkcc" ]
9204f08b50a98ce38b138b6abea8393a28df75c8xFrFtkcc
7a34322f4845b1291815ff52d120f81e0041f40c
2992da59793ad33e140f85c6297575fd8ad9184f
/vector.h
3137c0da0fd2b812ecd0f911a69683fd74e9b172
[]
no_license
han-hs16/mystl
18796ab122f53aa857ae2d4dbe6ec53650f01e6e
f65f915d74b080a8b5ab1b0c7b5c86a772a8efb0
refs/heads/master
2022-12-22T15:55:47.837517
2020-10-03T14:21:37
2020-10-03T14:21:37
300,896,469
1
0
null
null
null
null
GB18030
C++
false
false
8,538
h
#pragma once #include "defs.h" #include "util.h" namespace mystl { #define DEFALT_CAPACITY 3 typedef long Rank; template<typename T> class vector { protected: Rank _size; int _capacity; T* _elem; void copyFrom(T const* A, Rank lo, Rank hi); void expand();//扩容 void shrink();//压缩 bool bubble(Rank lo, Rank hi); void bubbleSort(Rank lo, Rank hi); Rank max(Rank lo, Rank hi); void selectionSort(Rank lo, Rank hi); void merge(Rank lo,Rank mi, Rank hi); void mergeSort(Rank lo, Rank hi); Rank partition(Rank lo, Rank hi); void quickSort(Rank lo, Rank hi); void heapSort(Rank lo, Rank hi); void swapByRank(Rank a, Rank b); public: // construct vector(int c = DEFALT_CAPACITY, int s = 0, T v = 0) { if (s > c) exit(-1); _elem = new T[_capacity = c]; for (_size = 0;_size < s; _elem[_size++] = v); } vector(T const* A, Rank lo, Rank hi) { copyFrom(A, lo, hi); } vector(T const* A, Rank n) { copyFrom(A, 0, n); } vector(vector<T> const& v, Rank lo, Rank hi) { copyFrom(v._elem, lo, hi); } vector(vector<T> const& v) { copyFrom(v._elem, 0, v._size); } //析构 ~vector(){delete[] _elem;} // only read api Rank size() const { return _size; } bool empty() const { return !_size; } int disordered() const; // wether sorted? Rank find(T const& e) const { return find(e, 0, _size); } Rank find(T const& e, Rank lo, Rank hi) const; Rank search(T const& e) const { return (0 >= _size) ? -1 : search(e, 0, _size); } Rank search(T const& e, Rank lo, Rank hi) const; // read / write T& operator[] (Rank r) const; vector<T>& operator=(vector<T> const&); T remove(Rank r); // remove rank k, not elem int remove(Rank lo, Rank hi); // delete elems in [lo, hi) Rank insert(Rank k, T const& e); Rank insert(T const& e) { return insert(_size, e); } Rank push_back(T const& e) { return insert(_size, e); }; Rank pop_back() { return remove(_size - 1); }; void sort() { sort(0, _size); } void sort(Rank lo, Rank hi); void unsort(Rank lo, Rank hi); // 置乱 void unsort() { unsort(0, _size); } int deduplicate(); //无序去重e int uniquify(); //有序去重 // visit void traverse(void (*visit)(T&)); //使用函数指针进行遍历, 只读或局部性修改 template <typename VST> void traverse(VST&); //遍历, 使用函数对象,可全局性修改 // show void show() { for (int i = 0;i < _size;i++) std::cout << _elem[i] << " "; std::cout << std::endl; } }; /* * ========================== implement ==================================== */ template<typename T> void vector<T>::copyFrom(T const* A, Rank lo, Rank hi) { // should we check wether the _elem already exist? _elem = new T[2 * (hi - lo)]; _size = 0; while (lo < hi) _elem[_size++] = A[lo++]; expand(); } template<typename T> void vector<T>::expand() { if (_size < _capacity) return; if (_capacity < DEFALT_CAPACITY) _capacity = DEFALT_CAPACITY; if (_capacity < _size) _capacity = _size; T* oldelem = _elem; _elem = new T[_capacity << 1]; for (int i = 0;i < _size;i++) _elem[i] = oldelem[i]; delete[] oldelem; } template<typename T> void vector<T>::shrink() { if (_capacity < DEFALT_CAPACITY << 1) return; // too small to shrink if (_size << 2 > _capacity) return; //_size > 0.25 _capacity, dont need to shrink T* oldelem = _elem; // _elem = new T[_capacity >> 1] // capacity / 2 _elem = new T[_size << 1]; // _size * 2 for (int i = 0;i < _size;i++) _elem[i] = oldelem[i]; delete[] oldelem; } template<typename T> void vector<T>::bubbleSort(Rank lo, Rank hi) { while (!bubble(lo, hi--)); } template<typename T> bool vector<T>::bubble(Rank lo, Rank hi) { bool sorted = true; while (++lo < hi) { if (_elem[lo - 1] > _elem[lo]) { sorted = false; swapByRank(lo-1, lo); } } return sorted; } template <typename T> void vector<T>::mergeSort(Rank lo, Rank hi) { if (hi - lo < 2) return ; // 只有一个 int mi = (lo + hi) >> 1; mergeSort(lo, mi); mergeSort(mi, hi); merge(lo, mi, hi); } template<typename T> void vector<T>::merge(Rank lo, Rank mi, Rank hi) { T* A = _elem + lo; int lb = mi - lo; T* B = new T[lb]; for (Rank i = 0; i < lb; B[i] = A[i++]); int lc = hi - mi; T* C = _elem + mi; for (Rank i = 0, j = 0, k = 0; (j < lb) || (k < lc); ) { if ((j < lb) && (!(k < lc) || (B[j] <= C[k]))) A[i++] = B[j++]; // 保证稳定性 if ((k < lc) && (!(j < lb) || (C[k] < B[j]))) A[i++] = C[k++]; } delete[] B; } template<typename T> void vector<T>::swapByRank(Rank a, Rank b) { T tmp = _elem[a]; _elem[a] = _elem[b]; _elem[b] = tmp; } template<typename T> void vector<T>::selectionSort(Rank lo, Rank hi) { for (;lo < hi;hi--) { Rank mxR = max(lo, hi); swapByRank(mxR, hi-1); } } template<typename T> Rank vector<T>::partition(Rank lo, Rank hi) { Rank p = lo; T key = _elem[p]; while (lo < hi) { while ((lo < hi) && (key <= _elem[--hi])); if (lo < hi) { //swapByRank(p, hi); _elem[lo] = _elem[hi]; lo++; } while ((lo < hi) && (_elem[lo++] < key)); if (lo < hi) { //swapByRank(p, lo); _elem[hi] = _elem[lo]; hi--; } _elem[lo] = key; return lo; } return p; } template<typename T> void vector<T>::quickSort(Rank lo, Rank hi) { if (lo >= hi) return; Rank p = partition(lo, hi); quickSort(lo, p); quickSort(p + 1, hi); } // TODO template<typename T> void vector<T>::heapSort(Rank lo, Rank hi) { } template<typename T> Rank vector<T>::max(Rank lo, Rank hi) { Rank mxR = lo; while (++lo < hi) { if (_elem[mxR] < _elem[lo]) mxR = lo; } return mxR; } // public #pragma region R template<typename T> Rank vector<T>::find(T const& e, Rank lo, Rank hi) const { while ((lo <= --hi) && (e != _elem[hi])); return hi; // fail -> return lo; } template<typename T> int vector<T>::disordered() const { int n = 0; for (int i = 0;i < _size - 1;i++) if (_elem[i] > _elem[i + 1]) n++; return n; } template<typename T> Rank vector<T>::search(T const& e, Rank lo, Rank hi) const { return (rand() % 2) ? binSearch(_elem, e, lo, hi) : fibSearch(_elem, e, lo, hi); } #pragma endregion #pragma region R/W template<typename T> vector<T>& vector<T>::operator=(vector<T> const& vt) { if (_elem) delete[] _elem; //release copyFrom(vt._elem, 0, vt.size()); return *this; } template<typename T> T& vector<T>::operator[] (Rank r) const { return _elem[r]; } template<typename T> int vector<T>::remove(Rank lo, Rank hi) { for (int i = hi; i < _size; i++) _elem[lo++] = _elem[hi++]; _size = lo; // update size shrink(); return hi - lo; // return number of deleted elems } template<typename T> T vector<T>::remove(Rank r) { T e = _elem[r]; remove(r, r + 1); return e; } template<typename T> Rank vector<T>::insert(Rank k, T const& e) { expand(); for (int i = _size;i > k;i--) _elem[i] = _elem[i - 1]; _elem[k] = e; _size++; return _size; } template<typename T> void vector<T>::unsort(Rank lo, Rank hi) { /* for (int i = hi - 1; i >= lo; i--) swapByRank(v[i - 1], v[(rand() % i) + lo]); */ // book T* v = _elem + lo; for (int i = hi - lo; i > 0; i--) swapByRank(v[i - 1], v[rand() % i]); } template<typename T> int vector<T>::deduplicate() { int oldSize = _size; Rank i = 1; while (i < _size) (find(_elem[i], 0, i) < 0) ? i++ : remove(i); return oldSize - _size; // decreased number } template<typename T> int vector<T>::uniquify() { int i = 0, j = 0; while (++j < _size) { if (_elem[i] != _elem[j]) _elem[++i] = _elem[j]; } _size = ++i; shrink(); return j - i; } template<typename T>// function pointer void vector<T>::traverse(void (*visit)(T&)) { for (int i = 0;i < _size;i++) visit(_elem[i]); } /* // 函数对象 template<typename T> struct Increase {virtual void operator()(T& e) {e++;} } template<typename T> void increase(vector<T> & v) {v.traverse(Increase<T>()); } */ template<typename T> template<typename VST> // 利用函数对象机制的遍历 void vector<T>::traverse(VST& visit) { for (int i = 0;i < _size; i++) visit(_elem[i]); } template <typename T> void vector<T>::sort(Rank lo, Rank hi) { int flag = rand() % 4; flag = 5; switch (flag) { case 1: bubbleSort(lo, hi); break; case 2: selectionSort(lo, hi); break; case 3: mergeSort(lo, hi);break; case 4: heapSort(lo, hi); break; default: quickSort(lo, hi); break; } } #pragma endregion };
[ "57581573+han-hs16@users.noreply.github.com" ]
57581573+han-hs16@users.noreply.github.com
477046972f9a3b41dcdc06f0fca75a81c9e7495c
1bcb966740f47c0edc23e9b05afec55f2bcae36a
/client/cplusplus/TeXiao.cpp
3ca88621b45b2d0c60a09c0f1ca1d56337b6bea6
[]
no_license
East196/diabloworld
0d2e9dbf650aa86fcc7b9fc1ef49912e79adb954
d7a83a21287ed66aea690ecb6b73588569478be6
refs/heads/master
2021-05-09T12:15:31.640065
2018-02-04T15:16:54
2018-02-04T15:16:54
119,007,609
3
2
null
null
null
null
UTF-8
C++
false
false
13,417
cpp
#include "TeXiao.h" static texiao * tx=NULL; //bool texiao::init(){ // if(!CCSprite::init()){ // return false; // } // this->texiaoCreate(); // return true; //} texiao::texiao(){ //加载图片缓存 CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("result_attacked.plist"); } texiao::~texiao(){ } texiao * texiao::TX(){ if (!tx) { tx= new texiao(); } return tx; } CCSprite * texiao::lingqucg(){ CCArray *lqcg=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("lq_lq_01.png"); CCSprite *lq=CCSprite::createWithSpriteFrame(pFrame); for (int i=2;i<=8; i++) { char allnames[50]=""; sprintf(allnames, "lq_lq_%02d.png",i); CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(allnames); //CCString::createWithFormat("zxj_%02d.png",i)->getCString() lqcg->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(lqcg,0.15f))); lq->runAction(Action); return lq; } CCSprite * texiao::duoqucg(){ CCArray *dqsb=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("lq_cg_01.png"); CCSprite *dq=CCSprite::createWithSpriteFrame(pFrame); for (int i=2;i<=9; i++) { char allnames[50]=""; sprintf(allnames, "lq_cg_%02d.png",i); CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(allnames); //CCString::createWithFormat("zxj_%02d.png",i)->getCString() dqsb->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(dqsb,0.15f))); dq->runAction(Action); return dq; } CCSprite * texiao::duoqusb(){ CCArray *dqcg=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("lq_sb_01.png"); CCSprite *dq=CCSprite::createWithSpriteFrame(pFrame); for (int i=2;i<=9; i++) { char allnames[50]=""; sprintf(allnames, "lq_sb_%02d.png",i); CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(allnames); //CCString::createWithFormat("zxj_%02d.png",i)->getCString() dqcg->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(dqcg,0.15f))); dq->runAction(Action); return dq; } CCSprite * texiao::yanwu(){ CCArray *yanwu=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("ef_01.png"); CCSprite *yw=CCSprite::createWithSpriteFrame(pFrame); for (int i=2;i<=22; i++) { char allnames[50]=""; sprintf(allnames, "ef_%02d.png",i); CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(allnames); //CCString::createWithFormat("zxj_%02d.png",i)->getCString() yanwu->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(yanwu,0.083f))); yw->runAction(Action); return yw; } CCSprite * texiao::dayan(){ CCArray *daya=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("dy_00016.png"); CCSprite *yw=CCSprite::createWithSpriteFrame(pFrame); for (int i=16;i<=62; i++) { char allnames[50]=""; sprintf(allnames, "dy_%05d.png",i); CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(allnames); daya->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(daya,0.0417f))); yw->runAction(Action); return yw; } CCSprite * texiao::texiaosCreate(const char *name, int num){ char names[20]=""; sprintf(names, "%s_01.png",name); CCArray *zuixingArr=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(names);//"zxj_01.png" CCSprite *zxjsp=CCSprite::createWithSpriteFrame(pFrame); for (int i=2;i<=num; i++) { char allnames[50]=""; sprintf(allnames, "%s_%02d.png",name,i); CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(allnames); //CCString::createWithFormat("zxj_%02d.png",i)->getCString() zuixingArr->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(zuixingArr,0.125f))); zxjsp->runAction(Action); return zxjsp; } //受伤特效 CCSprite * texiao:: texiaoCreate(){ CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("result_00001.png"); CCSprite *tzsp=CCSprite::createWithSpriteFrame(pFrame); CCArray * kneif=CCArray::create(); for (int i=2;i<=8; i++) { CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(CCString::createWithFormat("result_%05d.png",i)->getCString()); kneif->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(kneif,0.2f))); tzsp->runAction(Action); return tzsp; } CCSprite * texiao::beginyanwu(){ CCArray *touzhiArr=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("begin_yw_01.png"); CCSprite *tzsp=CCSprite::createWithSpriteFrame(pFrame); //tzsp->setPosition(ccp(player->getPosition().x, player->getPosition().y)); for (int i=2;i<=16; i++) { CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(CCString::createWithFormat("begin_yw_%02d.png",i)->getCString()); touzhiArr->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(touzhiArr,0.125f))); tzsp->runAction(Action); return tzsp; } //投掷特效 CCSprite * texiao:: touzhiCreate(){ CCArray *touzhiArr=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("tz-01.png"); CCSprite *tzsp=CCSprite::createWithSpriteFrame(pFrame); //tzsp->setPosition(ccp(player->getPosition().x, player->getPosition().y)); for (int i=2;i<=8; i++) { CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(CCString::createWithFormat("tz-%02d.png",i)->getCString()); touzhiArr->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(touzhiArr,0.2f))); tzsp->runAction(Action); return tzsp; } //投掷命中特效 CCSprite * texiao::mingzhongCreate(){ CCArray *mingzhongArr=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("mz-01.png"); CCSprite *mzsp=CCSprite::createWithSpriteFrame(pFrame); //tzsp->setPosition(ccp(player->getPosition().x, player->getPosition().y)); for (int i=2;i<=7; i++) { CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(CCString::createWithFormat("mz-%02d.png",i)->getCString()); mingzhongArr->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(mingzhongArr,0.2f))); mzsp->runAction(Action); return mzsp; } //普通攻击 CCSprite * texiao::normalAttackCreate(){ CCArray *mingzhongArr=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("n_attack_01.png"); CCSprite *mzsp=CCSprite::createWithSpriteFrame(pFrame); //tzsp->setPosition(ccp(player->getPosition().x, player->getPosition().y)); for (int i=2;i<=5; i++) { CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(CCString::createWithFormat("n_attack_%02d.png",i)->getCString()); mingzhongArr->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(mingzhongArr,0.1f))); mzsp->runAction(Action); return mzsp; } //醉醒技 CCSprite * texiao::zuixingji(){ CCArray *zuixingArr=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("zxj_01.png"); CCSprite *zxjsp=CCSprite::createWithSpriteFrame(pFrame); for (int i=2;i<=10; i++) { CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(CCString::createWithFormat("zxj_%02d.png",i)->getCString()); zuixingArr->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(zuixingArr,0.1f))); zxjsp->runAction(Action); return zxjsp; } //太极八卦 CCSprite * texiao::taijibagua(){ CCArray *tjbgArr=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("tjbg_01.png"); CCSprite *tjbgsp=CCSprite::createWithSpriteFrame(pFrame); for (int i=2;i<=12; i++) { CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(CCString::createWithFormat("tjbg_%02d.png",i)->getCString()); tjbgArr->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(tjbgArr,0.1f))); tjbgsp->runAction(Action); return tjbgsp; } //天公怒 CCSprite * texiao::tiangongnu(){ CCArray *tgnArr=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("tgn_01.png"); CCSprite *tgnsp=CCSprite::createWithSpriteFrame(pFrame); for (int i=2;i<=9; i++) { CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(CCString::createWithFormat("tgn_%02d.png",i)->getCString()); tgnArr->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(tgnArr,0.1f))); tgnsp->runAction(Action); return tgnsp; } //遇神诛神 CCSprite * texiao::yushenzhushen(){ CCArray *yszsArr=CCArray::create(); CCSpriteFrame *pFrame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("yszs_01.png"); CCSprite *yszssp=CCSprite::createWithSpriteFrame(pFrame); for (int i=2;i<=9; i++) { CCSpriteFrame *spf=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(CCString::createWithFormat("yszs_%02d.png",i)->getCString()); yszsArr->addObject(spf); } CCActionInterval * Action=CCRepeatForever::create(CCAnimate::create(CCAnimation::createWithSpriteFrames(yszsArr,0.1f))); yszssp->runAction(Action); return yszssp; } //CCSprite * texiao::huangquezhen(){ // //} //CCSprite * texiao::kunshouzhidou(){ // //}//困兽之斗 //CCSprite * texiao::luandaozhan(){ // //}//乱刀斩 //CCSprite * texiao::meirenji(){ // //}//美人计 //CCSprite * texiao::pojunji(){ // //}//破军计 //CCSprite * texiao::qubingji(){ // //}//屈兵计 //CCSprite * texiao::shengdongjixi_mz(){ // //}//声东击西-命中 //CCSprite * texiao::shengdongjixi_tz(){ // //}//声东击西-投掷 //CCSprite * texiao::shijizhou(){ // //}//狮子吼 //CCSprite * texiao::shuangfuzhishang_cz(){ // //}//双斧之伤-出招 //CCSprite * texiao::shuangfuzhishang_mz(){ // //}//双斧之伤-命中 //CCSprite * texiao::shuangjizhishang_cz(){ // //}//双戟之伤-出招 //CCSprite * texiao::texiao::shuangjizhishang_mz(){ // //}//双戟之伤-命中 //CCSprite * texiao::shuanglianzhishang_cz(){ // //}//双廉之伤-出招 //CCSprite * texiao::shuanglianzhishang_mz(){ // //}//双廉之伤-命中 //CCSprite * texiao::shuangqiangzhishang_cz(){ // //}//双枪之伤-出招 //CCSprite * texiao::shuangqiangzhishang_mz() //{ // //}//双枪之伤-命中 //CCSprite * texiao::shuangrenzhishang_cz(){ // //}//双刃之伤-出招 //CCSprite * texiao::shuangrenzhishang_mz(){ // //}//双刃之伤-命中 //CCSprite * texiao::shuijisanqianli(){ // //}//水击三千里 //CCSprite * texiao::touxi(){ // //}//偷袭 //CCSprite * texiao::wanlibingfeng(){ // //}//万里冰封 //CCSprite * texiao::xiefengzhen(){ // //}//邪风阵 //CCSprite * texiao::yehuoliaoyuan(){ // //}//野火燎原 //移除方法 void texiao::removeSprite(CCNode *sender){ this->removeFromParentAndCleanup(true); }
[ "2901180515@qq.com" ]
2901180515@qq.com
22c3c80b82ff8cacdfda6e7759027b70c6ec59ae
f08307d0f973f1f29057cf66ac539b3d6a60860a
/Source/Application.cpp
9db5543e59713b525dc51aeac63eb6e3d9a25c0b
[]
no_license
maiger/CloneCraft
0297b2e34aac0b60dced4e4fcfbd6d1888cd412e
0c9b8ed930f7b3a280218b75a3eb31bf8ae2164f
refs/heads/master
2021-01-13T15:02:09.708118
2017-03-20T15:57:31
2017-03-20T15:57:31
79,338,289
0
0
null
null
null
null
UTF-8
C++
false
false
774
cpp
#include "Application.h" #include "Display.h" #include "States/SPlaying.h" Application::Application() { pushState(std::make_unique<State::Playing>(*this)); } void Application::runMainGameLoop() { sf::Clock clock; while(Display::isOpen()) { auto dt = clock.restart().asSeconds(); m_renderer.clear(); // Do stuff with states m_states.top()->input (camera); camera.update(); m_states.top()->update (camera, dt); m_states.top()->draw (m_renderer); m_renderer.update(camera); Display::checkForClose(); } } void Application::pushState(std::unique_ptr<State::Game_State> state) { m_states.push(std::move(state)); } void Application::popState() { m_states.pop(); }
[ "mage_ege@hotmail.com" ]
mage_ege@hotmail.com
5d31fc689da6d293c88506c4a51d39a67e795e13
e2f8bb5b962705ea899a1594a3f6c0feffcc3bf3
/tests/mock_tcp_connection.hpp
0034eddcdf5893b466a7db7989b4df8d2ee373a6
[ "MIT" ]
permissive
Q-Minh/EventStore.Client.Api.Cpp
d6a707165bc92530834e316d557125e0b6056e3b
a2e7965b0b2be25dc78454587e0ed10b7cff1b6c
refs/heads/master
2020-07-11T18:37:33.967081
2020-03-12T19:51:34
2020-03-12T19:51:34
204,616,571
1
0
null
2019-09-05T21:47:40
2019-08-27T04:01:18
C++
UTF-8
C++
false
false
524
hpp
#pragma once #ifndef ES_MOCK_TCP_CONNECTION_HPP #define ES_MOCK_TCP_CONNECTION_HPP namespace es { namespace test { /* For now, the only type requirements for ConnectionType for read operations are these */ template <class AsyncReadStream> class mock_tcp_connection { public: explicit mock_tcp_connection(AsyncReadStream&& read_stream) : read_stream_(std::move(read_stream)) {} AsyncReadStream& socket() { return read_stream_; } private: AsyncReadStream read_stream_; }; } } #endif // ES_MOCK_TCP_CONNECTION_HPP
[ "tonthat.quocminh@gmail.com" ]
tonthat.quocminh@gmail.com
88ed13e56ad4b94efcb3a16c0dad64b09ef1cff2
3f78ac9921f1d12340210045af9659f8485fb521
/GraphicalAuthentication/eg2.cpp
d1138236de064d5529cf3d518f44aa5540228412
[]
no_license
cfyuen/Topcoder-Marathon
d2d1d42540081255432bdd2e34b9f255c83bf84d
0b617f323212ea08a48c1a7748696ddef669178b
refs/heads/master
2020-03-19T06:01:34.617770
2018-06-04T08:16:26
2018-06-04T08:16:26
135,984,163
0
0
null
null
null
null
UTF-8
C++
false
false
15,881
cpp
#include<iostream> #include<vector> #include<string> #include<cstdio> #include<algorithm> #include<sstream> #include<fstream> #include<set> #include<queue> #include<cmath> using namespace std; struct Image { vector<string> det; int sco; }; template <class STR> int s2i (STR S) { istringstream IS(S); int I; IS >> I; return I; } int sz,callnr; vector<Image> all; vector<vector<vector<int> > > prev; vector<int> sucx,sucy,final; set<int> hull,used; bool cmp (Image a,Image b) { return a.sco>b.sco; } int cross (int x1,int y1,int x2,int y2) { return x1*y2-y1*x2; } class GraphicalAuthentication { public: int shoulderSurfing(int K, int M, int SZ) { sz=SZ; cout << K << " " << M << endl; while (true) { cout << "RESTART " << callnr << endl; vector<string> suc(Spy::successfulLogin()); sucx.push_back(s2i(suc[1])); sucy.push_back(s2i(suc[0])); int gx=sucx[sucx.size()-1]/sz,gy=sucy[sucy.size()-1]/sz; cout << sucx[sucx.size()-1] << " " << sucy[sucy.size()-1] << " " << gx << " " << gy << endl; /* cout << suc[0] << " " << suc[1] << endl; for (int i=2; i<10*sz+2; i++) { for (int j=0; j<suc[i].length(); j++) if (suc[i][j]=='1') cout << '#'; else cout << '.'; cout << endl; } */ //process grid vector<vector<int> > cur; for (int m=0; m<10; m++) { vector<int> row; for (int n=0; n<10; n++) { int empty=1; for (int i=0; i<sz; i++) for (int j=0; j<sz; j++) { //if (suc[m*sz+i+2][n*sz+j]!='0' && empty==1) cout << m*sz+i << " " << n*sz+j << endl << endl; if (suc[m*sz+i+2][n*sz+j]!='0') empty=0; } if (empty==0) { int k; for (k=0; k<all.size(); k++) { int dif=0; //cout << k << " " << all[k].det[0][0] << endl<<flush; for (int i=0; i<sz; i++) for (int j=0; j<sz; j++) { if (all[k].det[i][j]!=suc[m*sz+i+2][n*sz+j]) dif++; } if (dif<=8) { row.push_back(k); break; } } //cout << k << endl << flush; if (k==all.size()) { Image nim; for (int i=0; i<sz; i++) { string nrow=""; for (int j=0; j<sz; j++) nrow+=suc[m*sz+i+2][n*sz+j]; nim.det.push_back(nrow); } nim.sco=0; all.push_back(nim); row.push_back(k); } } else row.push_back(-1); } cur.push_back(row); /* for (int n=0; n<10; n++) cout << row[n] << " "; cout << endl; cout << flush; */ } //cout << endl; prev[callnr]=cur; callnr++; cout << "point: " << cur[gx][gy] << endl; //calculate score hull.clear(); priority_queue<pair<int,int> > pq; //cout << pq.size() << endl; for (int i=0; i<all.size(); i++) { pq.push(make_pair(all[i].sco,i)); //cout << i << " sco: " << all[i].sco << endl; } for (int i=0; i<M; i++) if (!pq.empty() && pq.top().first>0) { hull.insert(pq.top().second); //cout << pq.top().second << " sco: " << pq.top().first << endl; pq.pop(); } //cout << hull.size() << endl; if (hull.empty()) { if (cur[gx][gy]==-1) continue; all[cur[gx][gy]].sco=10; //cout << cur[gx][gy] << endl; continue; } //cout << "BEGIN SEARCH" << endl; //************************************************************************************************************** int allin=1; for (int k=callnr-1; k>=0; k--) { hull.clear(); priority_queue<pair<int,int> > pqi; for (int i=0; i<all.size(); i++) pqi.push(make_pair(all[i].sco,i)); for (int i=0; i<M; i++) if (!pqi.empty() && pqi.top().first>0) { hull.insert(pqi.top().second); cout << pqi.top().second << " sco: " << pqi.top().first << endl; pqi.pop(); } /* for (set<int>::iterator it=hull.begin(); it!=hull.end(); it++) cout << *it << " "; cout << endl; */ /* for (int i=0; i<10; i++) { for (int j=0; j<10; j++) if (i==sucx[k]/sz && j==sucy[k]/sz) cout << "#"; else if (hull.find(prev[k][i][j])!=hull.end()) cout << "*"; else cout << "."; cout << endl; } */ //make convex hull used.clear(); vector<pair<int,int> > coor,vex; for (int i=0; i<10; i++) for (int j=0; j<10; j++) { //cout << i << " " << j << " " << prev[k][i][j] << " " << cur[i][j] << endl; if (hull.find(prev[k][i][j])!=hull.end()) { coor.push_back(make_pair(i*sz,j*sz)); coor.push_back(make_pair(i*sz+sz-1,j*sz)); coor.push_back(make_pair(i*sz,j*sz+sz-1)); coor.push_back(make_pair(i*sz+sz-1,j*sz+sz-1)); used.insert(prev[k][i][j]); } } if (used.find(prev[k][sucx[k]/sz][sucy[k]/sz])!=used.end() && k==callnr-1) { all[prev[k][sucx[k]/sz][sucy[k]/sz]].sco+=10; continue; } int pnr=coor.size(); //cout << pnr << endl; if (pnr==0) { all[prev[k][sucx[k]/sz][sucy[k]/sz]].sco+=10; continue; } //core part of convex hull int st=0,now=0; for (int i=0; i<pnr; i++) if (coor[i]<coor[now]) now=i; st=now; do { vex.push_back(make_pair(coor[now].first,coor[now].second)); int tpt=-1; for (int i=0; i<pnr; i++) if (i!=now) { if (tpt==-1) tpt=i; int crs=cross(coor[i].first-coor[now].first,coor[i].second-coor[now].second,coor[tpt].first-coor[now].first,coor[tpt].second-coor[now].second); if (crs<0) tpt=i; } now=tpt; } while (now!=st); /* for (int i=0; i<vex.size(); i++) cout << vex[i].first << " " << vex[i].second << endl; */ //if convex hull has too many points // all points-, regenerate int inhull=1,cx=0,cy=0,vnr=vex.size(); for (int i=0; i<vnr; i++) { cx+=vex[i].first; cy+=vex[i].second; } cx/=vnr; cy/=vnr; for (int i=0; i<vnr; i++) { int cpc=cross(vex[(i+1)%vnr].first-vex[i].first,vex[(i+1)%vnr].second-vex[i].second,cx-vex[i].first,cy-vex[i].second); int cps=cross(vex[(i+1)%vnr].first-vex[i].first,vex[(i+1)%vnr].second-vex[i].second,sucx[k]-vex[i].first,sucy[k]-vex[i].second); if (cpc*cps<0) inhull=0; } if (inhull==1) { cout << "INHULL" << endl; if (hull.size()==M) { int area=0; for (int i=0; i<vnr; i++) area+=vex[i].first*vex[(i+1)%vnr].second-vex[i].second*vex[(i+1)%vnr].first; area=abs(area)/2; cout << "area: " << area << endl; /* for (set<int>::iterator it=used.begin(); it!=used.end(); it++) cout << *it << " "; cout << endl; */ if (area<325) { for (set<int>::iterator it=used.begin(); it!=used.end(); it++) all[*it].sco+=21; } else if (area<1000) { for (set<int>::iterator it=used.begin(); it!=used.end(); it++) all[*it].sco+=15; } else if (area<2000) { for (set<int>::iterator it=used.begin(); it!=used.end(); it++) all[*it].sco+=8; } else if (area<5000) { for (set<int>::iterator it=used.begin(); it!=used.end(); it++) all[*it].sco+=4; } else if (area<10000) { for (set<int>::iterator it=used.begin(); it!=used.end(); it++) all[*it].sco+=1; } } } else { cout << "OUTHULL" << endl; allin=0; int mx=0; for (set<int>::iterator it=used.begin(); it!=used.end(); it++) if (all[*it].sco>mx) mx=all[*it].sco; all[prev[k][sucx[k]/sz][sucy[k]/sz]].sco+=21; //see if adding a image cover point vector<int> canadd; for (int i=0; i<10; i++) for (int j=0; j<10; j++) if (prev[k][i][j]!=-1) { coor.push_back(make_pair(i*sz,j*sz)); coor.push_back(make_pair(i*sz+sz-1,j*sz)); coor.push_back(make_pair(i*sz,j*sz+sz-1)); coor.push_back(make_pair(i*sz+sz-1,j*sz+sz-1)); int st=0,now=0; vex.clear(); for (int l=0; l<pnr+4; l++) if (coor[l]<coor[now]) now=l; st=now; do { vex.push_back(make_pair(coor[now].first,coor[now].second)); int tpt=-1; for (int l=0; l<pnr+4; l++) if (l!=now) { if (tpt==-1) tpt=l; int crs=cross(coor[l].first-coor[now].first,coor[l].second-coor[now].second,coor[tpt].first-coor[now].first,coor[tpt].second-coor[now].second); if (crs<0) tpt=l; } now=tpt; } while (now!=st); coor.erase(coor.end()-4,coor.end()); vnr=vex.size(); inhull=1; for (int l=0; l<vnr; l++) { int cpc=cross(vex[(l+1)%vnr].first-vex[l].first,vex[(l+1)%vnr].second-vex[l].second,cx-vex[l].first,cy-vex[l].second); int cps=cross(vex[(l+1)%vnr].first-vex[l].first,vex[(l+1)%vnr].second-vex[l].second,sucx[k]-vex[l].first,sucy[k]-vex[l].second); if (cpc*cps<0) inhull=0; } if (inhull==1) canadd.push_back(prev[k][i][j]); } for (int i=0; i<canadd.size(); i++) if (hull.find(canadd[i])==hull.end()) all[canadd[i]].sco+=6; } //break; //for (int i=0; i<all.size(); i++) // cout << i << " " << all[i].sco << endl; } //if sucx,sucy is in corner (the triangle), corner+=999999; if (callnr>99 || (allin==1 && callnr>M*10-1)) break; //cout << endl << endl; } priority_queue<pair<int,int> > pq; for (int i=0; i<all.size(); i++) if (all[i].sco>0) pq.push(make_pair(all[i].sco,i)); for (int i=0; i<M; i++) if (!pq.empty()) { cout << pq.top().second << " sco: " << pq.top().first << endl; for (int j=0; j<sz; j++) { for (int k=0; k<sz; k++) if (all[pq.top().second].det[j][k]=='1') cout << "#"; else cout << "."; cout << endl; } final.push_back(pq.top().second); pq.pop(); } return 1; } vector <int> loginAttempt(vector <string> scr) { vector<int> ret; ret.push_back(90); ret.push_back(90); /* for (int i=0; i<scr.size(); i++) { for (int j=0; j<scr[0].length(); j++) if (scr[i][j]=='1') cout << "#"; else cout << "."; cout << endl; } */ /* for (int i=0; i<final.size(); i++) cout << final[i] << " "; cout << endl; cout << ret.size() << endl; cout << "New" << endl; */ int prior=1000; for (int m=0; m<10; m++) { for (int n=0; n<10; n++) { int empty=1; for (int i=0; i<sz; i++) for (int j=0; j<sz; j++) { if (scr[m*sz+i][n*sz+j]!='0') empty=0; } if (empty==0) { for (int k=0; k<final.size(); k++) { int dif=0; for (int i=0; i<sz; i++) for (int j=0; j<sz; j++) if (all[final[k]].det[i][j]!=scr[m*sz+i][n*sz+j]) dif++; if (dif<=8 && k<prior) { ret[0]=(n*sz+9); ret[1]=(m*sz+9); prior=k; //cout << m << " " << n << endl; //cout << k << " dif: " << dif << endl; } } } } } cout << ret[0] << " " << ret[1] << endl << flush; return ret; } };
[ "cfyuen.trevor@gmail.com" ]
cfyuen.trevor@gmail.com
b37ea5c210332b363d98082e4c29cc8683843919
c3f715589f5d83e3ba92baaa309414eb253ca962
/C++/round-5/0901-1000/0961-0980/0973.h
605479a6b99d6708ea7b4a6a922e092f55dd8b3c
[]
no_license
kophy/Leetcode
4b22272de78c213c4ad42c488df6cffa3b8ba785
7763dc71fd2f34b28d5e006a1824ca7157cec224
refs/heads/master
2021-06-11T05:06:41.144210
2021-03-09T08:25:15
2021-03-09T08:25:15
62,117,739
13
1
null
null
null
null
UTF-8
C++
false
false
979
h
class Solution { public: vector<vector<int>> kClosest(vector<vector<int>> &points, int K) { auto cmp = [](const pair<long, int> &a, const pair<long, int> &b) -> bool { return a.first < b.first; }; std::priority_queue<pair<long, int>, std::vector<pair<long, int>>, decltype(cmp)> k_closest_points(cmp); for (int i = 0; i < points.size(); ++i) { const auto &point = points[i]; long distance = pow(point[0], 2) + pow(point[1], 2); if (k_closest_points.size() < K) { k_closest_points.push(std::make_pair(distance, i)); } else if (distance < k_closest_points.top().first) { k_closest_points.pop(); k_closest_points.push(std::make_pair(distance, i)); } } vector<vector<int>> result; for (int i = 0; i < K; ++i) { int index = k_closest_points.top().second; k_closest_points.pop(); result.push_back(points[index]); } return result; } };
[ "kophy@protonmail.com" ]
kophy@protonmail.com
d701caea4e51c316ba351dea8b54ab44e04fa25e
a35a1881a0967d86ef45e6098cd4897b7d4fc23a
/pooD-old/Conjunto.h
6af557338ebd85963e9f446f0394381850936add
[]
no_license
gabrielquiroga/POO---Integrador
f92e2de3ce88eba4d7c2dfabfd4c7b07cbf442a4
c59da453dc9cd6bdafd93c67f704519b85c5b25c
refs/heads/master
2020-04-02T10:42:18.140377
2018-11-12T00:52:33
2018-11-12T00:52:33
154,350,833
0
0
null
null
null
null
UTF-8
C++
false
false
855
h
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Conjunto.h * Author: gabrielq * * Created on 30 de septiembre de 2018, 20:46 */ #ifndef CONJUNTO_H #define CONJUNTO_H #include <iostream> using namespace std; #include <string> class Conjunto { public: string get_tipoPieza(); void set_tipoPieza(string nueva_pieza); string get_identificacion(); void set_identificacion(string nueva_identificacion); string get_descripcion(); void set_descripcion(string nueva_descripcion); float get_peso(); void set_peso(float nuevo_peso); private: string tipoPieza; string identificacion; string descripcion; float peso; }; #endif /* CONJUNTO_H */
[ "quiroga.m.gabriel@gmail.com" ]
quiroga.m.gabriel@gmail.com
904d2d657d93cf07d727b1813fd20bda69955946
d14161f95b20957c48ff34d66787de8c472b0c57
/Project3/assignment_data_download.cpp
c811e79facdc9d24d967f9ccef110604453678cf
[]
no_license
leoleil/qi_zhi_ji
0d6250315fdc7fa9d3591c7789530b52146eab26
2909c9d9f61e8089ec9ed0fd068b33decf414c01
refs/heads/master
2020-07-01T20:58:34.357830
2019-08-16T05:30:57
2019-08-16T05:30:57
201,299,086
1
0
null
null
null
null
GB18030
C++
false
false
6,961
cpp
#include "assignment_data_download.h" DWORD downdata(LPVOID lpParameter) { //数据库连接关键字 const char * SERVER = MYSQL_SERVER.data(); const char * USERNAME = MYSQL_USERNAME.data(); const char * PASSWORD = MYSQL_PASSWORD.data(); const char DATABASE[20] = "qian_zhi_ji"; const int PORT = 3306; while (1) { //5秒监测数据库的任务分配表 Sleep(5000); //cout << "| 数据下行 | 监测数据库分配表..." << endl; MySQLInterface mysql;//申请数据库连接对象 //连接数据库 if (mysql.connectMySQL(SERVER, USERNAME, PASSWORD, DATABASE, PORT)) { //从数据中获取分配任务 //寻找分发标志为2,数据分发标志为0的任务 string selectSql = "select 主键,任务编号,无人机编号 from 数据下行更新表"; vector<vector<string>> dataSet; mysql.getDatafromDB(selectSql, dataSet); if (dataSet.size() == 0) { continue;//无任务静默5秒后继续查询 } //查询到任务 for (int i = 0, len = dataSet.size(); i < len; i++) { char* messageDate; int messageDataSize = 0; //数据下行任务 StringNumUtils util;//字符转数字工具 long long dateTime = Message::getSystemTime();//获取当前时间戳 bool encrypt = false;//是否加密 UINT32 taskNum = util.stringToNum<UINT32>(dataSet[i][1]);//任务编号 string ackSql = ""; char* uavId = new char[20];//无人机编号 strcpy_s(uavId, dataSet[i][2].size() + 1, dataSet[i][2].c_str()); //查找地面站ip地址发送报文 string groundStationSql = "select IP地址 from 服务器信息表"; vector<vector<string>> ipSet; mysql.getDatafromDB(groundStationSql, ipSet); if (ipSet.size() == 0) { delete uavId; break;//没有找到ip地址 } MySQLInterface diskMysql; if (!diskMysql.connectMySQL(SERVER, USERNAME, PASSWORD, "disk", PORT)) { cout << "| 数据下行 | 连接数据库失败" << endl; cout << "| 数据下行错误信息 | " << diskMysql.errorNum << endl; break; } vector<vector<string>> disk; diskMysql.getDatafromDB("SELECT * FROM disk.存盘位置;", disk); if (disk.size() == 0) { mysql.writeDataToDB("INSERT INTO 系统日志表(时间,模块,事件) VALUES (now(),'数据下行','存盘位置未知');"); cout << "| 数据下行 | 存盘位置未知,请在数据库设置。" << endl; mysql.writeDataToDB(ackSql); //创建不成功释放资源 break;; } string path = disk[0][1]; path = path + "\\下行传输数据\\" + dataSet[i][2]; vector<string> files;//要上传的文件 // 文件句柄 //long hFile = 0; //win7 intptr_t hFile = 0; //win10 // 文件信息 struct _finddata_t fileinfo; string p; if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) { do { if ((strcmp(fileinfo.name, ".") != 0) && (strcmp(fileinfo.name, "..") != 0)) { // 保存文件的全路径 string s = ""; files.push_back(s.append(fileinfo.name)); } } while (_findnext(hFile, &fileinfo) == 0); //寻找下一个,成功返回0,否则-1 _findclose(hFile); } if (files.size() == 0) { mysql.writeDataToDB("INSERT INTO 系统日志表(时间,模块,事件) VALUES (now(),'数据下行','无下行文件');"); cout << "| 数据下行 | "; cout << path << " 无下行文件" << endl; //创建不成功释放资源 delete uavId; break;; } int pos = files[0].find_last_of('.'); string fileName(files[0].substr(0,pos));//文件名 string expandName(files[0].substr(pos));//扩展名 string file = path.append("\\").append(files[0]); ifstream fileIs(file, ios::binary | ios::in); if (!fileIs.is_open()) { mysql.writeDataToDB("INSERT INTO 系统日志表(时间,模块,事件) VALUES (now(),'数据下行','下行文件无法打开');"); cout << "| 数据下行 | "; cout << file << " 无法打开" << endl; //创建不成功释放资源 delete uavId; break;; } //创建发送者 Socket socketer; const char* ip = ipSet[0][0].c_str();//获取到地址 //建立TCP连接 if (!socketer.createSendServer(ip, 4997, 0)) { //创建不成功释放资源 delete uavId; break; } cout << "| 数据下行 | "; //读取文件 while (!fileIs.eof()) { int bufLen = 1024 * 64;//数据最大64K char* fileDataBuf = new char[bufLen];//64K fileIs.read(fileDataBuf, bufLen); bufLen = fileIs.gcount();//获取实际读取数据大小 char* up_file_name = new char[32];//文件名 strcpy_s(up_file_name, fileName.size() + 1, fileName.c_str()); char* up_expand_name = new char[8];//拓展名 strcpy_s(up_expand_name, expandName.size() + 1, expandName.c_str()); bool endFlag = fileIs.eof();//文件尾判断 //创建数据上行包 DownMessage downMessage(3020, dateTime, encrypt, taskNum, up_file_name, up_expand_name, endFlag); downMessage.setterData(fileDataBuf, bufLen);//传入数据 const int bufSize = 66560;//发送包固定65k int returnSize = 0; char* sendBuf = new char[bufSize];//申请发送buf ZeroMemory(sendBuf, bufSize);//清空发送空间 downMessage.createMessage(sendBuf, returnSize, bufSize);//创建传输字节包 Sleep(10); if (socketer.sendMessage(sendBuf, bufSize) == -1) {//发送包固定65k //发送失败释放资源跳出文件读写 mysql.writeDataToDB("INSERT INTO 系统日志表(时间,模块,事件) VALUES (now(),'数据下行','发送失败,断开连接');"); cout << "| 数据下行 | 发送失败,断开连接" << endl; delete sendBuf; delete up_expand_name; delete up_file_name; delete fileDataBuf; fileIs.close(); break; } cout << ">"; if (fileIs.eof() == true) { cout << endl; cout << "| 数据下行 | " << dataSet[i][1] << "号任务下行成功" << endl; mysql.writeDataToDB("INSERT INTO 系统日志表(时间,模块,事件) VALUES (now(),'数据下行','发送成功断开连接');"); //修改数据库分发标志 ackSql = "delete from 数据下行更新表 where 主键 = " + dataSet[i][0]; mysql.writeDataToDB(ackSql); fileIs.close(); remove(file.c_str()); } delete sendBuf; delete up_expand_name; delete up_file_name; delete fileDataBuf; } fileIs.close(); //断开TCP socketer.offSendServer(); delete uavId; Sleep(3000); } mysql.closeMySQL(); } else { cout << "| 数据下行 | 连接数据库失败" << endl; cout << "| 数据下行错误信息 | " << mysql.errorNum << endl; } cout << "| 数据下行 | 任务结束" << endl; } return 0; }
[ "leoleil@163.com" ]
leoleil@163.com
6a38dd57e823018022d4a684fe742d5819642744
ecdbce0a06430f11c3d9ba85ddea60075c335036
/src/Client/src/member.cpp
0565f28d7119fda55b90b3da9f705fddbd39a23a
[]
no_license
geekhsy/online-forum
66271d0a87793fe7b36a85f990a493c0665b45ee
1c7d01fa10a5b3685724d250e45fdb055815a064
refs/heads/master
2020-11-27T09:49:27.836985
2019-12-21T07:43:50
2019-12-21T07:43:50
229,387,985
1
0
null
null
null
null
UTF-8
C++
false
false
659
cpp
#include "member.h" #include "user.h" #include "forum.h" #include "Socket.h" Member::Member(QString id, QString username, QString password, int type) : User(id,username,password,type){} bool Member::deletePost(QString id, QString board) { if(!Forum::getInstance()->switchBoard(board)){ return false; } QStringList info = Socket::getInstance()->getPostInfo(id); if(info.size() == 0 ||info.at(4) != board){ return false; } QString authorId = info.at(3); if(authorId.length() == 0 || authorId != this->getId()){ return false; } return Forum::getInstance()->getCurrentBoard()->deletePost(id); }
[ "1402543398@qq.com" ]
1402543398@qq.com
01b332e04338e35a93b44b92e8b1613bfbbf1370
e780ac4efed690d0671c9e25df3e9732a32a14f5
/RaiderEngine/libs/PhysX-4.1/physx/source/pvd/src/PxProfileEventBufferClientManager.h
ed870d746f0264c917053cb41279c963acedb482
[ "MIT" ]
permissive
rystills/RaiderEngine
fbe943143b48f4de540843440bd4fcd2a858606a
3fe2dcdad6041e839e1bad3632ef4b5e592a47fb
refs/heads/master
2022-06-16T20:35:52.785407
2022-06-11T00:51:40
2022-06-11T00:51:40
184,037,276
6
0
MIT
2022-05-07T06:00:35
2019-04-29T09:05:20
C++
UTF-8
C++
false
false
3,087
h
// // 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 NVIDIA CORPORATION 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 ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved. #ifndef PXPVDSDK_PXPROFILEEVENTBUFFERCLIENTMANAGER_H #define PXPVDSDK_PXPROFILEEVENTBUFFERCLIENTMANAGER_H #include "PxProfileEventBufferClient.h" namespace physx { namespace profile { /** \brief Manager keep collections of PxProfileEventBufferClient clients. @see PxProfileEventBufferClient */ class PxProfileEventBufferClientManager { protected: virtual ~PxProfileEventBufferClientManager(){} public: /** \brief Adds new client. \param inClient Client to add. */ virtual void addClient( PxProfileEventBufferClient& inClient ) = 0; /** \brief Removes a client. \param inClient Client to remove. */ virtual void removeClient( PxProfileEventBufferClient& inClient ) = 0; /** \brief Check if manager has clients. \return True if manager has added clients. */ virtual bool hasClients() const = 0; }; /** \brief Manager keep collections of PxProfileZoneClient clients. @see PxProfileZoneClient */ class PxProfileZoneClientManager { protected: virtual ~PxProfileZoneClientManager(){} public: /** \brief Adds new client. \param inClient Client to add. */ virtual void addClient( PxProfileZoneClient& inClient ) = 0; /** \brief Removes a client. \param inClient Client to remove. */ virtual void removeClient( PxProfileZoneClient& inClient ) = 0; /** \brief Check if manager has clients. \return True if manager has added clients. */ virtual bool hasClients() const = 0; }; } } #endif // PXPVDSDK_PXPROFILEEVENTBUFFERCLIENTMANAGER_H
[ "rystills@gmail.com" ]
rystills@gmail.com
a76538195aebd2acbbaaf6a81271463ce51ac32b
16a6d102a1a63717f274b4e13ddc14ad8324a908
/Contests/Codeforces Round 678/A.cpp
1e6d342668f78bac305ae88c76bd7fd6eed22ff9
[]
no_license
jomorales1/Competitive-Programming
0f284dd96132939eed2497416d5ba3c589ea6c85
a7972b5210fa803eab0213ef1182deae68ebc300
refs/heads/master
2023-03-12T01:36:48.344862
2021-03-03T20:24:20
2021-03-03T20:24:20
286,822,924
0
1
null
null
null
null
UTF-8
C++
false
false
485
cpp
#include <bits/stdc++.h> using namespace std; void solve() { int n = 0; long long m; cin >> n >> m; vector<int> a(n); long long sum = 0LL; for (int i = 0; i < n; i++) { cin >> a[i]; sum += a[i]; } if (sum == m) { cout << "YES\n"; } else { cout << "NO\n"; } } int main() { ios::sync_with_stdio(0), cin.tie(0); int t = 0; cin >> t; for (int i = 0; i < t; i++) { solve(); } return 0; }
[ "manriquem1901@gmail.com" ]
manriquem1901@gmail.com
aa2e9989bde007d960b649f6c488f3c3b8799d16
bde38b97498bb7b9233716db8f565a8caf4cb825
/scanner.cpp
94d233b2db4ba8e902016b9034d7aa9c95b3a934
[]
no_license
BrejeMihai/FLCD-labFinal
02e78c3d49b18f2b10e914d17658b50702bf764b
399e282f68c15c229cce52e95f2f91f0ddb3c03b
refs/heads/main
2023-01-05T16:34:40.861085
2020-10-28T10:22:36
2020-10-28T10:22:36
307,979,254
0
0
null
null
null
null
UTF-8
C++
false
false
5,603
cpp
#include "scanner.h" #include "node.h" #include <string> #include <fstream> #include <vector> #include <sstream> #include <map> #include <regex> #include <iostream> bool SplitTokenRead(std::string Token, std::string fileLine, int numberOfLines, std::vector<std::pair<std::string, std::pair<int, int>>>& tokenList) { bool check = false; std::regex e("([\\(\\)\\{\\},~\\[\\]:!=])|([^\\(\\)\\{\\},~\\[\\]:!=]+)"); std::regex_iterator<std::string::iterator> rit(Token.begin(), Token.end(), e); std::regex_iterator<std::string::iterator> rend; while (rit != rend) { size_t found = fileLine.find(rit->str()); tokenList.push_back(std::pair<std::string, std::pair<int, int>>(rit->str(), std::pair<int, int>(numberOfLines, found))); ++rit; check = true; } return check; } bool IsSeparatorOrOperator(std::string Token) { const char* arr[] = { "!", "[", "]", "(", ")", "{", "}", " ", ":", ";", ",", "~", "+", "-", "*", "/", "^", "=" }; for (auto c : arr) { if (0 == Token.compare(c)) { return true; } } return false; } bool IsReservedWord(std::string Token) { const char* arr[] = { "int", "char", "string", "listof", "incase", "ifnot", "then", "gountil", "do", "input", "echo", "lt", "lte", "equals", "ne", "gt", "gte", "increment", "decrement" }; for (auto c : arr) { if (0 == Token.compare(c)) { return true; } } return false; } bool CheckIfExpression(std::string Token) { std::regex e("^-*[1-9][0-9]*[\\+\\*/-]-*[1-9][0-9]*$"); std::regex_iterator<std::string::iterator> rit(Token.begin(), Token.end(), e); std::regex_iterator<std::string::iterator> rend; return !(rit == rend); } bool CheckIfProperNumericalValue(std::string Token) { std::regex e("^-*[1-9][0-9]*$"); std::regex_iterator<std::string::iterator> rit(Token.begin(), Token.end(), e); std::regex_iterator<std::string::iterator> rend; return !(rit == rend); } bool CheckIfProperIdentifier(std::string Token) { std::regex e("^[a-zA-Z][0-9a-zA-Z]*$"); std::regex_iterator<std::string::iterator> rit(Token.begin(), Token.end(), e); std::regex_iterator<std::string::iterator> rend; return !(rit == rend); } bool CheckIfConstChar(std::string Token) { std::regex e("^\'.\'$"); std::regex_iterator<std::string::iterator> rit(Token.begin(), Token.end(), e); std::regex_iterator<std::string::iterator> rend; return !(rit == rend); } bool CheckIfConstString(std::string Token) { std::regex e("^\".*\"$"); std::regex_iterator<std::string::iterator> rit(Token.begin(), Token.end(), e); std::regex_iterator<std::string::iterator> rend; return !(rit == rend); } bool CheckIfConst(std::string Token) { return CheckIfProperNumericalValue(Token) | CheckIfConstString(Token) | CheckIfConstChar(Token) | CheckIfExpression(Token); } bool CheckIfIdentifier(std::string Token) { return CheckIfProperIdentifier(Token); } void StartScanning(char* InputFilePath) { std::vector<std::pair<std::string, std::pair<int, int>>> tokenList; std::string inputPath = InputFilePath; std::vector<std::pair<std::string, int>> pif; std::vector<std::string> listOfTokens; std::string token; std::string fileLine; int numberOfLines = 1; std::string stoutput; std::ifstream inputFile(inputPath); std::ofstream piffile("./PIF.out"); std::ofstream stfile("./ST.out"); HashTable hashTable; while (std::getline(inputFile, fileLine)) { std::istringstream iss(fileLine); while (iss >> token) { if (!(SplitTokenRead(token, fileLine, numberOfLines, tokenList))) { size_t found = fileLine.find(token); tokenList.push_back(std::pair<std::string, std::pair<int, int>>(token, std::pair<int, int>(numberOfLines, found))); } } numberOfLines++; } for (std::pair<std::string, std::pair<int,int>> singleTokenPair : tokenList) { if (IsReservedWord(singleTokenPair.first) || IsSeparatorOrOperator(singleTokenPair.first)) { pif.push_back(std::pair<std::string,int>(singleTokenPair.first,-1)); } else { if (CheckIfIdentifier(singleTokenPair.first)) { hashTable.insertNode(singleTokenPair.first); pif.push_back(std::pair<std::string, int>("0", hashTable.getPosition(singleTokenPair.first))); } else if (CheckIfConst(singleTokenPair.first)) { hashTable.insertNode(singleTokenPair.first); pif.push_back(std::pair<std::string, int>("1", hashTable.getPosition(singleTokenPair.first))); } else { fprintf_s(stderr, "LEXICAL ERROR\nLine %d, column %d\n", singleTokenPair.second.first, singleTokenPair.second.second); return; } } } fprintf_s(stdout, "Lexically correct!\n"); piffile << "PIF\n"; for (auto c : pif) { piffile << c.first << " " << c.second << std::endl; } stoutput = hashTable.displayToString(); stfile << "Symbol Table\n"; stfile << stoutput; piffile.flush(); piffile.close(); stfile.flush(); stfile.close(); }
[ "brejemihaipaul@gmail.com" ]
brejemihaipaul@gmail.com
af14c82b69da5b0a33ab30ac78014f2f919e35df
012784e8de35581e1929306503439bb355be4c4f
/problems/654/n1.cc
ee7b1e17bc9d94046f665af9c00d63b6348cf599
[]
no_license
silenke/my-leetcode
7502057c9394e41ddeb2e7fd6c1b8261661639e0
d24ef0970785c547709b1d3c7228e7d8b98b1f06
refs/heads/master
2023-06-05T02:05:48.674311
2021-07-01T16:18:29
2021-07-01T16:18:29
331,948,127
0
0
null
null
null
null
UTF-8
C++
false
false
1,079
cc
#include "..\..\leetcode.h" /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* constructMaximumBinaryTree(vector<int>& nums) { stack<TreeNode*> s; for (int n : nums) { TreeNode* curr = new TreeNode(n); while (!s.empty() && s.top()->val < n) { TreeNode* top = s.top(); s.pop(); if (s.empty() || s.top()->val > n) { curr->left = top; } else { s.top()->right = top; } } s.emplace(curr); } while (s.size() > 1) { TreeNode* top = s.top(); s.pop(); s.top()->right = top; } return s.top(); } };
[ "2595756713@qq.com" ]
2595756713@qq.com
4f08ef4da8792269cff078f2d7f598ef945bb7f1
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/ClickHouse/2015/12/TableFunctionFactory.cpp
f1df2cd4194e991685a67fbb0798210d72dc86f1
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
701
cpp
#include <DB/TableFunctions/TableFunctionMerge.h> #include <DB/TableFunctions/TableFunctionRemote.h> #include <DB/TableFunctions/TableFunctionFactory.h> namespace DB { TableFunctionPtr TableFunctionFactory::get( const String & name, const Context & context) const { if (context.getSettings().limits.readonly == 1) /** Например, для readonly = 2 - разрешено. */ throw Exception("Table functions are forbidden in readonly mode", ErrorCodes::READONLY); if (name == "merge") return new TableFunctionMerge; else if (name == "remote") return new TableFunctionRemote; else throw Exception("Unknown table function " + name, ErrorCodes::UNKNOWN_FUNCTION); } }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
76618c192e087408857673de98b5b3bd0c3723da
83f05babe32ee1188f7f8b72e2cb7192f854d9c8
/heap(Priorty Queue)/min_heap/min_heap.cpp
4b3cde37c2d3b637bd727b50de10ef272adca36d
[]
no_license
Jimin9401/Data_Structures
45765be32530c493a2f41e55140e88dd66e0998b
08af5d634fc1931ba44a9f012305064f9454bf3b
refs/heads/master
2020-04-28T18:08:06.617769
2019-05-08T02:49:24
2019-05-08T02:49:24
175,469,091
0
0
null
null
null
null
UTF-8
C++
false
false
1,954
cpp
#define _CRT_SECURE_NO_WARNINGS #define max_size (129) #include <stdio.h> #include<stdlib.h> #include<string.h> typedef int element; typedef struct heap { element data[max_size] = { INT_MAX }; element key; }heap; heap *create() { heap *tmp; tmp = (heap*)malloc(sizeof(heap)); tmp->key = 0; return tmp; } void push(heap *arr, element value) { arr->key++; element i = arr->key; arr->data[arr->key] = value; element tmp; while ((i/2 != 0) && (arr->data[i] < arr->data[i / 2])) { tmp = arr->data[i]; arr->data[i] = arr->data[i / 2]; arr->data[i / 2] = tmp; i /= 2; } } element pop(heap *arr) { element pop_value; pop_value = arr->data[1]; arr->data[1] = arr->data[arr->key]; arr->key--; element i = 1; element tmp; while ((arr->data[i] > arr->data[i * 2]) || (arr->data[i] > arr->data[i * 2 + 1])) { if (i * 2 <= arr->key && arr->data[i * 2] < arr->data[i * 2 + 1]) { tmp = arr->data[i]; arr->data[i] = arr->data[i * 2]; arr->data[i * 2] = tmp; i *= 2; } else if (i * 2 + 1 <= arr->key && arr->data[i * 2] >= arr->data[i * 2 + 1]) { tmp = arr->data[i]; arr->data[i] = arr->data[i * 2 + 1]; arr->data[i * 2 + 1] = tmp; i = i * 2 + 1; } else { break; } } return pop_value; } void print(heap *arr) { for (int i = 1; i <= arr->key; i++) { printf("%d ", arr->data[i]); } printf("\n"); } void sort(heap *arr) { heap *a = arr; element k = a->key; for (int i = 0; i < k; i++) { printf("%d ", pop(a)); } printf("\n"); } int main() { char command[20]; heap *heapnode; heapnode = create(); element value; while (1) { scanf("%s", command); if (strcmp(command, "push") == 0) { scanf("%d", &value); push(heapnode, value); } else if (strcmp(command, "print") == 0) { print(heapnode); } else if (strcmp(command, "pop") == 0) { printf("%d\n", pop(heapnode)); } else if (strcmp(command, "sort") == 0) { sort(heapnode); } } return 0; }
[ "su010331@naver.com" ]
su010331@naver.com
d3e3a62304f97a3153937e12c952356e48be4937
5137216db087c50aed394248cb6d10e1cf43b29c
/original/love2d072/src/modules/physics/box2d/wrap_DistanceJoint.h
63525791f11fdeeb4c8f56b679ddcd8fa6cb63a8
[ "Zlib" ]
permissive
shuhaowu/nottetris2
0dc4ecae52bb58442293b35d44fe072c5c61c73e
8a8e7fc3bbbe4e724fa6eb64c27011a0b6e1b089
refs/heads/master
2020-05-04T06:25:22.064594
2019-04-04T02:26:08
2019-04-04T02:26:08
179,005,443
0
0
WTFPL
2019-04-02T05:30:51
2019-04-02T05:30:50
null
UTF-8
C++
false
false
1,695
h
/** * Copyright (c) 2006-2011 LOVE Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. **/ #ifndef LOVE_PHYSICS_BOX2D_WRAP_DISTANCE_JOINT_H #define LOVE_PHYSICS_BOX2D_WRAP_DISTANCE_JOINT_H // LOVE #include <common/runtime.h> #include "wrap_Joint.h" #include "DistanceJoint.h" namespace love { namespace physics { namespace box2d { DistanceJoint * luax_checkdistancejoint(lua_State * L, int idx); int w_DistanceJoint_setLength(lua_State * L); int w_DistanceJoint_getLength(lua_State * L); int w_DistanceJoint_setFrequency(lua_State * L); int w_DistanceJoint_getFrequency(lua_State * L); int w_DistanceJoint_setDampingRatio(lua_State * L); int w_DistanceJoint_getDampingRatio(lua_State * L); int luaopen_distancejoint(lua_State * L); } // box2d } // physics } // love #endif // LOVE_PHYSICS_BOX2D_WRAP_DISTANCE_JOINT_H
[ "shuhao@shuhaowu.com" ]
shuhao@shuhaowu.com
0e8d0d661239b501f40c68151068a776c07a8562
fb69a4b90e3e1fd34860ecb360573d4fcf56150b
/include/mainComponents/customtableview.cpp
2554d692fa004b1a3fade4cdbf5ec959cc385a81
[]
no_license
ryera89/TideAnalisisPredictionSystem
40da629937ab9dbd7353e05f531ea0aa242e5736
2223446e9b48e741e5072664bbcc539f6953774f
refs/heads/master
2023-07-08T06:57:22.105956
2021-08-07T20:58:43
2021-08-07T20:58:43
393,788,977
1
0
null
null
null
null
UTF-8
C++
false
false
32
cpp
#include "customtableview.h"
[ "ryera@UDI.emarinos.geocuba.cu" ]
ryera@UDI.emarinos.geocuba.cu
50d9e9bb5b2c97341e6b3dce0f623350652c7611
213057bf491be349cc226383fb5cc9ef28b9ead7
/audiograbber.cpp
651d13a782483fe54c5de3f2cbd8fe2d236a3256
[]
no_license
ffkirill/vk_audios
5f9ab1508b93519c67df5a0c2a14f8b23acf6cb6
203e86fdce0a3ea50a03c6bf0960b1855fa1b817
refs/heads/master
2021-01-10T11:27:42.079216
2015-12-14T12:01:14
2015-12-14T12:01:14
47,473,708
1
1
null
null
null
null
UTF-8
C++
false
false
1,017
cpp
#include "audiograbber.h" #include <QFile> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QDir> #include <QStandardPaths> #include <QDebug> AudioGrabber::AudioGrabber(QObject *parent) : QObject(parent) { connect(&m_networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); pathToSave = QDir( QDir(QStandardPaths::writableLocation(QStandardPaths::MusicLocation)) .filePath("vk_audios")); if (!pathToSave.exists()) { pathToSave.mkpath("."); } } void AudioGrabber::enqueueUrl(const QString &url) { m_networkManager.get(QNetworkRequest(url)); } void AudioGrabber::replyFinished(QNetworkReply *reply) { QFile file; file.setFileName(pathToSave .filePath(reply->request().url().fileName())); file.open(QIODevice::WriteOnly); if (file.isOpen() && file.isWritable()) { file.write(reply->readAll()); file.close(); } }
[ "ff.kirill@gmail.com" ]
ff.kirill@gmail.com
3c3a87b943e3ea5fd6204d6236a9ad2ddb067251
6c3944111d9332c7b89e6de40d7363a0d35b6d7b
/MMH7SDKGenerator/TFL_SdkGen.h
548c3051207067cebd50f34f09b8914d689fc43c
[]
no_license
LukaOo/Might-And-Magic-Heroes-VII-Mods
82de3a8f5cdf039671c8221ee6fb781fc2d96855
267ab3ab67ee96c6db76ed965e4fc5d14aa3caec
refs/heads/master
2021-01-21T02:02:57.194477
2018-11-10T15:26:51
2018-11-10T15:26:51
60,117,202
9
2
null
2018-08-20T21:20:25
2016-05-31T19:25:06
C++
UTF-8
C++
false
false
7,340
h
/* ############################################################################################# # TheFeckless UE3 SDK Generator v1.4_Beta-Rev.51 # ========================================================================================= # # File: TFL_SdkGen.h # ========================================================================================= # # Credits: uNrEaL, Tamimego, SystemFiles, R00T88, _silencer, the1domo, K@N@VEL # Thanks: HOOAH07, lowHertz # Forums: www.uc-forum.com, www.gamedeception.net # ========================================================================================= # # This work is licensed under the # Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. # To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ # or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, # California, 94041, USA. ############################################################################################# */ #include <Windows.h> #include <stdio.h> #include <direct.h> #include <iostream> #include <sstream> #include <iomanip> #include <string> #include <vector> #include <map> #include <algorithm> #include "TFL_HT.h" using namespace std; /* # ========================================================================================= # # Game Specific Includes (UE3 Basic Core) # ========================================================================================= # */ // America's Army 3 //#include "UE3BasicCore\AA3\GameDefines.h" //#include "UE3BasicCore\AA3\ObjectFunctions.h" //#include "UE3BasicCore\AA3\PiecesOfCode.h" // All Points Bulletin Reloaded //#include "UE3BasicCore\APB\GameDefines.h" //#include "UE3BasicCore\APB\ObjectFunctions.h" //#include "UE3BasicCore\APB\PiecesOfCode.h" // Tom Clancy's Rainbow Six Vegas 2 //#include "UE3BasicCore\R6V2\GameDefines.h" //#include "UE3BasicCore\R6V2\ObjectFunctions.h" //#include "UE3BasicCore\R6v2\PiecesOfCode.h" // Red Orchestra 2: Heroes of Stalingrad //#include "UE3BasicCore\RO2\GameDefines.h" //#include "UE3BasicCore\RO2\ObjectFunctions.h" //#include "UE3BasicCore\RO2\PiecesOfCode.h" // Blacklight: Retribution //#include "UE3BasicCore\BLR\GameDefines.h" //#include "UE3BasicCore\BLR\ObjectFunctions.h" //#include "UE3BasicCore\BLR\PiecesOfCode.h" // Mass Effect 3 //#include "UE3BasicCore\ME3\GameDefines.h" //#include "UE3BasicCore\ME3\ObjectFunctions.h" //#include "UE3BasicCore\ME3\PiecesOfCode.h" // Super Monday Night Combat #include "GameIncludes\GameDefines.h" #include "GameIncludes\ObjectFunctions.h" #include "GameIncludes\PiecesOfCode.h" /* # ========================================================================================= # # Defines # ========================================================================================= # */ // Generator #define SDK_GEN_VER "v1.4_Beta-Rev.51 x64" #define SDK_GEN_CREDITS "uNrEaL, Tamimego, SystemFiles, R00T88, _silencer, the1domo, K@N@VEL" #define SDK_GEN_FORUMS "www.uc-forum.com, www.gamedeception.net" #define SDK_GEN_STHANKS "HOOAH07, lowHertz" #define SDK_BASE_DIR "C:\\Users\\Dima\\Documents\\GitHub\\Might-And-Magic-Heroes-VII-Mods\\v1.8" #define SDK_BUFF_SIZE 256 #define SDK_COL1 50 #define SDK_COL2 50 #define SDK_NO_STR true /* # ========================================================================================= # # Define Macros # ========================================================================================= # */ #define SDKFN_PRINT( file, stream ) fprintf ( file, "%s", stream.str().c_str() ); stream.str ( string() ); #define SDKFN_EMPTY( stream ) stream.str ( string() ); #define SDKMC_SSDEC( value, width ) dec << setfill ( '0' ) << setw ( width ) << right << value #define SDKMC_SSHEX( value, width ) "0x" << hex << uppercase << setfill ( '0' ) << setw ( width ) << right << value << nouppercase #define SDKMC_SSCOL( string, width ) setfill ( ' ' ) << setw ( width ) << left << string /* # ========================================================================================= # # Typedefs # ========================================================================================= # */ typedef map< string, unsigned int > StrIntM_t; typedef multimap< string, string > StrStrMm_t; typedef pair< string, string > StrStrPair_t; /* # ========================================================================================= # # Globals # ========================================================================================= # */ FILE* pFile = NULL; FILE* pLog = NULL; char cBuffer[ SDK_BUFF_SIZE ] = { NULL }; vector< UObject* > vIncludes; /* # ========================================================================================= # # Functions # ========================================================================================= # */ // DllMain void OnAttach (); // Initialization void Init_Core (); // Finalization void Final_SdkHeaders (); // Process Objects by Package void ProcessPackages (); void ProcessScriptStructsByPackage ( UObject* pPackageToProcess ); void ProcessConstsByPackage ( UObject* pPackageToProcess ); void ProcessEnumsByPackage ( UObject* pPackageToProcess ); void ProcessClassesByPackage ( UObject* pPackageToProcess ); void ProcessFuncStructsByPackage ( UObject* pPackageToProcess ); void ProcessFuncsByPackage ( UObject* pPackageToProcess ); // Generate Code void GenerateConst ( UConst* pConst ); void GenerateEnum ( UEnum* pEnum ); void GenerateScriptStruct ( UScriptStruct* pScriptStruct ); void GenerateScriptStructPre ( UScriptStruct* pScriptStruct, UObject* pPackageToProcess ); void GenerateFuncStruct ( UClass* pClass ); void GenerateFuncDef ( UClass* pClass ); void GenerateFuncDec ( UClass* pClass ); void GenerateVirtualFunc ( UClass* pClass ); void GenerateClass ( UClass* pClass ); void GenerateClassPre ( UClass* pClass, UObject* pPackageToProcess ); // object utils UScriptStruct* FindBiggestScriptStruct ( string ScriptStructFullName ); // Property Utils int GetPropertyType ( UProperty* pProperty, string& sPropertyType, bool bFuncRet ); unsigned long GetPropertySize ( UProperty* pProperty ); bool SortProperty ( UProperty* pPropertyA, UProperty* pPropertyB ); bool SortPropertyPair ( pair< UProperty*, string > pPropertyA, pair< UProperty*, string > pPropertyB ); // String Utils string GetValidName ( const string& sName ); string ToS ( const wchar_t* wcOrig ); string ToS ( const char* cOrig ); bool StrStrMm_Exist ( const StrStrMm_t& StrStrMm, string sKey, string sValue ); // Print Code void PrintFileHeder ( char* cFileName, char* cFileExt, bool setPP ); void PrintFileFooter (); void PrintSectionHeader ( char* cSectionName ); // Generate Flags void GetAllPropertyFlags ( int PropertyFlags, ostringstream& ssStreamBuffer ); void GetAllFunctionFlags ( unsigned long FunctionFlags, ostringstream& ssStreamBuffer );
[ "dvsoloviev@gmail.com" ]
dvsoloviev@gmail.com
d24514a6e9c396cf4110918db10120b8bed8e1b9
798b1e4455aa8d12700426ada63487fb568d4bc4
/Contests/CodeForces 710 div3/C_Double_ended_Strings.cpp
9f65e49a825f5cb499bb1cfb994b3ca7e718577f
[]
no_license
Kowsihan-sk/Codeforces-Solutions
0138d07a09b928c3c56085d9341505b52c5c8809
0ee9e0c6c5d4f10d3bf63917849600420a1f9ce0
refs/heads/master
2023-06-19T15:30:16.174939
2021-07-21T12:37:12
2021-07-21T12:37:12
269,496,651
0
0
null
null
null
null
UTF-8
C++
false
false
2,622
cpp
/** Author : S Kowsihan **/ #include <bits/stdc++.h> using namespace std; #define fast \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); #define ll long long #define endl "\n" #define f(a, b, c) for (ll i = a; i < b; i += c) #define fo(i, a, b, c) for (ll i = a; i < b; i += c) #define fd(a, b, c) for (ll i = a; i >= b; i -= c) #define fdo(i, a, b, c) for (ll i = a; i >= b; i -= c) #define Size(n) ((int)(n).size()) #define all(n) (n).begin(), (n).end() typedef vector<ll> vl; typedef vector<vl> vll; #define pb push_back #define ff first #define ss second #define mp make_pair typedef pair<int, int> pii; typedef pair<ll, ll> pll; const int mod = 1e9 + 7; const int N = (int)2 * 1e5 + 10; // ll lcs(string a, string b, ll i, ll j, ll count) // { // if (i == 0 || j == 0) // return count; // if (a[i - 1] == b[j - 1]) // { // count = lcs(a, b, i - 1, j - 1, count + 1); // } // count = max(count, // max(lcs(a, b, i, j - 1, 0), // lcs(a, b, i - 1, j, 0))); // return count; // } ll LCS(string X, string Y, int m, int n) { int maxlen = 0; // stores the max length of LCS int endingIndex = m; // stores the ending index of LCS in `X` // `lookup[i][j]` stores the length of LCS of substring // `X[0…i-1]`, `Y[0…j-1]` int lookup[m + 1][n + 1]; // initialize all cells of the lookup table to 0 memset(lookup, 0, sizeof(lookup)); // fill the lookup table in a bottom-up manner for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { // if the current character of `X` and `Y` matches if (X[i - 1] == Y[j - 1]) { lookup[i][j] = lookup[i - 1][j - 1] + 1; // update the maximum length and ending index if (lookup[i][j] > maxlen) { maxlen = lookup[i][j]; endingIndex = i; } } } } // return longest common substring having length `maxlen` return maxlen; } int main() { fast; ll TT; cin >> TT; while (TT--) { string a, b; cin >> a; cin >> b; ll n = a.size(), m = b.size(); cout << n << " " << m << endl; // ll ms = LCS(a, b, n, m); // ll fcount = a.size() - b.size() - 2 * ms; // cout << fcount << endl; } return 0; }
[ "kowsihan2sk@gmail.com" ]
kowsihan2sk@gmail.com
e9cbee93f469fd250225be2921bf4e691e07ce7e
f59da58345ef902710666756b8cb09011d130c7a
/FSM/FSM/Melee.h
d029379033e489f7fc01fbed62f5fc6de29e2c91
[]
no_license
JackDalton3110/GamesEngLabY4
09991507767693ede5c765ed06f53c4293446032
2116e762d47e888cc011e1112900eb97ff3abfd5
refs/heads/master
2020-03-29T16:00:53.972742
2019-03-14T10:04:08
2019-03-14T10:04:08
150,092,527
0
0
null
null
null
null
UTF-8
C++
false
false
161
h
#pragma once #include "Command.h" #include <iostream> class Melee : public Command { public: virtual void execute() { std::cout << "mellee" << std::endl; } };
[ "c00205943@itcarlow.ie" ]
c00205943@itcarlow.ie
20cae6d12857171297c6e5e642f4f0ad2be2824b
e7f41fc2faaeabad7d305d1f15e7a97f7480b849
/util/base.cc
f625a0b75d7070993d22e84ac4fbcea9ebe32c68
[]
no_license
wenruo95/cpp-study
c8ddde985d226f9eecc0a000600827a2d8695b9a
04f84578b1374194b47eaa888d1b2efbc7c40449
refs/heads/master
2020-03-22T03:51:00.492616
2019-12-24T13:56:02
2019-12-24T13:56:02
139,455,885
2
0
null
null
null
null
UTF-8
C++
false
false
104
cc
#include<iostream> /* template <class T> void swap(T &a, T &b) { T temp = b; b = a; a = temp; } */
[ "1358124684@qq.com" ]
1358124684@qq.com
2fd501c3c97093759957dd7ad3ed18bf98a24c3c
f10321225c4a09060235264b4f132e2682d4ef8a
/code/pat/1046_2.cpp
389c32a4ddc70b453c896428301a45e20c492a7f
[]
no_license
lawrencelulu/acm
a638fd57352913d8975fc4ee99cd9256afe64b6c
b896da2c6827e51c0ca4eeaeca7b0453b4d85c0a
refs/heads/master
2022-12-10T23:21:09.971369
2020-03-18T13:13:51
2020-03-18T13:13:51
165,783,752
1
0
null
2022-12-10T22:02:54
2019-01-15T04:11:46
HTML
UTF-8
C++
false
false
539
cpp
/* 甲喊,甲划,乙喊,乙划 规则:比划的数字等于两人喊出的数字之和, 谁就赢了,输家罚一杯酒。两人同赢或两人同输则继续下一轮,直到唯一的赢家出现 */ #include <cstdio> int main() { int N, a, da, b, db, cnta = 0, cntb = 0; scanf("%d", &N); for(int i = 0; i < N; i++){ scanf("%d %d %d %d", &a, &da, &b, &db); if(a + b == da && a + b != db) cntb++; if(a + b == db && a + b != da) cnta++; } printf("%d %d\n", cnta, cntb); return 0; }
[ "luhuijian@luhuijiandeMacBook-Air.local" ]
luhuijian@luhuijiandeMacBook-Air.local
2a925146172bf266062548f45c0af778e0f8541c
24f26275ffcd9324998d7570ea9fda82578eeb9e
/content/browser/tracing/memory_tracing_browsertest.cc
2f47e544084437dccdb71ead8ef82bb2f8d07c59
[ "BSD-3-Clause" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
14,661
cc
// Copyright 2015 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 <stdint.h> #include "base/bind.h" #include "base/callback_forward.h" #include "base/command_line.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/memory_dump_provider.h" #include "base/trace_event/memory_dump_request_args.h" #include "base/trace_event/trace_config_memory_test_util.h" #include "base/trace_event/trace_log.h" #include "build/build_config.h" #include "content/browser/tracing/tracing_controller_impl.h" #include "content/public/browser/tracing_controller.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/shell/browser/shell.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "testing/gmock/include/gmock/gmock.h" using base::trace_event::MemoryDumpArgs; using base::trace_event::MemoryDumpDeterminism; using base::trace_event::MemoryDumpLevelOfDetail; using base::trace_event::MemoryDumpManager; using base::trace_event::MemoryDumpType; using base::trace_event::ProcessMemoryDump; using testing::_; using testing::Return; namespace content { // A mock dump provider, used to check that dump requests actually end up // creating memory dumps. class MockDumpProvider : public base::trace_event::MemoryDumpProvider { public: MOCK_METHOD2(OnMemoryDump, bool(const MemoryDumpArgs& args, ProcessMemoryDump* pmd)); }; class MemoryTracingTest : public ContentBrowserTest { public: // Used as callback argument for MemoryDumpManager::RequestGlobalDump(): void OnGlobalMemoryDumpDone( scoped_refptr<base::SingleThreadTaskRunner> task_runner, base::Closure closure, uint32_t request_index, bool success, uint64_t dump_guid) { // Make sure we run the RunLoop closure on the same thread that originated // the run loop (which is the IN_PROC_BROWSER_TEST_F main thread). if (!task_runner->RunsTasksInCurrentSequence()) { task_runner->PostTask( FROM_HERE, base::BindOnce(&MemoryTracingTest::OnGlobalMemoryDumpDone, base::Unretained(this), task_runner, std::move(closure), request_index, success, dump_guid)); return; } if (success) EXPECT_NE(0u, dump_guid); OnMemoryDumpDone(request_index, success); if (!closure.is_null()) std::move(closure).Run(); } void RequestGlobalDumpWithClosure( bool from_renderer_thread, const MemoryDumpType& dump_type, const MemoryDumpLevelOfDetail& level_of_detail, const base::Closure& closure) { uint32_t request_index = next_request_index_++; auto callback = base::Bind( &MemoryTracingTest::OnGlobalMemoryDumpDone, base::Unretained(this), base::ThreadTaskRunnerHandle::Get(), closure, request_index); if (from_renderer_thread) { PostTaskToInProcessRendererAndWait(base::BindOnce( &memory_instrumentation::MemoryInstrumentation:: RequestGlobalDumpAndAppendToTrace, base::Unretained( memory_instrumentation::MemoryInstrumentation::GetInstance()), dump_type, level_of_detail, MemoryDumpDeterminism::NONE, std::move(callback))); } else { memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpAndAppendToTrace(dump_type, level_of_detail, MemoryDumpDeterminism::NONE, std::move(callback)); } } protected: void SetUp() override { next_request_index_ = 0; mock_dump_provider_.reset(new MockDumpProvider()); MemoryDumpManager::GetInstance()->RegisterDumpProvider( mock_dump_provider_.get(), "MockDumpProvider", nullptr); MemoryDumpManager::GetInstance() ->set_dumper_registrations_ignored_for_testing(false); ContentBrowserTest::SetUp(); } void TearDown() override { MemoryDumpManager::GetInstance()->UnregisterAndDeleteDumpProviderSoon( std::move(mock_dump_provider_)); mock_dump_provider_.reset(); ContentBrowserTest::TearDown(); } void EnableMemoryTracing() { // Re-enabling tracing could crash these tests https://crbug.com/657628 . if (base::trace_event::TraceLog::GetInstance()->IsEnabled()) { FAIL() << "Tracing seems to be already enabled. " "Very likely this is because the startup tracing file " "has been leaked from a previous test."; } // Enable tracing without periodic dumps. base::trace_event::TraceConfig trace_config( base::trace_event::TraceConfigMemoryTestUtil:: GetTraceConfig_EmptyTriggers()); base::RunLoop run_loop; bool success = TracingController::GetInstance()->StartTracing( trace_config, run_loop.QuitClosure()); EXPECT_TRUE(success); run_loop.Run(); } void DisableTracing() { base::RunLoop run_loop; bool success = TracingController::GetInstance()->StopTracing( TracingControllerImpl::CreateCallbackEndpoint(base::BindOnce( [](base::OnceClosure quit_closure, std::unique_ptr<std::string> trace_str) { std::move(quit_closure).Run(); }, run_loop.QuitClosure()))); EXPECT_TRUE(success); run_loop.Run(); } void RequestGlobalDumpAndWait( bool from_renderer_thread, const MemoryDumpType& dump_type, const MemoryDumpLevelOfDetail& level_of_detail) { base::RunLoop run_loop; RequestGlobalDumpWithClosure(from_renderer_thread, dump_type, level_of_detail, run_loop.QuitClosure()); run_loop.Run(); } void RequestGlobalDump(bool from_renderer_thread, const MemoryDumpType& dump_type, const MemoryDumpLevelOfDetail& level_of_detail) { RequestGlobalDumpWithClosure(from_renderer_thread, dump_type, level_of_detail, base::Closure()); } void Navigate(Shell* shell) { EXPECT_TRUE(NavigateToURL(shell, GetTestUrl("", "title1.html"))); } MOCK_METHOD2(OnMemoryDumpDone, void(uint32_t request_index, bool successful)); base::Closure on_memory_dump_complete_closure_; std::unique_ptr<MockDumpProvider> mock_dump_provider_; uint32_t next_request_index_; bool last_callback_success_; }; // Run SingleProcessMemoryTracingTests only on Android, since these tests are // intended to give coverage to Android WebView. #if defined(OS_ANDROID) class SingleProcessMemoryTracingTest : public MemoryTracingTest { public: SingleProcessMemoryTracingTest() {} void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(switches::kSingleProcess); } }; // https://crbug.com/788788 #if defined(OS_ANDROID) && defined(ADDRESS_SANITIZER) #define MAYBE_BrowserInitiatedSingleDump DISABLED_BrowserInitiatedSingleDump #else #define MAYBE_BrowserInitiatedSingleDump BrowserInitiatedSingleDump #endif // defined(OS_ANDROID) && defined(ADDRESS_SANITIZER) // Checks that a memory dump initiated from a the main browser thread ends up in // a single dump even in single process mode. IN_PROC_BROWSER_TEST_F(SingleProcessMemoryTracingTest, MAYBE_BrowserInitiatedSingleDump) { Navigate(shell()); EXPECT_CALL(*mock_dump_provider_, OnMemoryDump(_,_)).WillOnce(Return(true)); EXPECT_CALL(*this, OnMemoryDumpDone(_, true /* success */)); EnableMemoryTracing(); RequestGlobalDumpAndWait(false /* from_renderer_thread */, MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::DETAILED); DisableTracing(); } // https://crbug.com/788788 #if defined(OS_ANDROID) && defined(ADDRESS_SANITIZER) #define MAYBE_RendererInitiatedSingleDump DISABLED_RendererInitiatedSingleDump #else #define MAYBE_RendererInitiatedSingleDump RendererInitiatedSingleDump #endif // defined(OS_ANDROID) && defined(ADDRESS_SANITIZER) // Checks that a memory dump initiated from a renderer thread ends up in a // single dump even in single process mode. IN_PROC_BROWSER_TEST_F(SingleProcessMemoryTracingTest, MAYBE_RendererInitiatedSingleDump) { Navigate(shell()); EXPECT_CALL(*mock_dump_provider_, OnMemoryDump(_,_)).WillOnce(Return(true)); EXPECT_CALL(*this, OnMemoryDumpDone(_, true /* success */)); EnableMemoryTracing(); RequestGlobalDumpAndWait(true /* from_renderer_thread */, MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::DETAILED); DisableTracing(); } // https://crbug.com/788788 #if defined(OS_ANDROID) && defined(ADDRESS_SANITIZER) #define MAYBE_ManyInterleavedDumps DISABLED_ManyInterleavedDumps #else #define MAYBE_ManyInterleavedDumps ManyInterleavedDumps #endif // defined(OS_ANDROID) && defined(ADDRESS_SANITIZER) IN_PROC_BROWSER_TEST_F(SingleProcessMemoryTracingTest, MAYBE_ManyInterleavedDumps) { Navigate(shell()); EXPECT_CALL(*mock_dump_provider_, OnMemoryDump(_,_)) .Times(4) .WillRepeatedly(Return(true)); EXPECT_CALL(*this, OnMemoryDumpDone(_, true /* success */)).Times(4); EnableMemoryTracing(); RequestGlobalDumpAndWait(true /* from_renderer_thread */, MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::DETAILED); RequestGlobalDumpAndWait(false /* from_renderer_thread */, MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::DETAILED); RequestGlobalDumpAndWait(false /* from_renderer_thread */, MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::DETAILED); RequestGlobalDumpAndWait(true /* from_renderer_thread */, MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::DETAILED); DisableTracing(); } // Checks that, if there already is a memory dump in progress, subsequent memory // dump requests are queued and carried out after it's finished. Also checks // that periodic dump requests fail in case there is already a request in the // queue with the same level of detail. // Flaky failures on all platforms. https://crbug.com/752613 IN_PROC_BROWSER_TEST_F(SingleProcessMemoryTracingTest, DISABLED_QueuedDumps) { Navigate(shell()); EnableMemoryTracing(); // Issue the following 6 global memory dump requests: // // 0 (ED) req-------------------------------------->ok // 1 (PD) req->fail(0) // 2 (PL) req------------------------>ok // 3 (PL) req->fail(2) // 4 (EL) req---------->ok // 5 (ED) req--------->ok // 6 (PL) req->ok // // where P=PERIODIC_INTERVAL, E=EXPLICITLY_TRIGGERED, D=DETAILED and L=LIGHT. EXPECT_CALL(*mock_dump_provider_, OnMemoryDump(_, _)) .Times(5) .WillRepeatedly(Return(true)); EXPECT_CALL(*this, OnMemoryDumpDone(0, true /* success */)); RequestGlobalDump(true /* from_renderer_thread */, MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::DETAILED); // This dump should fail immediately because there's already a detailed dump // request in the queue. EXPECT_CALL(*this, OnMemoryDumpDone(1, false /* success */)); RequestGlobalDump(true /* from_renderer_thread */, MemoryDumpType::PERIODIC_INTERVAL, MemoryDumpLevelOfDetail::DETAILED); EXPECT_CALL(*this, OnMemoryDumpDone(2, true /* success */)); RequestGlobalDump(true /* from_renderer_thread */, MemoryDumpType::PERIODIC_INTERVAL, MemoryDumpLevelOfDetail::LIGHT); // This dump should fail immediately because there's already a light dump // request in the queue. EXPECT_CALL(*this, OnMemoryDumpDone(3, false /* success */)); RequestGlobalDump(true /* from_renderer_thread */, MemoryDumpType::PERIODIC_INTERVAL, MemoryDumpLevelOfDetail::LIGHT); EXPECT_CALL(*this, OnMemoryDumpDone(4, true /* success */)); RequestGlobalDump(true /* from_renderer_thread */, MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::LIGHT); EXPECT_CALL(*this, OnMemoryDumpDone(5, true /* success */)); RequestGlobalDumpAndWait(true /* from_renderer_thread */, MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::DETAILED); EXPECT_CALL(*this, OnMemoryDumpDone(6, true /* success */)); RequestGlobalDumpAndWait(true /* from_renderer_thread */, MemoryDumpType::PERIODIC_INTERVAL, MemoryDumpLevelOfDetail::LIGHT); DisableTracing(); } #endif // defined(OS_ANDROID) // Flaky on Mac. crbug.com/809809 #if defined(OS_MACOSX) #define MAYBE_BrowserInitiatedDump DISABLED_BrowserInitiatedDump #else #define MAYBE_BrowserInitiatedDump BrowserInitiatedDump #endif // Checks that a memory dump initiated from a the main browser thread ends up in // a successful dump. IN_PROC_BROWSER_TEST_F(MemoryTracingTest, MAYBE_BrowserInitiatedDump) { Navigate(shell()); EXPECT_CALL(*mock_dump_provider_, OnMemoryDump(_,_)).WillOnce(Return(true)); #if defined(OS_LINUX) // TODO(ssid): Test for dump success once the on start tracing done callback // is fixed to be called after enable tracing is acked by all processes, // crbug.com/709524. The test still tests if dumping does not crash. EXPECT_CALL(*this, OnMemoryDumpDone(_, _)); #else EXPECT_CALL(*this, OnMemoryDumpDone(_, true /* success */)); #endif EnableMemoryTracing(); RequestGlobalDumpAndWait(false /* from_renderer_thread */, MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::DETAILED); DisableTracing(); } } // namespace content
[ "rjkroege@chromium.org" ]
rjkroege@chromium.org
3bbee7bf8287e3a6263e9ba54f57b390385a71b6
10e14cdf4501bbb8fd4760f5a3a0f0a589b3667b
/src/rpcprotocol.cpp
ae939990e30e9db1365a6f4ef3d514d1001357a6
[ "MIT" ]
permissive
hkaase/TestCoin
57462b0fc11620e64d0f7450a72a989d58e513b0
73c647a99e933085ecc04c1d51491eeb44a922a4
refs/heads/master
2021-11-23T11:55:05.798829
2021-11-01T20:18:18
2021-11-01T20:18:18
29,237,303
0
0
null
null
null
null
UTF-8
C++
false
false
8,820
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Testcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcprotocol.h" #include "clientversion.h" #include "tinyformat.h" #include "util.h" #include "utilstrencodings.h" #include "utiltime.h" #include "version.h" #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/shared_ptr.hpp> #include "json/json_spirit_writer_template.h" using namespace std; using namespace json_spirit; //! Number of bytes to allocate and read at most at once in post data const size_t POST_READ_SIZE = 256 * 1024; /** * HTTP protocol * * This ain't Apache. We're just using HTTP header for the length field * and to be compatible with other JSON-RPC implementations. */ string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: Testcoin-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } static string rfc1123Time() { return DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", GetTime()); } static const char *httpStatusDescription(int nStatus) { switch (nStatus) { case HTTP_OK: return "OK"; case HTTP_BAD_REQUEST: return "Bad Request"; case HTTP_FORBIDDEN: return "Forbidden"; case HTTP_NOT_FOUND: return "Not Found"; case HTTP_INTERNAL_SERVER_ERROR: return "Internal Server Error"; default: return ""; } } string HTTPError(int nStatus, bool keepalive, bool headersOnly) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: Testcoin-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time(), FormatFullVersion()); return HTTPReply(nStatus, httpStatusDescription(nStatus), keepalive, headersOnly, "text/plain"); } string HTTPReplyHeader(int nStatus, bool keepalive, size_t contentLength, const char *contentType) { return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %u\r\n" "Content-Type: %s\r\n" "Server: Testcoin-json-rpc/%s\r\n" "\r\n", nStatus, httpStatusDescription(nStatus), rfc1123Time(), keepalive ? "keep-alive" : "close", contentLength, contentType, FormatFullVersion()); } string HTTPReply(int nStatus, const string& strMsg, bool keepalive, bool headersOnly, const char *contentType) { if (headersOnly) { return HTTPReplyHeader(nStatus, keepalive, 0, contentType); } else { return HTTPReplyHeader(nStatus, keepalive, strMsg.size(), contentType) + strMsg; } } bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto, string& http_method, string& http_uri) { string str; getline(stream, str); // HTTP request line is space-delimited vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return false; // HTTP methods permitted: GET, POST http_method = vWords[0]; if (http_method != "GET" && http_method != "POST") return false; // HTTP URI must be an absolute path, relative to current host http_uri = vWords[1]; if (http_uri.size() == 0 || http_uri[0] != '/') return false; // parse proto, if present string strProto = ""; if (vWords.size() > 2) strProto = vWords[2]; proto = 0; const char *ver = strstr(strProto.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return true; } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; while (true) { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTPMessage(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet, int nProto, size_t max_size) { mapHeadersRet.clear(); strMessageRet = ""; // Read header int nLen = ReadHTTPHeaders(stream, mapHeadersRet); if (nLen < 0 || (size_t)nLen > max_size) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch; size_t ptr = 0; while (ptr < (size_t)nLen) { size_t bytes_to_read = std::min((size_t)nLen - ptr, POST_READ_SIZE); vch.resize(ptr + bytes_to_read); stream.read(&vch[ptr], bytes_to_read); if (!stream) // Connection lost while reading return HTTP_INTERNAL_SERVER_ERROR; ptr += bytes_to_read; } strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return HTTP_OK; } /** * JSON-RPC protocol. Testcoin speaks version 1.0 for maximum compatibility, * but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were * unspecified (HTTP errors and contents of 'error'). * * 1.0 spec: http://json-rpc.org/wiki/specification * 1.2 spec: http://jsonrpc.org/historical/json-rpc-over-http.html * http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx */ string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; }
[ "livin2chill@yahoo.com" ]
livin2chill@yahoo.com