blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
ccdba0706dc029553594060a75f55704b3a808b2
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/make/new_hunk_1418.cpp
508a9f890b35f3b565abb7d268d5902613060970
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,610
cpp
if (!must_make) { if (debug_flag) { print_spaces(depth); printf("No need to remake target `%s'", file->name); if (!streq(file->name, file->hname)) printf("; using VPATH name `%s'", file->hname); printf(".\n"); fflush(stdout); } notice_finished_file (file); /* Since we don't need to remake the file, convert it to use the VPATH filename if we found one. hfile will be either the local name if no VPATH or the VPATH name if one was found. */ while (file) { file->name = file->hname; file = file->prev; } return 0; } DEBUGPR ("Must remake target `%s'.\n"); /* It needs to be remade. If it's VPATH and not GPATH, toss the VPATH */ if (!streq(file->name, file->hname)) { char *name = file->name; if (gpath_search (&name, NULL)) { register struct file *fp = file; /* Since we found the file on GPATH, convert it to use the VPATH filename. */ while (fp) { fp->name = fp->hname; fp = fp->prev; } DEBUGPR (" Using VPATH `%s' due to GPATH.\n"); } else { if (debug_flag) { print_spaces (depth); printf(" Ignoring VPATH name `%s'.\n", file->hname); fflush(stdout); } file->ignore_vpath = 1; } } /* Now, take appropriate actions to remake the file. */ remake_file (file);
[ "993273596@qq.com" ]
993273596@qq.com
c48a1e1c5b178e56d73b6cd82fa5d38cc4d8e249
30773b649ebd89ffadd16d30fd62740b77ca7865
/SDK/BP_female_makeup_asian_07_Desc_classes.h
25c70c144506ce58e83d297f77a6f230e7cc8fc9
[]
no_license
The-Jani/Sot-SDK
7f2772fb5df421e02b8fec237248af407cb2540b
2a158a461c697cca8db67aa28ffe3e43677dcf11
refs/heads/main
2023-07-09T07:17:56.972569
2021-08-18T23:45:06
2021-08-18T23:45:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
790
h
#pragma once // Name: S, Version: 2.2.1 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_female_makeup_asian_07_Desc.BP_female_makeup_asian_07_Desc_C // 0x0000 (FullSize[0x00E0] - InheritedSize[0x00E0]) class UBP_female_makeup_asian_07_Desc_C : public UClothingDesc { public: static UClass* StaticClass() { static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass BP_female_makeup_asian_07_Desc.BP_female_makeup_asian_07_Desc_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "ploszjanos9844@gmail.com" ]
ploszjanos9844@gmail.com
05023c08bbf982934bd2a8c915f8b45e9df86097
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-medialive/include/aws/medialive/model/BlackoutSlateState.h
dfa6b41ec1ed040abf99e65fe0c391a44def2386
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
1,142
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/medialive/MediaLive_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace MediaLive { namespace Model { enum class BlackoutSlateState { NOT_SET, DISABLED, ENABLED }; namespace BlackoutSlateStateMapper { AWS_MEDIALIVE_API BlackoutSlateState GetBlackoutSlateStateForName(const Aws::String& name); AWS_MEDIALIVE_API Aws::String GetNameForBlackoutSlateState(BlackoutSlateState value); } // namespace BlackoutSlateStateMapper } // namespace Model } // namespace MediaLive } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
d4078c7d186a2c61c3300ee22c7e2463905113b6
cd52ae2e7b1b0a8cf37255d164d56e2f312a281a
/system/host/fidl/include/fidl/attributes.h
f4415d925a2b6355f09b4bb0ffc4a4e68462214f
[ "BSD-3-Clause", "MIT" ]
permissive
xueshanlongyin/zircon
89e4f43d543d9e8a60cc44a2a68423ddca8f44c1
ef3759b917173f28e3ed6b175fd3dd5f0763c654
refs/heads/master
2020-04-09T11:34:19.344384
2018-12-01T04:41:54
2018-12-03T06:22:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,169
h
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ZIRCON_SYSTEM_HOST_FIDL_INCLUDE_FIDL_ATTRIBUTES_H_ #define ZIRCON_SYSTEM_HOST_FIDL_INCLUDE_FIDL_ATTRIBUTES_H_ #include <set> #include <vector> #include "error_reporter.h" #include "raw_ast.h" namespace fidl { // AttributePlacement indicates the placement of an attribute list, e.g. // whether that list will be placed on an enum declaration, method, or // union member. enum AttributePlacement { kConstDecl, kEnumDecl, kEnumMember, kInterfaceDecl, kLibrary, kMethod, kStructDecl, kStructMember, kTableDecl, kTableMember, kUnionDecl, kUnionMember, }; class AttributesBuilder { public: AttributesBuilder(ErrorReporter* error_reporter) : error_reporter_(error_reporter) {} AttributesBuilder(ErrorReporter* error_reporter, std::vector<std::unique_ptr<raw::Attribute>> attributes) : error_reporter_(error_reporter), attributes_(std::move(attributes)) { for (auto& attribute : attributes_) { names_.emplace(attribute->name); } } bool Insert(std::unique_ptr<raw::Attribute> attribute); std::vector<std::unique_ptr<raw::Attribute>> Done(); static void ValidatePlacement( ErrorReporter* error_reporter, AttributePlacement placement, const std::vector<std::unique_ptr<raw::Attribute>>& attributes); private: struct InsertResult { enum Kind { kOk, kDuplicate, kInvalidValue, kTypoOnKey, }; InsertResult(Kind kind, std::string message_fragment) : kind(kind), message_fragment(message_fragment) {} Kind kind; std::string message_fragment; }; InsertResult InsertHelper(std::unique_ptr<raw::Attribute> attribute); ErrorReporter* error_reporter_; std::vector<std::unique_ptr<raw::Attribute>> attributes_; std::set<std::string> names_; }; } // namespace fidl #endif // ZIRCON_SYSTEM_HOST_FIDL_INCLUDE_FIDL_ATTRIBUTES_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
fc7ec773a9888de99dd7cf76ec6bb998e490e890
b45a06b1b872983d5839d986a06a468f6f0a9ce3
/Информатика 2-е полугодие/5 Наследование. Виртуальные функции. Полиморфизм/Pup.h
8ae709716f0ba3fdaf6a1371423c25f66689e820
[]
no_license
Mimkas/Labs_PSTU
4dee49d25ae47e4ca6e757d7f6bee546e2d6688f
2d7b656d63fde6295eab048e8fdbb93ae488c555
refs/heads/master
2022-08-25T10:26:27.708532
2020-05-26T20:37:20
2020-05-26T20:37:20
263,996,728
0
0
null
null
null
null
UTF-8
C++
false
false
204
h
#pragma once #include <iostream> using namespace std; class Pup { public: Pup(void) {} ~Pup(void) {} virtual void Perimetr() = 0; virtual void Area() = 0; virtual void Show() = 0; };
[ "noreply@github.com" ]
noreply@github.com
a7171ff121e32309d4603ccd60e86e54870a5c16
65a95db5143154b85f21f784ba2cf692b4d77051
/ klcommon --username zmhn320@163.com/misc_utils/crashdumper.h
f49049916b0ec113e47b1ce264b559578268d5ca
[]
no_license
alphavip/klcommon
59ae20977fd0f9ab05d3435e56376c38bf0e78f6
a4e36efcebdd4e168b038bab903d4408a7fd0499
refs/heads/master
2020-04-26T14:10:24.047840
2012-12-20T09:48:39
2012-12-20T09:48:39
33,985,689
0
0
null
null
null
null
UTF-8
C++
false
false
236
h
/// /// /// #ifndef ___CRASH_DUMPER_H_ #define ___CRASH_DUMPER_H_ #include <windows.h> namespace CrashHelper { int CrashFilter( LPEXCEPTION_POINTERS lpEP, DWORD dwExceptionCode, char* dumpfilename = 0 ); } #endif
[ "kevinlynx@gmail.com@7f47985f-014d-0410-bc31-5375574df57d" ]
kevinlynx@gmail.com@7f47985f-014d-0410-bc31-5375574df57d
964b6e35a2d83a923e762dcf995161f75f31942e
81e71315f2f9e78704b29a5688ba2889928483bb
/include/Plugin/Plugin cre/crTexEnv.h
5e2a6550c6d566c06e80c9daa80d8f496a238574
[]
no_license
Creature3D/Creature3DApi
2c95c1c0089e75ad4a8e760366d0dd2d11564389
b284e6db7e0d8e957295fb9207e39623529cdb4d
refs/heads/master
2022-11-13T07:19:58.678696
2019-07-06T05:48:10
2019-07-06T05:48:10
274,064,341
0
1
null
null
null
null
UTF-8
C++
false
false
883
h
/* Creature3D - Online Game Engine, Copyright (C) 2005 Wucaihua(26756325@qq.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #ifndef CRE_TEXENV #define CRE_TEXENV 1 #include <CRCore/crTexEnv.h> #include <Plugin cre/crReadWrite.h> namespace cre{ class crTexEnv : public CRCore::crTexEnv, public crReadWrite { public: void write(crDataOutputStream* out); void read(crDataInputStream* in); }; } #endif
[ "wucaihua@86aba9cf-fb85-4101-ade8-2f98c1f5b361" ]
wucaihua@86aba9cf-fb85-4101-ade8-2f98c1f5b361
bd8ea9460a26aac8882be7d6301c54d85894170f
3cd0d9a1bfff1b977eb7bd2c15881e103141cbc3
/src/Widgets/VerticalSliderWidget.cpp
0c242b7f395d3f3fc8851f12faa53020ea0ce44a
[]
no_license
cefix/cefix
30c8a67120b1c0c94bbe5ad878373f7378392808
197f89a8cf603c14fe708f8e70252c3f725c2b08
refs/heads/master
2020-12-24T16:49:18.153881
2015-05-24T11:47:46
2015-05-24T11:47:46
36,169,777
0
0
null
null
null
null
UTF-8
C++
false
false
1,177
cpp
/* * VerticalSliderWidget.cpp * cefixWidgets * * Created by Stephan Huber on 04.06.07. * Copyright 2007 __MyCompanyName__. All rights reserved. * */ #include "VerticalSliderWidget.h" #include "AreaSliderWidget.h" #include <cefix/WidgetFactory.h> #include <cefix/Serializer.h> namespace cefix { VerticalSliderWidget::VerticalSliderWidget(cefix::PropertyList* pl) : SliderWidget(pl) { setRange( cefix::doubleRange(pl->get("min")->asDouble(), pl->get("max")->asDouble()) ); if (pl->hasKey("allowedValues")) { cefix::Serializer serializer(pl); std::vector<double> allowedValues; serializer >> "allowedValues" >> allowedValues; setAllowedValues(allowedValues); } setValue(pl->get("value")->asDouble()); } void VerticalSliderWidget::respondToAction(const std::string& action, AbstractWidget* widget) { if (action == SliderWidget::Actions::valueChanged() ) { { VerticalSliderWidget* s = dynamic_cast<VerticalSliderWidget*>(widget); if (s) { setValue(s->getValue()); return; } } { AreaSliderWidget* s = dynamic_cast<AreaSliderWidget*>(widget); if (s) { setValue(s->getValue()[1]); return; } } } } }
[ "stephan@factorial.io" ]
stephan@factorial.io
2b5b7fc7937ec1e07306051cd7780d8384a700cc
56368e062b6489fd8c8ee4313444de1cdf1f9635
/src/algorithm/pose_estimation/core/opOutputToCvMat.cpp
21d999903b58697180b777200afd4db9db795eba
[]
no_license
lampsonSong/PersonDetectTrack
a63d22dfb0385e57e6d2c7091e642131e58a9c21
324867269c1ed4c65b464f3552660d7dc3b95755
refs/heads/master
2021-06-20T16:38:38.765764
2019-07-18T15:11:50
2019-07-18T15:11:50
136,471,764
1
0
null
null
null
null
UTF-8
C++
false
false
900
cpp
#include <algorithm/ulspose/utilities/errorAndLog.hpp> #include <algorithm/ulspose/utilities/openCv.hpp> #include <algorithm/ulspose/core/opOutputToCvMat.hpp> namespace pose { OpOutputToCvMat::OpOutputToCvMat(const Point<int>& outputResolution) : mOutputResolution{outputResolution} { } cv::Mat OpOutputToCvMat::formatToCvMat(const Array<float>& outputData) const { try { // Security checks if (outputData.empty()) error("Wrong input element (empty outputData).", __LINE__, __FUNCTION__, __FILE__); cv::Mat cvMat; floatPtrToUCharCvMat(cvMat, outputData.getConstPtr(), mOutputResolution, 3); return cvMat; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return cv::Mat{}; } } }
[ "lampson.song@ulsee.com" ]
lampson.song@ulsee.com
97751db957f85bccdea77591797a33c833669381
3bcbbcb988c0d6a9ed06cb865f7fbb6876e0fb9f
/plugins/gui/src/configurator/Group.h
fa79a8db83168fe6f8d96d5846a3b717aa2afbec
[]
permissive
voei/megamol
7afd26ff7bd106ecf99e56393593a8b92f978207
569b7b58c1f9bc5405b79549b86f84009329f668
refs/heads/master
2022-12-26T08:18:13.553724
2020-10-03T13:26:49
2020-10-03T13:26:49
263,350,326
0
0
BSD-3-Clause
2020-05-12T13:49:50
2020-05-12T13:49:50
null
UTF-8
C++
false
false
2,830
h
/* * Group.h * * Copyright (C) 2020 by Universitaet Stuttgart (VISUS). * Alle Rechte vorbehalten. */ #ifndef MEGAMOL_GUI_GRAPH_GROUP_H_INCLUDED #define MEGAMOL_GUI_GRAPH_GROUP_H_INCLUDED #include "Call.h" #include "CallSlot.h" #include "GUIUtils.h" #include "Module.h" namespace megamol { namespace gui { namespace configurator { // Forward declaration class Group; // Pointer types to class typedef std::shared_ptr<Group> GroupPtrType; typedef std::vector<GroupPtrType> GroupPtrVectorType; /** * Defines module data structure for graph. */ class Group { public: Group(ImGuiID uid); ~Group(); const ImGuiID uid; // Init when adding group to graph std::string name; bool AddModule(const ModulePtrType& module_ptr); bool RemoveModule(ImGuiID module_uid); bool ContainsModule(ImGuiID module_uid); inline const ModulePtrVectorType& GetModules(void) { return this->modules; } inline bool EmptyModules(void) { return (this->modules.size() == 0); } bool AddCallSlot(const CallSlotPtrType& callslot_ptr); bool RemoveCallSlot(ImGuiID callslot_uid); bool ContainsCallSlot(ImGuiID callslot_uid); inline const CallSlotPtrMapType& GetCallSlots(void) { return this->callslots; } // GUI Presentation ------------------------------------------------------- inline void GUI_Present(GraphItemsStateType& state) { this->present.Present(*this, state); } inline void GUI_Update(const GraphCanvasType& in_canvas) { this->present.UpdatePositionSize(*this, in_canvas); } private: // VARIABLES -------------------------------------------------------------- ModulePtrVectorType modules; CallSlotPtrMapType callslots; /** ************************************************************************ * Defines GUI group presentation. */ class Presentation { public: Presentation(void); ~Presentation(void); void Present(Group& inout_group, GraphItemsStateType& state); void UpdatePositionSize(Group& inout_group, const GraphCanvasType& in_canvas); inline bool ModuleVisible(void) { return !this->collapsed_view; } inline void ForceUpdate(void) { this->update = true; } private: const float border; // Relative position without considering canvas offset and zooming ImVec2 position; // Relative size without considering zooming ImVec2 size; GUIUtils utils; std::string name_label; bool collapsed_view; bool selected; bool update; } present; // FUNCTIONS -------------------------------------------------------------- void restore_callslot_interface_sate(void); }; } // namespace configurator } // namespace gui } // namespace megamol #endif // MEGAMOL_GUI_GRAPH_GROUP_H_INCLUDED
[ "matthias.braun@visus.uni-stuttgart.de" ]
matthias.braun@visus.uni-stuttgart.de
b5b22751098a2089fb25bf41bf1d0b354b3b70dd
f561be153bdccd4b9fd0eb17049d542a1d8effd9
/ReverseLinkedList.cpp
241eb43f2a8182f65e08b5ec06e56062c9f5f109
[]
no_license
smiley001/LintCode-Mine
e2150f08a67a309293d1819ea1b3c59960fea11f
771057677783e50dc4f7101d9172b70c8b401416
refs/heads/master
2021-01-12T18:59:59.596580
2015-09-08T06:47:57
2015-09-08T06:47:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,154
cpp
/************************************************************************* > File Name: ReverseLinkedList.cpp > Author: Shaojie kang > Mail: kangshaojie@ict.ac.cn > Created Time: 2015年08月16日 星期日 15时35分51秒 > Problem: Reverse a linked list. Have you met this question in a real interview? Yes Example For linked list 1->2->3, the reversed linked list is 3->2->1 Challenge Reverse it in-place and in one-pass > Solution: ************************************************************************/ #include<iostream> using namespace std; // Solution 1: ListNode *reverse(ListNode *head) { if(!head || !head->next) return head; ListNode *p = head; ListNode *q = head->next; p->next = NULL; ListNode *r; while(q) { r = q->next; q->next = p; p = q; q = r; } return q; } // Solution 2: recursive ListNode *reverse2(ListNode *head) { if(!head || !head->next) return head; ListNode *p = head->next; head->next = NULL; ListNode *newHead = reverse2(p); p->next = head; return newHead; }
[ "TopShaojie.kang@gmail.com" ]
TopShaojie.kang@gmail.com
833787ae4e9ef24d72af9c75a5a3244eabb80b98
eac6389b179ad0d4891f08604643bd9221a7ae24
/float2int.cpp
0ec3ab3044e4ce10bbb6d327fc1e8326b1824b3c
[]
no_license
Bokaein/float2int
574bb6846f334a6b5e251f9551fe4492e7a74bc2
3d57063fa99f3d258bfc6b31c6ae1ce1646577be
refs/heads/master
2016-09-05T10:50:18.181086
2014-07-30T08:13:19
2014-07-30T08:13:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
105
cpp
#include<iostream> using namespace std; int main() { cout<<"HI"<<endl; system("pause"); return 0; }
[ "am.bo740@gmail.com" ]
am.bo740@gmail.com
2198a6b682994785fbb4e3c064e6824709d1099e
dfe51c30e42dd415c41a47feb6ad21195d456c78
/TGUI/include/TGUI/Exception.hpp
90d14b962e2828d553266a18465c4fcfa6e05fb3
[]
no_license
Ruckamongus/ChessProject
d2e74f31870d9f569231b181bc0cc7319fa050f0
df941c91113e93aa7fb838d33a0f0a3b993d5e9f
refs/heads/master
2020-12-24T16:06:03.337930
2015-04-06T16:18:32
2015-04-06T16:18:32
24,443,629
0
0
null
null
null
null
UTF-8
C++
false
false
2,236
hpp
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TGUI - Texus's Graphical User Interface // Copyright (C) 2012-2014 Bruno Van de Velde (vdv_b@tgui.eu) // // 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 TGUI_EXCEPTION_HPP #define TGUI_EXCEPTION_HPP ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <string> #include <stdexcept> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace tgui { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class TGUI_API Exception : public std::runtime_error { public: explicit Exception(const std::string& argument) : std::runtime_error(argument) { } }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif // TGUI_EXCEPTION_HPP
[ "ruckamongus@live.com" ]
ruckamongus@live.com
10fce70c7058fb2f41b642b860521012ac1f1a31
932be410302b60bb5d2606f70a3dd49d96c937d5
/BluemixBasic.ino
653f5ed6fcdfe647708a7a066b25a2b76676cf52
[]
no_license
gsethi2409/BluemixDHT
06839ccaa74fc0e17833c69144a042b0c84aef01
5262277e2bdcccd91b327d88f7d5854dad1878df
refs/heads/master
2021-01-21T21:22:35.674855
2017-06-20T00:53:17
2017-06-20T00:53:17
94,833,503
0
0
null
null
null
null
UTF-8
C++
false
false
1,456
ino
#include <ESP8266WiFi.h> #include <PubSubClient.h> #include<DHT.h> const char* ssid = "Paradise"; const char* password = "mukesh9980813506"; #define ORG "5z4xqx" #define DEVICE_TYPE "ESP8266" #define DEVICE_ID "HDK" #define TOKEN "9632333088" char server[] = ORG ".messaging.internetofthings.ibmcloud.com"; char topic[] = "iot-2/evt/DHT/fmt/json"; char authMethod[] = "use-token-auth"; char token[] = TOKEN; char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID; WiFiClient wifiClient; PubSubClient client(server, 1883, NULL, wifiClient); void setup() { Serial.begin(115200); Serial.println(); Serial.print("Connecting to "); Serial.print(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("WiFi connected, IP address: "); Serial.println(WiFi.localIP()); } int counter = 0; void loop() { if (!client.connected()) { Serial.print("Reconnecting client to "); Serial.println(server); while (!client.connect(clientId, authMethod, token)) { Serial.print("."); delay(500); } Serial.println(); } String payload = "{\"d\":{\"Name\":\"18FE34D81E46\""; payload += ",\"counter\":"; payload += counter++; payload += "}}"; Serial.print("Sending payload: "); Serial.println(payload); if (client.publish(topic, (char*) payload.c_str())) { Serial.println("Publish ok"); } else { Serial.println("Publish failed"); } delay(5000); }
[ "noreply@github.com" ]
noreply@github.com
2ed40c1d36a57f2d070b74c4cd5afc8360c902c0
5e0d2cccaa65646b9a8acb505d48e09c9ddecbde
/Libs/IBAMR/src/IB/msvIBInitializer.h
0bad9e62ad0a6f774be6d5909303b037c10cc3b8
[ "Apache-2.0" ]
permissive
alan-wu/MSVTK
8a35aa2875e8cc765b7c92c477f8b0307b2b333c
c287e822c046f3062d13d34c4fb0e15adc4f2368
refs/heads/master
2021-01-16T20:38:09.863294
2013-02-01T01:01:59
2013-02-01T01:01:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,989
h
// Filename: msvIBInitializer.h // Created on 22 Nov 2006 by Boyce Griffith // // Copyright (c) 2002-2010, Boyce Griffith // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of New York University nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef included_msvIBInitializer #define included_msvIBInitializer /////////////////////////////// INCLUDES ///////////////////////////////////// #ifndef included_IBAMR_prefix_config // #include <IBAMR_prefix_config.h> #define included_IBAMR_prefix_config #endif // IBAMR INCLUDES #include <ibamr/IBRodForceSpec.h> // IBTK INCLUDES #include <ibtk/LInitStrategy.h> #include <ibtk/LSiloDataWriter.h> #include <ibtk/Streamable.h> // C++ STDLIB INCLUDES #include <map> #include <vector> #include <vtkSmartPointer.h> class vtkDataSet; /////////////////////////////// CLASS DEFINITION ///////////////////////////// namespace IBAMR { /*! * \brief Class msvIBInitializer is a concrete LInitStrategy that * initializes the configuration of one or more Lagrangian structures from vtk * datasets. * * */ class msvIBInitializer : public IBTK::LInitStrategy { public: /*! * \brief Constructor. */ msvIBInitializer( const std::string& object_name, SAMRAI::tbox::Pointer<SAMRAI::tbox::Database> input_db, vtkSmartPointer<vtkDataSet> data ); /*! * \brief Destructor. */ ~msvIBInitializer(); /*! * \brief Register a Silo data writer with the IB initializer object. */ void registerLSiloDataWriter( SAMRAI::tbox::Pointer<IBTK::LSiloDataWriter> silo_writer); /*! * \brief Determine whether there are any Lagrangian nodes on the specified * patch level. * * \return A boolean value indicating whether Lagrangian data is associated * with the given level in the patch hierarchy. */ bool getLevelHasLagrangianData( int level_number, bool can_be_refined) const; /*! * \brief Determine the number of local nodes on the specified patch level. * * \return The number of local nodes on the specified level. */ unsigned int computeLocalNodeCountOnPatchLevel( SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > hierarchy, int level_number, double init_data_time, bool can_be_refined, bool initial_time); /*! * \brief Initialize the structure indexing information on the patch level. */ void initializeStructureIndexingOnPatchLevel( std::map<int,std::string>& strct_id_to_strct_name_map, std::map<int,std::pair<int,int> >& strct_id_to_lag_idx_range_map, int level_number, double init_data_time, bool can_be_refined, bool initial_time, IBTK::LDataManager* l_data_manager); /*! * \brief Initialize the LNode and LData data needed to specify the * configuration of the curvilinear mesh on the patch level. * * \return The number of local nodes initialized on the patch level. */ unsigned int initializeDataOnPatchLevel( int lag_node_index_idx, unsigned int global_index_offset, unsigned int local_index_offset, SAMRAI::tbox::Pointer<IBTK::LData> X_data, SAMRAI::tbox::Pointer<IBTK::LData> U_data, SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > hierarchy, int level_number, double init_data_time, bool can_be_refined, bool initial_time, IBTK::LDataManager* l_data_manager); /*! * \brief Initialize the LData needed to specify the mass and spring * constant data required by the penalty IB method. * * \return The number of local nodes initialized on the patch level. */ unsigned int initializeMassDataOnPatchLevel( unsigned int global_index_offset, unsigned int local_index_offset, SAMRAI::tbox::Pointer<IBTK::LData> M_data, SAMRAI::tbox::Pointer<IBTK::LData> K_data, SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > hierarchy, int level_number, double init_data_time, bool can_be_refined, bool initial_time, IBTK::LDataManager* l_data_manager); /*! * \brief Initialize the LNode data needed to specify director vectors * required by some material models. * * \return The number of local nodes initialized on the patch level. */ unsigned int initializeDirectorDataOnPatchLevel( unsigned int global_index_offset, unsigned int local_index_offset, SAMRAI::tbox::Pointer<IBTK::LData> D_data, SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > hierarchy, int level_number, double init_data_time, bool can_be_refined, bool initial_time, IBTK::LDataManager* l_data_manager); /*! * \brief Tag cells for initial refinement. * * When the patch hierarchy is being constructed at the initial simulation * time, it is necessary to instruct the gridding algorithm where to place * local refinement in order to accommodate portions of the curvilinear mesh * that will reside in any yet-to-be-constructed level(s) of the patch * hierarchy. */ void tagCellsForInitialRefinement( SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > hierarchy, int level_number, double error_data_time, int tag_index); protected: private: /*! * \brief Default constructor. * * \note This constructor is not implemented and should not be used. */ msvIBInitializer(); /*! * \brief Copy constructor. * * \note This constructor is not implemented and should not be used. * * \param from The value to copy to this object. */ msvIBInitializer( const msvIBInitializer& from); /*! * \brief Assignment operator. * * \note This constructor is not implemented and should not be used. * * \param that The value to assign to this object. * * \return A reference to this object. */ msvIBInitializer& operator=( const msvIBInitializer& that); /*! * \brief Configure the Lagrangian Silo data writer to plot the data * associated with the specified level of the locally refined Cartesian * grid. */ void initializeLSiloDataWriter( int level_number); /*! * \brief Read the vertex data from one or more datasets. */ void readVertexDataset(); /*! * \brief Read the spring data from one or more input files. */ void readSpringDataset(); /*! * \brief Read the spring data from one or more vtk datasets. */ void AddPolyDataSet(int ln, vtkDataSet *data_set); // /*! // * \brief Read the beam data from one or more input files. // */ // void // readBeamFiles(); // // /*! // * \brief Read the rod data from one or more input files. // */ // void // readRodFiles(); // /*! * \brief Read the target point data from one or more input files. */ void readTargetPointDataset(); // // /*! // * \brief Read the anchor point data from one or more input files. // */ // void // readAnchorPointFiles(); // // /*! // * \brief Read the boundary mass data from one or more input files. // */ // void // readBoundaryMassFiles(); // // /*! // * \brief Read the director data from one or more input files. // */ // void // readDirectorFiles(); // // /*! // * \brief Read the instrumentation data from one or more input files. // */ // void // readInstrumentationFiles(); // /*! * \brief Read the source/sink data from one or more input datasets. */ void readSourceDatasets(); /*! * \brief Determine the indices of any vertices initially located within the * specified patch. */ void getPatchVertices( std::vector<std::pair<int,int> >& point_indices, SAMRAI::tbox::Pointer<SAMRAI::hier::Patch<NDIM> > patch, int level_number, bool can_be_refined) const; /*! * \return The canonical Lagrangian index of the specified vertex. */ int getCanonicalLagrangianIndex( const std::pair<int,int>& point_index, int level_number) const; /*! * \return The initial position of the specified vertex. */ blitz::TinyVector<double,NDIM> getVertexPosn( const std::pair<int,int>& point_index, int level_number) const; /*! * \return The target point specifications associated with a particular * node. */ struct TargetSpec; const TargetSpec& getVertexTargetSpec( const std::pair<int,int>& point_index, int level_number) const; /*! * \return The anchor point specifications associated with a particular * node. */ struct AnchorSpec; const AnchorSpec& getVertexAnchorSpec( const std::pair<int,int>& point_index, int level_number) const; /*! * \return The massive boundary point specifications associated with a * particular node. */ struct BdryMassSpec; const BdryMassSpec& getVertexBdryMassSpec( const std::pair<int,int>& point_index, int level_number) const; /*! * \return The directors associated with a particular node. */ const std::vector<double>& getVertexDirectors( const std::pair<int,int>& point_index, int level_number) const; /*! * \return The instrumentation indices associated with a particular node (or * std::make_pair(-1,-1) if there is no instrumentation data associated with * that node). */ std::pair<int,int> getVertexInstrumentationIndices( const std::pair<int,int>& point_index, int level_number) const; /*! * \return The source indices associated with a particular node (or -1 if * there is no source data associated with that node). */ int getVertexSourceIndices( const std::pair<int,int>& point_index, int level_number) const; /*! * \return The specification objects associated with the specified vertex. */ std::vector<SAMRAI::tbox::Pointer<IBTK::Streamable> > initializeSpecs( const std::pair<int,int>& point_index, unsigned int global_index_offset, int level_number) const; /*! * Read input values, indicated above, from given database. * * When assertion checking is active, the database pointer must be non-null. */ void getFromInput( SAMRAI::tbox::Pointer<SAMRAI::tbox::Database> db, vtkDataSet* data ); /* * The object name is used as a handle to databases stored in restart files * and for error reporting purposes. */ std::string d_object_name; /* * The boolean value determines whether file read batons are employed to * prevent multiple MPI processes from accessing the same input files * simultaneously. */ bool d_use_file_batons; /* * The maximum number of levels in the Cartesian grid patch hierarchy and a * vector of boolean values indicating whether a particular level has been * initialized yet. */ int d_max_levels; std::vector<bool> d_level_is_initialized; /* * An (optional) Lagrangian Silo data writer. */ SAMRAI::tbox::Pointer<IBTK::LSiloDataWriter> d_silo_writer; /* * The base filenames of the structures are used to generate unique names * when registering data with the Silo data writer. */ std::vector<std::vector<std::string> > d_base_filename; /* * Pointers to vtk datasets */ std::vector<std::vector<vtkSmartPointer<vtkDataSet> > > d_data_sets; /* * Optional shift and scale factors. * * \note These shift and scale factors are applied to ALL structures read in * by this reader. * * \note The scale factor is applied both to positions and to spring rest * lengths. * * \note The shift factor should have the same units as the positions in the * input files, i.e., X_final = scale*(X_initial + shift). */ double d_length_scale_factor; blitz::TinyVector<double,NDIM> d_posn_shift; /* * Vertex information. */ std::vector<std::vector<int> > d_num_vertex, d_vertex_offset; std::vector<std::vector<std::vector<blitz::TinyVector<double,NDIM> > > > d_vertex_posn; /* * Edge data structures. */ typedef std::pair<int,int> Edge; struct EdgeComp : public std::binary_function<Edge,Edge,bool> { inline bool operator()( const Edge& e1, const Edge& e2) const { return (e1.first < e2.first) || (e1.first == e2.first && e1.second < e2.second); } }; /* * Spring information. */ std::vector<std::vector<bool> > d_enable_springs; std::vector<std::vector<std::multimap<int,Edge> > > d_spring_edge_map; struct SpringSpec { double stiffness, rest_length; int force_fcn_idx; #if ENABLE_SUBDOMAIN_INDICES int subdomain_idx; #endif }; std::vector<std::vector<std::map<Edge,SpringSpec,EdgeComp> > > d_spring_spec_data; std::vector<std::vector<bool> > d_using_uniform_spring_stiffness; std::vector<std::vector<double> > d_uniform_spring_stiffness; std::vector<std::vector<bool> > d_using_uniform_spring_rest_length; std::vector<std::vector<double> > d_uniform_spring_rest_length; std::vector<std::vector<bool> > d_using_uniform_spring_force_fcn_idx; std::vector<std::vector<int> > d_uniform_spring_force_fcn_idx; #if ENABLE_SUBDOMAIN_INDICES std::vector<std::vector<bool> > d_using_uniform_spring_subdomain_idx; std::vector<std::vector<int> > d_uniform_spring_subdomain_idx; #endif /* * Beam information. */ std::vector<std::vector<bool> > d_enable_beams; struct BeamSpec { std::pair<int,int> neighbor_idxs; double bend_rigidity; blitz::TinyVector<double,NDIM> curvature; #if ENABLE_SUBDOMAIN_INDICES int subdomain_idx; #endif }; std::vector<std::vector<std::multimap<int,BeamSpec> > > d_beam_spec_data; std::vector<std::vector<bool> > d_using_uniform_beam_bend_rigidity; std::vector<std::vector<double> > d_uniform_beam_bend_rigidity; std::vector<std::vector<bool> > d_using_uniform_beam_curvature; std::vector<std::vector<blitz::TinyVector<double,NDIM> > > d_uniform_beam_curvature; #if ENABLE_SUBDOMAIN_INDICES std::vector<std::vector<bool> > d_using_uniform_beam_subdomain_idx; std::vector<std::vector<int> > d_uniform_beam_subdomain_idx; #endif /* * Rod information. */ std::vector<std::vector<bool> > d_enable_rods; std::vector<std::vector<std::multimap<int,Edge> > > d_rod_edge_map; struct RodSpec { blitz::TinyVector<double,IBRodForceSpec::NUM_MATERIAL_PARAMS> properties; #if ENABLE_SUBDOMAIN_INDICES int subdomain_idx; #endif }; std::vector<std::vector<std::map<Edge,RodSpec,EdgeComp> > > d_rod_spec_data; std::vector<std::vector<bool> > d_using_uniform_rod_properties; std::vector<std::vector<blitz::TinyVector<double,IBRodForceSpec::NUM_MATERIAL_PARAMS> > > d_uniform_rod_properties; #if ENABLE_SUBDOMAIN_INDICES std::vector<std::vector<bool> > d_using_uniform_rod_subdomain_idx; std::vector<std::vector<int> > d_uniform_rod_subdomain_idx; #endif /* * Target point information. */ std::vector<std::vector<bool> > d_enable_target_points; struct TargetSpec { double stiffness, damping; #if ENABLE_SUBDOMAIN_INDICES int subdomain_idx; #endif }; std::vector<std::vector<std::vector<TargetSpec> > > d_target_spec_data; std::vector<std::vector<bool> > d_using_uniform_target_stiffness; std::vector<std::vector<double> > d_uniform_target_stiffness; std::vector<std::vector<bool> > d_using_uniform_target_damping; std::vector<std::vector<double> > d_uniform_target_damping; #if ENABLE_SUBDOMAIN_INDICES std::vector<std::vector<bool> > d_using_uniform_target_subdomain_idx; std::vector<std::vector<int> > d_uniform_target_subdomain_idx; #endif /* * Anchor point information. */ std::vector<std::vector<bool> > d_enable_anchor_points; struct AnchorSpec { bool is_anchor_point; #if ENABLE_SUBDOMAIN_INDICES int subdomain_idx; #endif }; std::vector<std::vector<std::vector<AnchorSpec> > > d_anchor_spec_data; #if ENABLE_SUBDOMAIN_INDICES std::vector<std::vector<bool> > d_using_uniform_anchor_subdomain_idx; std::vector<std::vector<int> > d_uniform_anchor_subdomain_idx; #endif /* * Mass information for the pIB method. */ std::vector<std::vector<bool> > d_enable_bdry_mass; struct BdryMassSpec { double bdry_mass, stiffness; }; std::vector<std::vector<std::vector<BdryMassSpec> > > d_bdry_mass_spec_data; std::vector<std::vector<bool> > d_using_uniform_bdry_mass; std::vector<std::vector<double> > d_uniform_bdry_mass; std::vector<std::vector<bool> > d_using_uniform_bdry_mass_stiffness; std::vector<std::vector<double> > d_uniform_bdry_mass_stiffness; /* * Orthonormal directors for the generalized IB method. */ std::vector<std::vector<std::vector<std::vector<double> > > > d_directors; /* * Instrumentation information. */ std::vector<std::vector<bool> > d_enable_instrumentation; std::vector<std::vector<std::map<int,std::pair<int,int> > > > d_instrument_idx; /* * Source information. */ std::vector<std::vector<bool> > d_enable_sources; std::vector<std::vector<std::map<int,int> > > d_source_idx; /* * Data required to specify connectivity information for visualization * purposes. */ std::vector<unsigned int> d_global_index_offset; }; }// namespace IBAMR /////////////////////////////// INLINE /////////////////////////////////////// //#include "msvIBInitializer.I" ////////////////////////////////////////////////////////////////////////////// #endif //#ifndef included_msvIBInitializer
[ "ricardo.ortiz@kitware.com" ]
ricardo.ortiz@kitware.com
55ae6edd9254303da51210166bb2c810a603b803
a615d3604fc47643df42f7d9fd14102eb27efc7e
/outboundbot/src/model/CreateGlobalQuestionResult.cc
2056caa606df004a5dfdc71f49c89464d27137bc
[ "Apache-2.0" ]
permissive
CharlesE-233/aliyun-openapi-cpp-sdk
b5d336e8d5f8c6041f3d294d99b89965e3370831
cba94f21199ae8943b5d0024099a90b1880024e7
refs/heads/master
2021-04-19T10:15:35.376349
2020-03-24T02:53:36
2020-03-24T02:53:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,121
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/outboundbot/model/CreateGlobalQuestionResult.h> #include <json/json.h> using namespace AlibabaCloud::OutboundBot; using namespace AlibabaCloud::OutboundBot::Model; CreateGlobalQuestionResult::CreateGlobalQuestionResult() : ServiceResult() {} CreateGlobalQuestionResult::CreateGlobalQuestionResult(const std::string &payload) : ServiceResult() { parse(payload); } CreateGlobalQuestionResult::~CreateGlobalQuestionResult() {} void CreateGlobalQuestionResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["Message"].isNull()) message_ = value["Message"].asString(); if(!value["HttpStatusCode"].isNull()) httpStatusCode_ = std::stoi(value["HttpStatusCode"].asString()); if(!value["GlobalQuestionId"].isNull()) globalQuestionId_ = value["GlobalQuestionId"].asString(); } std::string CreateGlobalQuestionResult::getMessage()const { return message_; } int CreateGlobalQuestionResult::getHttpStatusCode()const { return httpStatusCode_; } std::string CreateGlobalQuestionResult::getGlobalQuestionId()const { return globalQuestionId_; } std::string CreateGlobalQuestionResult::getCode()const { return code_; } bool CreateGlobalQuestionResult::getSuccess()const { return success_; }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
401e435d5c5230e2295608ffbec0f5bb37164a6f
625f6dfc65b44beeba2f2cb6b5a7501b5998355d
/ybt/ybt2037.cpp
02e7f229fc830a265c295db9352e372f7739dae1
[]
no_license
rczfe390/leomaster-oi-code
5388979681a0b96b0cb948fbf467bff2410098e3
d0fe4ca734050a95fbc468643914fd0a6fc29306
refs/heads/main
2023-07-08T07:17:56.074455
2021-08-19T03:20:47
2021-08-19T03:20:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
465
cpp
#include <bits/stdc++.h> using namespace std; int n, m, x, t; int a[10010]; int main() { cin >> n >> m; x = t = 0; while (x < n) { for (int i = 1; i <= n; i++) if (a[i] == 0) { t++; if (t == m) { cout << i << " "; a[i] = 1; t = 0; x++; } } } return 0; }
[ "873393631@qq.com" ]
873393631@qq.com
013c0b2d2c4d53682659e3b6694e4bb4b5051dae
87c48e4f87405ebed2e55b5aa385fe0467830f5c
/Kiehls_GlobalVideoWall_08/src/button.h
d611e0ce578a4c1dbc4b0195a65f4beb233b0974
[]
no_license
bestpaul1985/YesYesNo
fe92e2edbeb4a4871864992de9c0fc085e2f099f
12ab95146e196c151512f9b4c1bc82cd0f0ad15b
refs/heads/master
2021-01-13T01:22:32.001885
2014-09-08T18:48:21
2014-09-08T18:48:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
457
h
#pragma once #include "ofMain.h" class button { public: button(); void setup(ofImage &img, int x, int y, int Angle); void update(); void draw(); float angle; float xSpeed; float width; float height; ofPoint pos; ofPoint orgPos; ofImage *image; ofRectangle rect; bool bMousePressed; float dragDx; };
[ "bestpaul1985@gmail.com" ]
bestpaul1985@gmail.com
4ea3e9d3c0791908710461033f6bcf621925779a
b7e97047616d9343be5b9bbe03fc0d79ba5a6143
/src/protocols/stepwise/screener/IntegrationTestBreaker.cc
05f8c7ea4898405a4890ba789eadc41e25b2dc7d
[]
no_license
achitturi/ROSETTA-main-source
2772623a78e33e7883a453f051d53ea6cc53ffa5
fe11c7e7cb68644f404f4c0629b64da4bb73b8f9
refs/heads/master
2021-05-09T15:04:34.006421
2018-01-26T17:10:33
2018-01-26T17:10:33
119,081,547
1
3
null
null
null
null
UTF-8
C++
false
false
3,169
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file protocols/stepwise/screener/IntegrationTestBreaker.cc /// @brief /// @details /// @author Rhiju Das, rhiju@stanford.edu #include <protocols/stepwise/screener/IntegrationTestBreaker.hh> #include <protocols/stepwise/screener/AlignRMSD_Screener.hh> #include <protocols/stepwise/sampler/rigid_body/RigidBodyStepWiseSamplerWithResidueList.hh> #include <protocols/stepwise/sampler/rigid_body/RigidBodyStepWiseSamplerWithResidueAlternatives.hh> #include <basic/Tracer.hh> static THREAD_LOCAL basic::Tracer TR( "protocols.stepwise.screener.IntegrationTestBreaker" ); using namespace protocols::stepwise::sampler; using namespace protocols::stepwise::sampler::rigid_body; namespace protocols { namespace stepwise { namespace screener { //Constructor IntegrationTestBreaker::IntegrationTestBreaker( StepWiseScreenerOP screener_whose_counts_to_check, StepWiseScreenerOP final_screener /*total_count -- for turning on align screen*/, AlignRMSD_ScreenerOP align_rmsd_screener ): screener_whose_counts_to_check_( screener_whose_counts_to_check ), final_screener_( final_screener ), align_rmsd_screener_( align_rmsd_screener ) {} //Destructor IntegrationTestBreaker::~IntegrationTestBreaker() {} ////////////////////////////////////////////////////////////////////////// // If you see an issue with changes to integration tests, take // a close look at options -- note that it should 'spawn' get_sampler_options() // which is fixed for integration tests. bool IntegrationTestBreaker::check_screen() { if ( screener_whose_counts_to_check_ && screener_whose_counts_to_check_->count() >= 100 ) return false; if ( align_rmsd_screener_ != 0 ) { if ( final_screener_->count() >= 10 ) align_rmsd_screener_->set_do_screen( true ); if ( align_rmsd_screener_->pass_count() >= 10 ) return false; } return true; } //////////////////////////////////////////////////////////////////////////// void IntegrationTestBreaker::fast_forward( sampler::StepWiseSamplerOP sampler ){ if ( sampler->type() == toolbox::RIGID_BODY_WITH_RESIDUE_LIST ) { RigidBodyStepWiseSamplerWithResidueList & rigid_body_rotamer_with_copy_dofs = *( static_cast< RigidBodyStepWiseSamplerWithResidueList * >( sampler.get() ) ); rigid_body_rotamer_with_copy_dofs.fast_forward(); } else if ( sampler->type() == toolbox::RIGID_BODY_WITH_RESIDUE_ALTERNATIVES ) { RigidBodyStepWiseSamplerWithResidueAlternatives & rigid_body_rotamer_with_residue_alternatives = *( static_cast< RigidBodyStepWiseSamplerWithResidueAlternatives * >( sampler.get() ) ); rigid_body_rotamer_with_residue_alternatives.fast_forward(); } } } //screener } //stepwise } //protocols
[ "achitturi17059@gmail.com" ]
achitturi17059@gmail.com
13c98eeb847b7fc93e3169df6485759d447df697
4fe0d1c3c54f434665302a5d0152e41596ce1304
/14 vector容器/14 vector容器/14 vector容器/06 vector互换容器.cpp
3bf53eb6a9fbd2062c2285aa6af1ac19d5098bbb
[]
no_license
ZP-GITHUB/studyCpp
f10677c48f5c0cec3f963e2a563ffc14cc279768
6e33baf77dc372a33bc43a1db9c9071d29ea4cac
refs/heads/master
2023-03-25T12:28:41.225480
2021-03-27T08:25:38
2021-03-27T08:25:38
278,849,114
0
0
null
null
null
null
GB18030
C++
false
false
971
cpp
#include<iostream> using namespace std; #include <vector> // 引用01文件里的方法 extern void printVector(vector<int>& v); void test06() { vector<int>v1; for (int i = 0; i < 10; i++) { v1.push_back(i); } printVector(v1); vector<int>v2; for (int i = 10; i > 0; i--) { v2.push_back(i); } printVector(v2); //互换容器 cout << "互换后" << endl; v1.swap(v2); printVector(v1); printVector(v2); } void test07() { vector<int> v; for (int i = 0; i < 100000; i++) { v.push_back(i); } cout << "v的容量为:" << v.capacity() << endl; cout << "v的大小为:" << v.size() << endl; v.resize(3); cout << "v的容量为:" << v.capacity() << endl; cout << "v的大小为:" << v.size() << endl; //收缩内存 vector<int>(v).swap(v); //匿名对象 cout << "v的容量为:" << v.capacity() << endl; cout << "v的大小为:" << v.size() << endl; } int main1406() { test06(); test07(); system("pause"); return 0; }
[ "991475623@qq.com" ]
991475623@qq.com
8548119eab18b3d280051757a8a82a3f2a939b6b
f5ecd45ff4c65f4805a580cfe9f58426bc610511
/tests/UnitTests/TestTransfers.cpp
6baf2fc0b0190c3f2cb68ccaabb960f18bdd3439
[ "MIT" ]
permissive
JacopoDT/numerare-core
3d0f115f4f557439ce821842abb32e5a22fd99af
a98b32150a9b2e6ea7535d12b7e8e1aac0589e2f
refs/heads/master
2021-06-28T08:32:45.221794
2020-08-30T23:50:22
2020-08-30T23:50:22
131,741,111
0
0
null
null
null
null
UTF-8
C++
false
false
12,758
cpp
/*** MIT License Copyright (c) 2018 NUMERARE 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. Parts of this file are originally Copyright (c) 2012-2017 The CryptoNote developers, The Bytecoin developers ***/ #include "gtest/gtest.h" #include "Transfers/BlockchainSynchronizer.h" #include "Transfers/TransfersSynchronizer.h" #include "INodeStubs.h" #include "TestBlockchainGenerator.h" #include "TransactionApiHelpers.h" #include "CryptoNoteCore/TransactionApi.h" #include <boost/scoped_array.hpp> #include <future> #include <algorithm> #include <numeric> #include <Logging/ConsoleLogger.h> using namespace CryptoNote; class TransfersObserver : public ITransfersObserver { public: virtual void onTransactionUpdated(ITransfersSubscription* object, const Hash& transactionHash) override { std::lock_guard<std::mutex> lk(m_mutex); m_transfers.emplace_back(transactionHash); } std::vector<Hash> m_transfers; std::mutex m_mutex; }; class TransfersApi : public ::testing::Test, public IBlockchainSynchronizerObserver { public: TransfersApi() : m_logger(Logging::ERROR), m_currency(CryptoNote::CurrencyBuilder(m_logger).currency()), generator(m_currency), m_node(generator), m_sync(m_node, m_logger, m_currency.genesisBlockHash()), m_transfersSync(m_currency, m_logger, m_sync, m_node) { } void addAccounts(size_t count) { while (count--) { m_accounts.push_back(generateAccountKeys()); } } void addPaymentAccounts(size_t count) { KeyPair p1; Crypto::generate_keys(p1.publicKey, p1.secretKey); auto viewKeys = p1; while (count--) { Crypto::generate_keys(p1.publicKey, p1.secretKey); m_accounts.push_back(accountKeysFromKeypairs(viewKeys, p1)); } } void addMinerAccount() { m_accounts.push_back(reinterpret_cast<const AccountKeys&>(generator.getMinerAccount())); } AccountSubscription createSubscription(size_t acc, uint64_t timestamp = 0) { const auto& keys = m_accounts[acc]; AccountSubscription sub; sub.keys = keys; sub.syncStart.timestamp = timestamp; sub.syncStart.height = 0; sub.transactionSpendableAge = 5; return sub; } void subscribeAccounts() { m_transferObservers.reset(new TransfersObserver[m_accounts.size()]); for (size_t i = 0; i < m_accounts.size(); ++i) { m_subscriptions.push_back(&m_transfersSync.addSubscription(createSubscription(i))); m_subscriptions.back()->addObserver(&m_transferObservers[i]); } } void startSync() { syncCompleted = std::promise<std::error_code>(); syncCompletedFuture = syncCompleted.get_future(); m_sync.addObserver(this); m_sync.start(); syncCompletedFuture.get(); m_sync.removeObserver(this); } void refreshSync() { syncCompleted = std::promise<std::error_code>(); syncCompletedFuture = syncCompleted.get_future(); m_sync.addObserver(this); m_sync.lastKnownBlockHeightUpdated(0); syncCompletedFuture.get(); m_sync.removeObserver(this); } void synchronizationCompleted(std::error_code result) override { decltype(syncCompleted) detachedPromise = std::move(syncCompleted); detachedPromise.set_value(result); } void generateMoneyForAccount(size_t idx) { generator.getBlockRewardForAddress( reinterpret_cast<const CryptoNote::AccountPublicAddress&>(m_accounts[idx].address)); } std::error_code submitTransaction(ITransactionReader& tx) { auto data = tx.getTransactionData(); Transaction outTx; CryptoNote::fromBinaryArray(outTx, data); std::promise<std::error_code> result; m_node.relayTransaction(outTx, [&result](std::error_code ec) { std::promise<std::error_code> detachedPromise = std::move(result); detachedPromise.set_value(ec); }); return result.get_future().get(); } protected: boost::scoped_array<TransfersObserver> m_transferObservers; std::vector<AccountKeys> m_accounts; std::vector<ITransfersSubscription*> m_subscriptions; Logging::ConsoleLogger m_logger; CryptoNote::Currency m_currency; TestBlockchainGenerator generator; INodeTrivialRefreshStub m_node; BlockchainSynchronizer m_sync; TransfersSyncronizer m_transfersSync; std::promise<std::error_code> syncCompleted; std::future<std::error_code> syncCompletedFuture; }; namespace CryptoNote { inline bool operator == (const TransactionOutputInformation& t1, const TransactionOutputInformation& t2) { return t1.type == t2.type && t1.amount == t2.amount && t1.outputInTransaction == t2.outputInTransaction && t1.transactionPublicKey == t2.transactionPublicKey; } } TEST_F(TransfersApi, testSubscriptions) { addAccounts(1); m_transfersSync.addSubscription(createSubscription(0)); std::vector<AccountPublicAddress> subscriptions; m_transfersSync.getSubscriptions(subscriptions); const auto& addr = m_accounts[0].address; ASSERT_EQ(1, subscriptions.size()); ASSERT_EQ(addr, subscriptions[0]); ASSERT_TRUE(m_transfersSync.getSubscription(addr) != 0); ASSERT_TRUE(m_transfersSync.removeSubscription(addr)); subscriptions.clear(); m_transfersSync.getSubscriptions(subscriptions); ASSERT_EQ(0, subscriptions.size()); } TEST_F(TransfersApi, syncOneBlock) { addAccounts(2); subscribeAccounts(); generator.getBlockRewardForAddress(m_accounts[0].address); generator.generateEmptyBlocks(15); startSync(); auto& tc1 = m_transfersSync.getSubscription(m_accounts[0].address)->getContainer(); auto& tc2 = m_transfersSync.getSubscription(m_accounts[1].address)->getContainer(); ASSERT_NE(&tc1, &tc2); ASSERT_GT(tc1.balance(ITransfersContainer::IncludeAll), 0); ASSERT_GT(tc1.transfersCount(), 0); ASSERT_EQ(0, tc2.transfersCount()); } TEST_F(TransfersApi, syncMinerAcc) { addMinerAccount(); subscribeAccounts(); generator.generateEmptyBlocks(10); startSync(); ASSERT_NE(0, m_subscriptions[0]->getContainer().transfersCount()); } namespace { std::unique_ptr<ITransaction> createMoneyTransfer( uint64_t amount, uint64_t fee, const AccountKeys& senderKeys, const AccountPublicAddress& reciever, ITransfersContainer& tc) { std::vector<TransactionOutputInformation> transfers; tc.getOutputs(transfers, ITransfersContainer::IncludeAllUnlocked); auto tx = createTransaction(); std::vector<std::pair<TransactionTypes::InputKeyInfo, KeyPair>> inputs; uint64_t foundMoney = 0; for (const auto& t : transfers) { TransactionTypes::InputKeyInfo info; info.amount = t.amount; TransactionTypes::GlobalOutput globalOut; globalOut.outputIndex = t.globalOutputIndex; globalOut.targetKey = t.outputKey; info.outputs.push_back(globalOut); info.realOutput.outputInTransaction = t.outputInTransaction; info.realOutput.transactionIndex = 0; info.realOutput.transactionPublicKey = t.transactionPublicKey; KeyPair kp; tx->addInput(senderKeys, info, kp); inputs.push_back(std::make_pair(info, kp)); foundMoney += info.amount; if (foundMoney >= amount + fee) { break; } } // output to reciever tx->addOutput(amount, reciever); // change uint64_t change = foundMoney - amount - fee; if (change) { tx->addOutput(change, senderKeys.address); } for (size_t inputIdx = 0; inputIdx < inputs.size(); ++inputIdx) { tx->signInputKey(inputIdx, inputs[inputIdx].first, inputs[inputIdx].second); } return tx; } } TEST_F(TransfersApi, moveMoney) { addMinerAccount(); addAccounts(2); subscribeAccounts(); generator.generateEmptyBlocks(2 * m_currency.minedMoneyUnlockWindow()); // sendAmount is an even number auto& transaction = generator.getBlockchain()[1].baseTransaction; uint64_t sendAmount = std::accumulate( transaction.outputs.begin(), transaction.outputs.end(), UINT64_C(0), [](uint64_t sum, const decltype(transaction.outputs)::value_type& output) { return sum + output.amount; }); sendAmount = (sendAmount / 4) * 2; auto fee = m_currency.minimumFee(); startSync(); auto& tc0 = m_subscriptions[0]->getContainer(); ASSERT_LE(sendAmount, tc0.balance(ITransfersContainer::IncludeAllUnlocked)); auto tx = createMoneyTransfer(sendAmount, fee, m_accounts[0], m_accounts[1].address, tc0); submitTransaction(*tx); refreshSync(); ASSERT_EQ(1, m_transferObservers[1].m_transfers.size()); ASSERT_EQ(tx->getTransactionHash(), m_transferObservers[1].m_transfers[0]); auto& tc1 = m_subscriptions[1]->getContainer(); ASSERT_EQ(sendAmount, tc1.balance(ITransfersContainer::IncludeAll)); ASSERT_EQ(0, tc1.balance(ITransfersContainer::IncludeAllUnlocked)); generator.generateEmptyBlocks(m_currency.minedMoneyUnlockWindow()); // unlock money refreshSync(); ASSERT_EQ(sendAmount, tc1.balance(ITransfersContainer::IncludeAllUnlocked)); auto tx2 = createMoneyTransfer(sendAmount / 2, fee, m_accounts[1], m_accounts[2].address, tc1); submitTransaction(*tx2); refreshSync(); ASSERT_EQ(2, m_transferObservers[1].m_transfers.size()); ASSERT_EQ(tx2->getTransactionHash(), m_transferObservers[1].m_transfers.back()); ASSERT_EQ(sendAmount / 2 - fee, m_subscriptions[1]->getContainer().balance(ITransfersContainer::IncludeAll)); ASSERT_EQ(sendAmount / 2, m_subscriptions[2]->getContainer().balance(ITransfersContainer::IncludeAll)); } struct lessOutKey { bool operator()(const TransactionOutputInformation& t1, const TransactionOutputInformation& t2) { return std::hash<PublicKey>()(t1.outputKey) < std::hash<PublicKey>()(t2.outputKey); } }; bool compareStates(TransfersSyncronizer& sync1, TransfersSyncronizer& sync2) { std::vector<AccountPublicAddress> subs; sync1.getSubscriptions(subs); for (const auto& s : subs) { auto& tc1 = sync1.getSubscription(s)->getContainer(); if (sync2.getSubscription(s) == nullptr) return false; auto& tc2 = sync2.getSubscription(s)->getContainer(); std::vector<TransactionOutputInformation> out1; std::vector<TransactionOutputInformation> out2; tc1.getOutputs(out1); tc2.getOutputs(out2); std::sort(out1.begin(), out1.end(), lessOutKey()); std::sort(out2.begin(), out2.end(), lessOutKey()); if (out1 != out2) return false; } return true; } TEST_F(TransfersApi, state) { addMinerAccount(); subscribeAccounts(); generator.generateEmptyBlocks(20); startSync(); m_sync.stop(); std::stringstream memstm; m_transfersSync.save(memstm); m_sync.start(); BlockchainSynchronizer bsync2(m_node, m_logger, m_currency.genesisBlockHash()); TransfersSyncronizer sync2(m_currency, m_logger, bsync2, m_node); for (size_t i = 0; i < m_accounts.size(); ++i) { sync2.addSubscription(createSubscription(i)); } sync2.load(memstm); // compare transfers ASSERT_TRUE(compareStates(m_transfersSync, sync2)); // generate more blocks generator.generateEmptyBlocks(10); refreshSync(); syncCompleted = std::promise<std::error_code>(); syncCompletedFuture = syncCompleted.get_future(); bsync2.addObserver(this); bsync2.start(); syncCompletedFuture.get(); bsync2.removeObserver(this); // check again ASSERT_TRUE(compareStates(m_transfersSync, sync2)); } TEST_F(TransfersApi, sameTrackingKey) { size_t offset = 2; // miner account + ordinary account size_t paymentAddresses = 1000; size_t payments = 10; addMinerAccount(); addAccounts(1); addPaymentAccounts(paymentAddresses); subscribeAccounts(); for (size_t i = 0; i < payments; ++i) { generateMoneyForAccount(i + offset); } startSync(); for (size_t i = 0; i < payments; ++i) { auto sub = m_subscriptions[offset + i]; EXPECT_NE(0, sub->getContainer().balance(ITransfersContainer::IncludeAll)); } }
[ "38866023+numerare@users.noreply.github.com" ]
38866023+numerare@users.noreply.github.com
3f6ddd8809918945e25f7d68fdc00558d679e6bb
a18b38806ac1fd4877dae3ee17359ac2edafe4e6
/src/network.h
3beb18cdbb9ad31fcac2797d85fecd0ef7bfd2f1
[]
no_license
isghe/green_qt
34cf3dbfdb114fc9d6db127d34bfdcd47aafe074
48c2c617660ef261744cd316c87ef60cca91d4b2
refs/heads/master
2020-12-12T04:26:26.254400
2020-01-03T19:41:33
2020-01-13T14:15:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
957
h
#ifndef GREEN_NETWORK_H #define GREEN_NETWORK_H #include <QJsonObject> #include <QObject> #include <QQmlListProperty> class Network; class NetworkManager; class NetworkManager : public QObject { Q_OBJECT Q_PROPERTY(QQmlListProperty<Network> networks READ networks CONSTANT) public: static NetworkManager* instance(); QQmlListProperty<Network> networks(); Network* network(const QString& id) const; private: explicit NetworkManager(); QList<Network*> m_networks; }; class Network : public QObject { Q_OBJECT Q_PROPERTY(QString id READ id CONSTANT) Q_PROPERTY(QString name READ name CONSTANT) public: Network(const QJsonObject& data, NetworkManager* manager); QString id() const { return m_id; } QString name() const { return m_name; } void openTransactionInExplorer(const QString& hash); private: QJsonObject m_data; QString m_id; QString m_name; }; #endif // GREEN_NETWORK_H
[ "borgbyte@gmail.com" ]
borgbyte@gmail.com
3abc0c142f85d4fe42e038300dfdce5449de1d5d
f375c29bb5f8ed5b9704785e591c02887d0a3170
/src/Magnum/Implementation/TextureState.h
ed1dfcc88f550498192439123228c957ed5ef803
[ "MIT" ]
permissive
kylinxh/magnum
5160177fc715b2c724354929dd0e2330c2d64dea
c25c6031e241deaaef66756db90ca749b3e64e9c
refs/heads/master
2021-01-12T13:54:28.027462
2016-03-25T18:24:28
2016-03-25T18:24:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,729
h
#ifndef Magnum_Implementation_TextureState_h #define Magnum_Implementation_TextureState_h /* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016 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 <string> #include <vector> #include <Corrade/Containers/Array.h> #include "Magnum/CubeMapTexture.h" #if defined(_MSC_VER) && !defined(MAGNUM_TARGET_GLES2) /* Otherwise the member function pointers will have different size based on whether the header was included or not. CAUSES SERIOUS MEMORY CORRUPTION AND IS NOT CAUGHT BY ANY WARNING WHATSOEVER! AARGH! */ #include "Magnum/BufferTexture.h" #endif namespace Magnum { namespace Implementation { struct TextureState { explicit TextureState(Context& context, std::vector<std::string>& extensions); ~TextureState(); void reset(); Int(*compressedBlockDataSizeImplementation)(GLenum, TextureFormat); void(*unbindImplementation)(GLint); void(*bindMultiImplementation)(GLint, Containers::ArrayView<AbstractTexture* const>); void(AbstractTexture::*createImplementation)(); void(AbstractTexture::*bindImplementation)(GLint); void(AbstractTexture::*parameteriImplementation)(GLenum, GLint); void(AbstractTexture::*parameterfImplementation)(GLenum, GLfloat); #ifndef MAGNUM_TARGET_GLES2 void(AbstractTexture::*parameterivImplementation)(GLenum, const GLint*); #endif void(AbstractTexture::*parameterfvImplementation)(GLenum, const GLfloat*); #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) void(AbstractTexture::*parameterIuivImplementation)(GLenum, const GLuint*); void(AbstractTexture::*parameterIivImplementation)(GLenum, const GLint*); #endif void(AbstractTexture::*setMaxAnisotropyImplementation)(GLfloat); #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) void(AbstractTexture::*getLevelParameterivImplementation)(GLint, GLenum, GLint*); #endif void(AbstractTexture::*mipmapImplementation)(); #ifndef MAGNUM_TARGET_GLES void(AbstractTexture::*storage1DImplementation)(GLsizei, TextureFormat, const Math::Vector<1, GLsizei>&); #endif void(AbstractTexture::*storage2DImplementation)(GLsizei, TextureFormat, const Vector2i&); #if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) void(AbstractTexture::*storage3DImplementation)(GLsizei, TextureFormat, const Vector3i&); #endif #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) void(AbstractTexture::*storage2DMultisampleImplementation)(GLsizei, TextureFormat, const Vector2i&, GLboolean); void(AbstractTexture::*storage3DMultisampleImplementation)(GLsizei, TextureFormat, const Vector3i&, GLboolean); #endif #ifndef MAGNUM_TARGET_GLES void(AbstractTexture::*getImageImplementation)(GLint, PixelFormat, PixelType, std::size_t, GLvoid*); void(AbstractTexture::*getCompressedImageImplementation)(GLint, std::size_t, GLvoid*); #endif #ifndef MAGNUM_TARGET_GLES void(AbstractTexture::*subImage1DImplementation)(GLint, const Math::Vector<1, GLint>&, const Math::Vector<1, GLsizei>&, PixelFormat, PixelType, const GLvoid*); void(AbstractTexture::*compressedSubImage1DImplementation)(GLint, const Math::Vector<1, GLint>&, const Math::Vector<1, GLsizei>&, CompressedPixelFormat, const GLvoid*, GLsizei); #endif void(AbstractTexture::*subImage2DImplementation)(GLint, const Vector2i&, const Vector2i&, PixelFormat, PixelType, const GLvoid*); void(AbstractTexture::*compressedSubImage2DImplementation)(GLint, const Vector2i&, const Vector2i&, CompressedPixelFormat, const GLvoid*, GLsizei); #if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) void(AbstractTexture::*subImage3DImplementation)(GLint, const Vector3i&, const Vector3i&, PixelFormat, PixelType, const GLvoid*); void(AbstractTexture::*compressedSubImage3DImplementation)(GLint, const Vector3i&, const Vector3i&, CompressedPixelFormat, const GLvoid*, GLsizei); #endif void(AbstractTexture::*invalidateImageImplementation)(GLint); void(AbstractTexture::*invalidateSubImageImplementation)(GLint, const Vector3i&, const Vector3i&); #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) void(BufferTexture::*setBufferImplementation)(BufferTextureFormat, Buffer&); void(BufferTexture::*setBufferRangeImplementation)(BufferTextureFormat, Buffer&, GLintptr, GLsizeiptr); #endif #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) void(CubeMapTexture::*getCubeLevelParameterivImplementation)(GLint, GLenum, GLint*); #endif #ifndef MAGNUM_TARGET_GLES GLint(CubeMapTexture::*getCubeLevelCompressedImageSizeImplementation)(GLint); void(CubeMapTexture::*getCubeImageImplementation)(CubeMapTexture::Coordinate, GLint, const Vector2i&, PixelFormat, PixelType, std::size_t, GLvoid*); void(CubeMapTexture::*getFullCompressedCubeImageImplementation)(GLint, const Vector2i&, std::size_t, std::size_t, GLvoid*); void(CubeMapTexture::*getCompressedCubeImageImplementation)(CubeMapTexture::Coordinate, GLint, const Vector2i&, std::size_t, GLvoid*); #endif void(CubeMapTexture::*cubeSubImageImplementation)(CubeMapTexture::Coordinate, GLint, const Vector2i&, const Vector2i&, PixelFormat, PixelType, const GLvoid*); void(CubeMapTexture::*cubeCompressedSubImageImplementation)(CubeMapTexture::Coordinate, GLint, const Vector2i&, const Vector2i&, CompressedPixelFormat, const GLvoid*, GLsizei); GLint maxSize, #if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) max3DSize, #endif maxCubeMapSize; #ifndef MAGNUM_TARGET_GLES2 GLint maxArrayLayers; #endif #ifndef MAGNUM_TARGET_GLES GLint maxRectangleSize; #endif #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) GLint maxBufferSize; #endif GLint maxTextureUnits; #ifndef MAGNUM_TARGET_GLES2 GLfloat maxLodBias; #endif GLfloat maxMaxAnisotropy; GLint currentTextureUnit; #ifndef MAGNUM_TARGET_GLES2 GLint maxColorSamples, maxDepthSamples, maxIntegerSamples; #endif #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) GLint bufferOffsetAlignment; #endif Containers::Array<std::pair<GLenum, GLuint>> bindings; #if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) /* Texture object ID, level, layered, layer, access */ Containers::Array<std::tuple<GLuint, GLint, GLboolean, GLint, GLenum>> imageBindings; #endif }; }} #endif
[ "mosra@centrum.cz" ]
mosra@centrum.cz
a1528e2731f424385cfc9fa28ce66742c487fccf
d7cf5f5d7822934f553e81ecd6c5f04270543138
/include/system.h
8aee8ca7950427f2350491c111aabaf932a82e3c
[ "MIT" ]
permissive
ajaypatil108/Linux-System-Monitor
00ba22730fba01323ca470702c2c8ff82ecacda3
6245111e105c5258092b6623a7504668071e738c
refs/heads/master
2022-11-10T21:13:29.983128
2020-07-02T21:02:54
2020-07-02T21:02:54
273,831,843
0
0
null
null
null
null
UTF-8
C++
false
false
638
h
#ifndef SYSTEM_H #define SYSTEM_H #include <string> #include <vector> #include "process.h" #include "processor.h" class System { public: Processor& Cpu(); std::vector<Process>& Processes(); float MemoryUtilization(); long UpTime(); int TotalProcesses(); int RunningProcesses(); std::string Kernel(); std::string OperatingSystem(); private: // Defining two private variables (1) Storing instance of processor and (2) Container of processes objects Processor cpu_; std::vector<Process> processes_; }; #endif
[ "ajaypatil15@gmail.com" ]
ajaypatil15@gmail.com
2e2300c2542216aead294ec39e06e53c2fc41b2d
76dd4afa63880b3b95a39b8a640c240f1f6ece60
/hello world.cpp
e3e505f01692329e07930462b185c93877c11880
[]
no_license
wangchiyucheng/C-study
e6dfd2dd362c1b3ab26505c38aae61045199de0e
cd8a3f61219be16ca7b5efbcc5504110cbce045d
refs/heads/master
2020-05-07T09:53:38.547212
2019-04-22T01:40:55
2019-04-22T01:40:55
180,395,927
0
0
null
null
null
null
EUC-JP
C++
false
false
227
cpp
#include<stdio.h> int main() { printf("*****************************\n"); printf("* C programming  *\n"); printf("* Hello world!     *\n"); printf("*****************************\n"); return 0; }
[ "1132209031@qq.com" ]
1132209031@qq.com
772654fd077bd4bc88d055785ffc196c7599772d
e6d01b5a08f5ea9562376111f927bd8f59589408
/TrollLanguage/TokenParser.hpp
0340a653d66bbd60ba75c09bf9e12b0eab046ac7
[]
no_license
stories2/TrollLanguage
1e2f4e0e511efb96a9e22a68687de2bd97b11b7a
17d601b677f9706a73499cfff98572f595ca5ce1
refs/heads/master
2021-01-18T19:45:19.058045
2017-04-02T06:10:27
2017-04-02T06:10:27
86,912,167
0
0
null
null
null
null
UTF-8
C++
false
false
298
hpp
// // TokenParser.hpp // TrollLanguage // // Created by 김현우 on 2017. 4. 2.. // Copyright © 2017년 김현우. All rights reserved. // #ifndef TokenParser_hpp #define TokenParser_hpp #include <iostream> class TokenParser { public: void TestFunc(); }; #endif /* TokenParser_hpp */
[ "stories2@gimhyeon-uui-MacBook-Pro.local" ]
stories2@gimhyeon-uui-MacBook-Pro.local
bb51cd02c6a580b18948275db6aac925e27d8190
fd5d9b06845d9d1829dfdefb2f1a3526cc093c2f
/tests/pcre2test/Source.cpp
f0b33b7529e7a4458d6f9c855f2544eb8d73be03
[]
no_license
meli-mira/pcre2-opcodes
ceaad28ca05d577d25cfcd0bde269908b247a81d
899a44ffe6a16a21fd7406a6482f8c4a60d5a305
refs/heads/master
2021-04-05T13:38:59.912914
2020-03-19T18:07:06
2020-03-19T18:07:06
248,562,283
0
0
null
null
null
null
UTF-8
C++
false
false
20,460
cpp
/************************************************* * PCRE2 DEMONSTRATION PROGRAM * *************************************************/ /* This is a demonstration program to illustrate a straightforward way of using the PCRE2 regular expression library from a C program. See the pcre2sample documentation for a short discussion ("man pcre2sample" if you have the PCRE2 man pages installed). PCRE2 is a revised API for the library, and is incompatible with the original PCRE API. There are actually three libraries, each supporting a different code unit width. This demonstration program uses the 8-bit library. The default is to process each code unit as a separate character, but if the pattern begins with "(*UTF)", both it and the subject are treated as UTF-8 strings, where characters may occupy multiple code units. In Unix-like environments, if PCRE2 is installed in your standard system libraries, you should be able to compile this program using this command: cc -Wall pcre2demo.c -lpcre2-8 -o pcre2demo If PCRE2 is not installed in a standard place, it is likely to be installed with support for the pkg-config mechanism. If you have pkg-config, you can compile this program using this command: cc -Wall pcre2demo.c `pkg-config --cflags --libs libpcre2-8` -o pcre2demo If you do not have pkg-config, you may have to use something like this: cc -Wall pcre2demo.c -I/usr/local/include -L/usr/local/lib \ -R/usr/local/lib -lpcre2-8 -o pcre2demo Replace "/usr/local/include" and "/usr/local/lib" with wherever the include and library files for PCRE2 are installed on your system. Only some operating systems (Solaris is one) use the -R option. Building under Windows: If you want to statically link this program against a non-dll .a file, you must define PCRE2_STATIC before including pcre2.h, so in this environment, uncomment the following line. */ /* #define PCRE2_STATIC */ /* The PCRE2_CODE_UNIT_WIDTH macro must be defined before including pcre2.h. For a program that uses only one code unit width, setting it to 8, 16, or 32 makes it possible to use generic function names such as pcre2_compile(). Note that just changing 8 to 16 (for example) is not sufficient to convert this program to process 16-bit characters. Even in a fully 16-bit environment, where string-handling functions such as strcmp() and printf() work with 16-bit characters, the code for handling the table of named substrings will still need to be modified. */ #define PCRE2_CODE_UNIT_WIDTH 8 #include <stdio.h> #include <string.h> #include <pcre2.h> /************************************************************************** * Here is the program. The API includes the concept of "contexts" for * * setting up unusual interface requirements for compiling and matching, * * such as custom memory managers and non-standard newline definitions. * * This program does not do any of this, so it makes no use of contexts, * * always passing NULL where a context could be given. * **************************************************************************/ int main(int argc, char **argv) { pcre2_code *re, *re2; PCRE2_SPTR pattern,patern2; /* PCRE2_SPTR is a pointer to unsigned code units of */ PCRE2_SPTR subject; /* the appropriate width (in this case, 8 bits). */ PCRE2_SPTR name_table; int crlf_is_newline; int errornumber; int find_all; int i; int rc; int utf8; uint32_t option_bits; uint32_t namecount; uint32_t name_entry_size; uint32_t newline; PCRE2_SIZE erroroffset; PCRE2_SIZE *ovector; size_t subject_length; pcre2_match_data *match_data; /************************************************************************** * First, sort out the command line. There is only one possible option at * * the moment, "-g" to request repeated matching to find all occurrences, * * like Perl's /g option. We set the variable find_all to a non-zero value * * if the -g option is present. * **************************************************************************/ find_all = 0; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-g") == 0) find_all = 1; else if (argv[i][0] == '-') { printf("Unrecognised option %s\n", argv[i]); return 1; } else break; } /* After the options, we require exactly two arguments, which are the pattern, and the subject string. */ /*if (argc - i != 2) { printf("Exactly two arguments required: a regex and a subject string\n"); return 1; }*/ /* As pattern and subject are char arguments, they can be straightforwardly cast to PCRE2_SPTR as we are working in 8-bit code units. */ pattern = (PCRE2_SPTR)"^NetBus\\s+\\d+\\x2E\\\d+"; patern2 = (PCRE2_SPTR)"[1-9]"; subject = (PCRE2_SPTR)"ea est. Mirabela 2tata e est"; subject_length = strlen((char *)subject); /************************************************************************* * Now we are going to compile the regular expression pattern, and handle * * any errors that are detected. * *************************************************************************/ re = pcre2_compile( pattern, /* the pattern */ PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */ 0, /* default options */ &errornumber, /* for error number */ &erroroffset, /* for error offset */ NULL); /* use default compile context */ /* Compilation failed: print the error message and exit. */ if (re == NULL) { PCRE2_UCHAR buffer[256]; pcre2_get_error_message(errornumber, buffer, sizeof(buffer)); printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset, buffer); return 1; } re2 = pcre2_compile( patern2, /* the pattern */ PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */ 0, /* default options */ &errornumber, /* for error number */ &erroroffset, /* for error offset */ NULL); /* use default compile context */ /* Compilation failed: print the error message and exit. */ if (re2 == NULL) { PCRE2_UCHAR buffer[256]; pcre2_get_error_message(errornumber, buffer, sizeof(buffer)); printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset, buffer); return 1; } FILE *f = fopen("opcodes.bin", "wb"); uint8_t *bytes; PCRE2_SIZE bytescount; const pcre2_code *list_of_codes[2]; list_of_codes[0] = re; list_of_codes[1] = re2; int errorcode = pcre2_serialize_encode(list_of_codes, 2, &bytes, &bytescount, NULL); fwrite(bytes, 1, bytescount, f); fclose(f); /************************************************************************* * If the compilation succeeded, we call PCRE again, in order to do a * * pattern match against the subject string. This does just ONE match. If * * further matching is needed, it will be done below. Before running the * * match we must set up a match_data block for holding the result. * *************************************************************************/ /* Using this function ensures that the block is exactly the right size for the number of capturing parentheses in the pattern. */ match_data = pcre2_match_data_create_from_pattern(re, NULL); rc = pcre2_match( re, /* the compiled pattern */ subject, /* the subject string */ subject_length, /* the length of the subject */ 0, /* start at offset 0 in the subject */ 0, /* default options */ match_data, /* block for storing the result */ NULL); /* use default match context */ /* Matching failed: handle error cases */ if (rc < 0) { switch (rc) { case PCRE2_ERROR_NOMATCH: printf("No match\n"); break; /* Handle other special cases if you like */ default: printf("Matching error %d\n", rc); break; } pcre2_match_data_free(match_data); /* Release memory used for the match */ pcre2_code_free(re); /* data and the compiled pattern. */ return 1; } /* Match succeded. Get a pointer to the output vector, where string offsets are stored. */ ovector = pcre2_get_ovector_pointer(match_data); printf("Match succeeded at offset %d\n", (int)ovector[0]); /************************************************************************* * We have found the first match within the subject string. If the output * * vector wasn't big enough, say so. Then output any substrings that were * * captured. * *************************************************************************/ /* The output vector wasn't big enough. This should not happen, because we used pcre2_match_data_create_from_pattern() above. */ if (rc == 0) printf("ovector was not big enough for all the captured substrings\n"); /* We must guard against patterns such as /(?=.\K)/ that use \K in an assertion to set the start of a match later than its end. In this demonstration program, we just detect this case and give up. */ if (ovector[0] > ovector[1]) { printf("\\K was used in an assertion to set the match start after its end.\n" "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]), (char *)(subject + ovector[1])); printf("Run abandoned\n"); pcre2_match_data_free(match_data); pcre2_code_free(re); return 1; } /* Show substrings stored in the output vector by number. Obviously, in a real application you might want to do things other than print them. */ for (i = 0; i < rc; i++) { PCRE2_SPTR substring_start = subject + ovector[2 * i]; size_t substring_length = ovector[2 * i + 1] - ovector[2 * i]; printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start); } /************************************************************************** * That concludes the basic part of this demonstration program. We have * * compiled a pattern, and performed a single match. The code that follows * * shows first how to access named substrings, and then how to code for * * repeated matches on the same subject. * **************************************************************************/ /* See if there are any named substrings, and if so, show them by name. First we have to extract the count of named parentheses from the pattern. */ (void)pcre2_pattern_info( re, /* the compiled pattern */ PCRE2_INFO_NAMECOUNT, /* get the number of named substrings */ &namecount); /* where to put the answer */ if (namecount == 0) printf("No named substrings\n"); else { PCRE2_SPTR tabptr; printf("Named substrings\n"); /* Before we can access the substrings, we must extract the table for translating names to numbers, and the size of each entry in the table. */ (void)pcre2_pattern_info( re, /* the compiled pattern */ PCRE2_INFO_NAMETABLE, /* address of the table */ &name_table); /* where to put the answer */ (void)pcre2_pattern_info( re, /* the compiled pattern */ PCRE2_INFO_NAMEENTRYSIZE, /* size of each entry in the table */ &name_entry_size); /* where to put the answer */ /* Now we can scan the table and, for each entry, print the number, the name, and the substring itself. In the 8-bit library the number is held in two bytes, most significant first. */ tabptr = name_table; for (i = 0; i < namecount; i++) { int n = (tabptr[0] << 8) | tabptr[1]; printf("(%d) %*s: %.*s\n", n, name_entry_size - 3, tabptr + 2, (int)(ovector[2 * n + 1] - ovector[2 * n]), subject + ovector[2 * n]); tabptr += name_entry_size; } } /************************************************************************* * If the "-g" option was given on the command line, we want to continue * * to search for additional matches in the subject string, in a similar * * way to the /g option in Perl. This turns out to be trickier than you * * might think because of the possibility of matching an empty string. * * What happens is as follows: * * * * If the previous match was NOT for an empty string, we can just start * * the next match at the end of the previous one. * * * * If the previous match WAS for an empty string, we can't do that, as it * * would lead to an infinite loop. Instead, a call of pcre2_match() is * * made with the PCRE2_NOTEMPTY_ATSTART and PCRE2_ANCHORED flags set. The * * first of these tells PCRE2 that an empty string at the start of the * * subject is not a valid match; other possibilities must be tried. The * * second flag restricts PCRE2 to one match attempt at the initial string * * position. If this match succeeds, an alternative to the empty string * * match has been found, and we can print it and proceed round the loop, * * advancing by the length of whatever was found. If this match does not * * succeed, we still stay in the loop, advancing by just one character. * * In UTF-8 mode, which can be set by (*UTF) in the pattern, this may be * * more than one byte. * * * * However, there is a complication concerned with newlines. When the * * newline convention is such that CRLF is a valid newline, we must * * advance by two characters rather than one. The newline convention can * * be set in the regex by (*CR), etc.; if not, we must find the default. * *************************************************************************/ if (!find_all) /* Check for -g */ { pcre2_match_data_free(match_data); /* Release the memory that was used */ pcre2_code_free(re); /* for the match data and the pattern. */ return 0; /* Exit the program. */ } /* Before running the loop, check for UTF-8 and whether CRLF is a valid newline sequence. First, find the options with which the regex was compiled and extract the UTF state. */ (void)pcre2_pattern_info(re, PCRE2_INFO_ALLOPTIONS, &option_bits); utf8 = (option_bits & PCRE2_UTF) != 0; /* Now find the newline convention and see whether CRLF is a valid newline sequence. */ (void)pcre2_pattern_info(re, PCRE2_INFO_NEWLINE, &newline); crlf_is_newline = newline == PCRE2_NEWLINE_ANY || newline == PCRE2_NEWLINE_CRLF || newline == PCRE2_NEWLINE_ANYCRLF; /* Loop for second and subsequent matches */ for (;;) { uint32_t options = 0; /* Normally no options */ PCRE2_SIZE start_offset = ovector[1]; /* Start at end of previous match */ /* If the previous match was for an empty string, we are finished if we are at the end of the subject. Otherwise, arrange to run another match at the same point to see if a non-empty match can be found. */ if (ovector[0] == ovector[1]) { if (ovector[0] == subject_length) break; options = PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED; } /* If the previous match was not an empty string, there is one tricky case to consider. If a pattern contains \K within a lookbehind assertion at the start, the end of the matched string can be at the offset where the match started. Without special action, this leads to a loop that keeps on matching the same substring. We must detect this case and arrange to move the start on by one character. The pcre2_get_startchar() function returns the starting offset that was passed to pcre2_match(). */ else { PCRE2_SIZE startchar = pcre2_get_startchar(match_data); if (start_offset <= startchar) { if (startchar >= subject_length) break; /* Reached end of subject. */ start_offset = startchar + 1; /* Advance by one character. */ if (utf8) /* If UTF-8, it may be more */ { /* than one code unit. */ for (; start_offset < subject_length; start_offset++) if ((subject[start_offset] & 0xc0) != 0x80) break; } } } /* Run the next matching operation */ rc = pcre2_match( re, /* the compiled pattern */ subject, /* the subject string */ subject_length, /* the length of the subject */ start_offset, /* starting offset in the subject */ options, /* options */ match_data, /* block for storing the result */ NULL); /* use default match context */ /* This time, a result of NOMATCH isn't an error. If the value in "options" is zero, it just means we have found all possible matches, so the loop ends. Otherwise, it means we have failed to find a non-empty-string match at a point where there was a previous empty-string match. In this case, we do what Perl does: advance the matching position by one character, and continue. We do this by setting the "end of previous match" offset, because that is picked up at the top of the loop as the point at which to start again. There are two complications: (a) When CRLF is a valid newline sequence, and the current position is just before it, advance by an extra byte. (b) Otherwise we must ensure that we skip an entire UTF character if we are in UTF mode. */ if (rc == PCRE2_ERROR_NOMATCH) { if (options == 0) break; /* All matches found */ ovector[1] = start_offset + 1; /* Advance one code unit */ if (crlf_is_newline && /* If CRLF is a newline & */ start_offset < subject_length - 1 && /* we are at CRLF, */ subject[start_offset] == '\r' && subject[start_offset + 1] == '\n') ovector[1] += 1; /* Advance by one more. */ else if (utf8) /* Otherwise, ensure we */ { /* advance a whole UTF-8 */ while (ovector[1] < subject_length) /* character. */ { if ((subject[ovector[1]] & 0xc0) != 0x80) break; ovector[1] += 1; } } continue; /* Go round the loop again */ } /* Other matching errors are not recoverable. */ if (rc < 0) { printf("Matching error %d\n", rc); pcre2_match_data_free(match_data); pcre2_code_free(re); return 1; } /* Match succeded */ printf("\nMatch succeeded again at offset %d\n", (int)ovector[0]); /* The match succeeded, but the output vector wasn't big enough. This should not happen. */ if (rc == 0) printf("ovector was not big enough for all the captured substrings\n"); /* We must guard against patterns such as /(?=.\K)/ that use \K in an assertion to set the start of a match later than its end. In this demonstration program, we just detect this case and give up. */ if (ovector[0] > ovector[1]) { printf("\\K was used in an assertion to set the match start after its end.\n" "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]), (char *)(subject + ovector[1])); printf("Run abandoned\n"); pcre2_match_data_free(match_data); pcre2_code_free(re); return 1; } /* As before, show substrings stored in the output vector by number, and then also any named substrings. */ for (i = 0; i < rc; i++) { PCRE2_SPTR substring_start = subject + ovector[2 * i]; size_t substring_length = ovector[2 * i + 1] - ovector[2 * i]; printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start); } if (namecount == 0) printf("No named substrings\n"); else { PCRE2_SPTR tabptr = name_table; printf("Named substrings\n"); for (i = 0; i < namecount; i++) { int n = (tabptr[0] << 8) | tabptr[1]; printf("(%d) %*s: %.*s\n", n, name_entry_size - 3, tabptr + 2, (int)(ovector[2 * n + 1] - ovector[2 * n]), subject + ovector[2 * n]); tabptr += name_entry_size; } } } /* End of loop to find second and subsequent matches */ printf("\n"); pcre2_match_data_free(match_data); pcre2_code_free(re); return 0; } /* End of pcre2demo.c */
[ "medvei.mira@gmail.com" ]
medvei.mira@gmail.com
65069519d9260a42033eb331cf95c02413237045
2f83c1837cbb938130e8d16e2c4a5eadd4f7258e
/controller.h
fcbbffb446e7a17437f1df5ad67581b8f88a75d7
[]
no_license
MarinaMeyta/qthreads
ae0c33721fe001961b16841834eb609ecdf5c96f
f022c5f5b06d92b7467290115e8a3d6336f9c9d5
refs/heads/master
2021-03-08T19:29:48.929672
2016-05-01T14:36:49
2016-05-01T14:36:49
56,851,702
8
0
null
null
null
null
UTF-8
C++
false
false
453
h
#ifndef CONTROLLER_H #define CONTROLLER_H #include <QObject> #include <QCoreApplication> #include <QThread> #include <QVector> class Worker; class Controller : public QObject { Q_OBJECT int threads_counter; QVector<QThread*> threads; public: Controller(); ~Controller(); void add_task(Worker* task); void start_threads(); public slots: void stop_threads(); signals: void finished(); }; #endif // CONTROLLER_H
[ "somekindofcookiemonster@gmail.com" ]
somekindofcookiemonster@gmail.com
f1d7f3c6f77010a9cab0f842e4aa01947d51fc6e
e4142fbc1f295359da7caa56b9508a6ec5a401db
/tests/arraytest.h
d3c3fc827f1685a0917ca93655eed7d48097fc45
[ "BSD-3-Clause" ]
permissive
ColinGilbert/d-collide
0f2dedfa79e8ca3a9afd303730a8f6767a55481c
8adb354d52e7ee49705ca2853d50a6a879f3cd49
refs/heads/master
2021-01-01T20:06:03.823170
2015-07-29T23:31:40
2015-07-29T23:31:40
39,916,820
6
0
null
null
null
null
UTF-8
C++
false
false
3,090
h
/******************************************************************************* * Copyright (C) 2007 by the members of PG 510, University of Dortmund: * * d-collide-users@lists.sourceforge.net * * Andreas Beckermann, Christian Bode, Marcel Ens, Sebastian Ens, * * Martin Fassbach, Maximilian Hegele, Daniel Haus, Oliver Horst, * * Gregor Jochmann, Timo Loist, Marcel Nienhaus and Marc Schulz * * * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met:* * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of the PG510 nor the names of its contributors may be * * used to endorse or promote products derived from this software without * * specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE * *******************************************************************************/ #ifndef DCOLLIDE_ARRAYTEST_H #define DCOLLIDE_ARRAYTEST_H #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "datatypes/array.h" using namespace CPPUNIT_NS; namespace dcollide { class ArrayTest : public TestFixture { CPPUNIT_TEST_SUITE (ArrayTest); CPPUNIT_TEST ( testArray ); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); protected: void testArray(); }; } #endif
[ "colingilbert86@gmail.com" ]
colingilbert86@gmail.com
8833933847fb89746bdaa82978c623233b929c31
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2652486_0/C++/kun/Zaki.cpp
67f0d527d53ee1eaf509cfd331adf6136db05137
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,079
cpp
#include<algorithm> #include<cstdio> int r,n,m,k,d,T; int x[10],g[3],sv[8],ct; using namespace std; void Try(int i,int j){ if(i==3){ sv[ct++] = j; return ; } Try(i+1,j*g[i]); Try(i+1,j); } int Chk(){ ct = 0; Try(0,1); for(int i=0;i<k;i++){ for(int j=0;j<ct;j++){ if(x[i]==sv[j]){ goto gs; } } return 0; gs:; } return 1; } int W(int i,int j){ if(i == 3){ if( Chk()){ for(int i=0;i<3;i++) printf("%d",g[i]); printf("\n"); return 1; } return 0; } for(int run = j;run<=m;run++){ g[i] = run; if(W(i+1,run)) return 1; g[i] = 0; } return 0; } int main(){ freopen("C-small-1-attempt0.in","r",stdin); freopen("out.txt","w",stdout); scanf("%d",&T); printf("Case #1:\n"); scanf("%d%d%d%d",&r,&n,&m,&k); while(r){ for(int i=0;i<k;i++){ scanf("%d",&x[i]); } int d = W(0,2); r--; } return 0; } //
[ "eewestman@gmail.com" ]
eewestman@gmail.com
1aac44796e8ef50a078a52751b496cdfa665bc3b
f8050958bf3b16d353d0de81709077833d57183b
/s32v234_sdk/libs/apexcv_pro/resize/graphs/build-apu-tct-sa-d/RESIZE_V_H_nativekernel.hpp
872a9236d9b850798adc16710b491ea50fbc9ce3
[ "WTFPL" ]
permissive
zhuhaijun753/Panorama4AIWAYS
9bf0482afc1e69fbf1dabf02b7df4f978efecb49
46e1988e54a5155be3b3b47c486b3f722be00b5c
refs/heads/master
2022-03-31T11:06:24.278727
2020-01-30T03:42:34
2020-01-30T03:42:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,846
hpp
#ifndef _ACF_PROCESS_APU_RESIZE_V_H_NATIVE_KERNEL_WRAPPER #define _ACF_PROCESS_APU_RESIZE_V_H_NATIVE_KERNEL_WRAPPER #include <RESIZE_V_H.hpp> //structure encapsulating the information ACF requires for each I/O typedef struct _acf_io_info { int32_t pBuf; //CL framework will initialize this with a pointer to global memory (based on associated cl_mem entity) int32_t width; //width in unit of elements int32_t height; //height in unit of elements int32_t span; //(2D only) the number of bytes required to jump from one line of bytes in memory to the 'next' line of bytes in memory icp::DATATYPE elementDataType; //element data type (icp::DATATYPE_08U, icp::DATATYPE_16S, etc. int32_t elementDimX; //element X dimension int32_t elementDimY; //element Y dimension } acf_io_info; /****************************************************** pArgs must point to an array with the following format: acf_io_info MYKERNEL_args[6]; where: [0] corresponds to indirect input 'SRC' source [1] corresponds to indirect input 'SRC' offset [2] corresponds to input 'SRC_WIDTH' [3] corresponds to input 'SRC_HEIGHT' [4] corresponds to input 'DST_WIDTH' [5] corresponds to input 'DST_HEIGHT' [6] corresponds to output 'DST' and 'pArgs = (void*)MYKERNEL_args;' ******************************************************/ static void RESIZE_V_H_nativekernel(void* pArgs) { acf_io_info* lpIo = 0; //SRC ACF_DataDesc SRC_src; ACF_DataDesc SRC_offset; lpIo = (acf_io_info*)((int32_t)pArgs+0*sizeof(acf_io_info)); SRC_src.Init2D(0, (void*)lpIo->pBuf, lpIo->nd_size.width, lpIo->nd_size.height, lpIo->nd_span.height, lpIo->elementDataType, lpIo->elementDimX, lpIo->elementDimY); lpIo = (acf_io_info*)((int32_t)pArgs+1*sizeof(acf_io_info)); SRC_offset.Init2D(0, (void*)lpIo->pBuf, lpIo->nd_size.width, lpIo->nd_size.height, lpIo->nd_span.height, lpIo->elementDataType, lpIo->elementDimX, lpIo->elementDimY); //SRC_WIDTH ACF_DataDesc SRC_WIDTH; lpIo = (acf_io_info*)((int32_t)pArgs+2*sizeof(acf_io_info)); SRC_WIDTH.Init2D(0, (void*)lpIo->pBuf, lpIo->nd_size.width, lpIo->nd_size.height, lpIo->nd_span.height, lpIo->elementDataType, lpIo->elementDimX, lpIo->elementDimY); //SRC_HEIGHT ACF_DataDesc SRC_HEIGHT; lpIo = (acf_io_info*)((int32_t)pArgs+3*sizeof(acf_io_info)); SRC_HEIGHT.Init2D(0, (void*)lpIo->pBuf, lpIo->nd_size.width, lpIo->nd_size.height, lpIo->nd_span.height, lpIo->elementDataType, lpIo->elementDimX, lpIo->elementDimY); //DST_WIDTH ACF_DataDesc DST_WIDTH; lpIo = (acf_io_info*)((int32_t)pArgs+4*sizeof(acf_io_info)); DST_WIDTH.Init2D(0, (void*)lpIo->pBuf, lpIo->nd_size.width, lpIo->nd_size.height, lpIo->nd_span.height, lpIo->elementDataType, lpIo->elementDimX, lpIo->elementDimY); //DST_HEIGHT ACF_DataDesc DST_HEIGHT; lpIo = (acf_io_info*)((int32_t)pArgs+5*sizeof(acf_io_info)); DST_HEIGHT.Init2D(0, (void*)lpIo->pBuf, lpIo->nd_size.width, lpIo->nd_size.height, lpIo->nd_span.height, lpIo->elementDataType, lpIo->elementDimX, lpIo->elementDimY); //DST ACF_DataDesc DST; lpIo = (acf_io_info*)((int32_t)pArgs+6*sizeof(acf_io_info)); DST.Init2D(0, (void*)lpIo->pBuf, lpIo->nd_size.width, lpIo->nd_size.height, lpIo->nd_span.height, lpIo->elementDataType, lpIo->elementDimX, lpIo->elementDimY); RESIZE_V_H lProcess; lProcess.Initialize(); lProcess.ConnectIndirectInput("SRC", SRC_src, SRC_offset); lProcess.ConnectIO("SRC_WIDTH", SRC_WIDTH); lProcess.ConnectIO("SRC_HEIGHT", SRC_HEIGHT); lProcess.ConnectIO("DST_WIDTH", DST_WIDTH); lProcess.ConnectIO("DST_HEIGHT", DST_HEIGHT); lProcess.ConnectIO("DST", DST); lProcess.Start(); lProcess.Wait(); } #endif //_ACF_PROCESS_APU_RESIZE_V_H_NATIVE_KERNEL_WRAPPER
[ "panyuhua@intesight.com" ]
panyuhua@intesight.com
7b86a0fe486971ab8713be4f38168408855fe120
2bbdbd3128b212adf5be946791f6cb21c2f3b09b
/AOFramework/Define/SystemDefine.hpp
ef983a55fe314e7036beadb2e9dfc350a0507f20
[]
no_license
kerwinzxc/AOFramework
60328fe011b9fddd009dfead5a54c3c317005914
70970c4ad3782714c39e0f1936d6e65d304fa1ba
refs/heads/master
2020-03-27T01:08:19.582307
2015-06-07T08:04:29
2015-06-07T08:04:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,358
hpp
#ifndef __AO_SYSTEM_DEFINE__ #define __AO_SYSTEM_DEFINE__ #include<string> #include<Windows.h> #include<cstdint> #if defined(DEBUG) || defined(_DEBUG) #define __AO_DEBUG__ #elif defined(RELEASE_DEBUG) #define __AO_RDEBUG__ #else #define __AO_RELEASE__ #endif #if defined(__AO_DEBUG__) || defined(__AO_RDEBUG__) #define AO_CHECK_ERROR_RETURN_HRESULT_MESSAGE(_hr,_str) \ if( FAILED(_hr) ) \ { \ ao::debug::PrintfColor(ConsoleColor::H_RED, _T("[%s]\n%s"),__AO_FUNCTION__,_str); \ return _hr; \ } #define AO_CHECK_ERROR_RETURN_HRESULT(_hr) \ if( FAILED(hr) ) \ { \ return hr; \ } #define AO_CHECK_ERROR_RETURN_TEMPLATE(_hr,_return) \ if( FAILED(hr) ) \ { \ return _return; \ } #define AO_CHECK_ERROR_USER_RETURN_TEMPLATE_MESSAGE(_bool,_return,_str) \ if( _bool ) \ { \ ao::debug::PrintfColor(ConsoleColor::H_RED, _T("[%s]\n%s"),__AO_FUNCTION__,_str); \ return _return; \ } #define AO_FAILED_FUNCTION_MESSAGE(_str) ao::debug::PrintfColor(ConsoleColor::H_RED, _T("[%s]\n%s"),__AO_FUNCTION__,_str); #define AO_SUCCEEDED_FUNCTION_MESSAGE(_str) ao::debug::PrintfColor(ConsoleColor::H_GREEN, _T("[%s]\n%s"),__AO_FUNCTION__,_str); #define AO_ASSERT(_flag,_str) #else #define AO_CHECK_ERROR_RETURN_HRESULT_MESSAGE(_hr,_str) _hr; #define AO_CHECK_ERROR_RETURN_HRESULT(_hr) _hr; #define AO_CHECK_ERROR_RETURN_TEMPLATE(_hr,_return) _hr; #define AO_CHECK_ERROR_USER_RETURN_TEMPLATE_MESSAGE(_bool,_return,_str) _return; #define AO_FAILED_FUNCTION_MESSAGE(_str) #define AO_SUCCEEDED_FUNCTION_MESSAGE(_str) #endif namespace ao { #if UNICODE typedef std::wstring string; typedef std::wostringstream ostringstream; template<class T> inline std::wstring to_string(const T& _val) { return std::to_wstring(_val); } #else typedef std::string string; typedef std::ostringstream ostringstream; template<class T> inline std::string to_string(const T& _val) { return std::to_string(_val); } #endif } #if UNICODE typedef wchar_t AOCHAR; typedef LPWSTR AOLPSTR; typedef LPCWSTR AOLPCSTR; typedef LPCWCHAR AOLPCCHAR; #define ao_strcmp lstrcmpiW #define ao_strcpy_s wcscpy_s #define _ao_vsnprintf_s _vsnwprintf_s #define ao_vsprintf_s vswprintf_s #define ao_fopen_s _wfopen_s #define ao_strlen wcslen #define ao_sprintf_s swprintf_s #define ao_to_f _wtof #define ao_to_i _wtoi #define __AO_FUNCTION__ __FUNCTIONW__ #else typedef char AOCHAR; typedef LPSTR AOLPSTR; typedef LPCTSTR AOLPCSTR; typedef LPCWCHAR AOLPCCHAR; #define ao_strcmp lstrcmpiA #define ao_strcpy_s strcpy_s #define _ao_vsnprintf_s _vsnprintf_s #define ao_vsprintf_s vsprintf_s #define ao_fopen_s fopen_s #define ao_strlen strlen #define ao_sprintf_s sprintf_s #define ao_to_f atof #define ao_to_i atoi #define __AO_FUNCTION__ __FUNCTION__ #endif #ifdef _WIN64 //64bit #define AO_GW_USERDATA GWLP_USERDATA #else //32bit #define AO_GW_USERDATA GWL_USERDATA #endif typedef int8_t s8; typedef int16_t s16; typedef int32_t s32; typedef int64_t s64; typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; typedef float_t f32; typedef double_t d64; typedef intptr_t ao_intptr; #endif
[ "jinten0@gmail.com" ]
jinten0@gmail.com
6434096ba6485893d408866fea698094bf6d64b3
b60b32163470f01c903dbde72b1142eb1a0e63fb
/hdu/2027/main.cpp
787581fb45c4a46ab4a4e5998c3e3d046e92eae5
[]
no_license
mdyang/oj-solutions
b4830c87ae861186fd738a5da72b9283d06a87eb
e038b513e82b6dbe9cb350c687007a2324f953fc
refs/heads/master
2016-09-16T16:45:06.281518
2016-04-09T05:20:12
2016-04-09T05:20:12
15,038,618
0
0
null
null
null
null
UTF-8
C++
false
false
753
cpp
#include<iostream> #include<string> #include<memory.h> using namespace std; int cnt[6]; int index(char c){ switch(c){ case 'a': case 'A':return 0; case 'e': case 'E':return 1; case 'i': case 'I':return 2; case 'o': case 'O':return 3; case 'u': case 'U':return 4; default:return 6; } } char c[6]="aeiou"; int main(){ int n; cin>>n;cin.ignore(); bool first=true; while(n--){ if(first)first=false; else cout<<endl; string s; getline(cin,s); memset(cnt,0,sizeof(cnt)); for(int i=0;i<s.size();i++)cnt[index(s[i])]++; for(int i=0;i<5;i++)cout<<c[i]<<':'<<cnt[i]<<endl; } return 0; }
[ "conanholmes001@gmail.com" ]
conanholmes001@gmail.com
ba87093810d46f0c172399be8ce6a56d4c5e16dc
b39cd1115a08507cc3f07ec29a7f99ca534e4e07
/gui/display/test_display.cpp
cb2c2be9d167248eb736449ab08df8d7e402ce38
[]
no_license
FrankBlabu/GEP
df5d392457f662f19d495b6fccb48b08ef105669
bf0edacd8a9e5f1f13722d605129e143a538e882
refs/heads/master
2022-11-11T01:34:04.031542
2011-08-03T17:43:34
2011-08-03T17:43:34
275,880,642
0
0
null
null
null
null
UTF-8
C++
false
false
576
cpp
/* * test_display.cpp - Test for the display classes * * Frank Cieslok, 05.06.2006 */ #include "GEPDisplayPopulationWidget.hpp" #include <QApplication> #include <string> using namespace std; namespace GEP { //#************************************************************************* // Test functions //#************************************************************************* } // namespace GEP int main (int argc, char** argv) { QApplication app (argc, argv); GEP::Display::PopulationWidget widget (0); widget.show (); return app.exec (); }
[ "frankcieslok@gmail.com" ]
frankcieslok@gmail.com
a6b568c766e73dd2d43076b59965e624578434d3
4642f67aa4cc14fe6032d83a89812939ce699e6c
/C++/algorithms/algorithm-interview/Time-Complexity/Common-Code-for-Time-Complexity/main.cpp
45b130cf5cbf63c980aa207c6bd678995d6cddd5
[]
no_license
Thpffcj/DataStructures-and-Algorithms
947e75b6e41cb4142fcd1d63e358d44389298a7b
66b838a7a90527064fc1cdcebb43379cb9f0c66c
refs/heads/master
2021-01-01T19:14:38.755589
2020-04-06T01:50:22
2020-04-06T01:50:22
98,543,990
7
0
null
null
null
null
UTF-8
C++
false
false
2,517
cpp
// // Created by Thpffcj on 2017/9/16. // #include <iostream> using namespace std; // O(1) void swapTwoInts( int &a , int &b ){ int temp = a; a = b; b = temp; return; } // O(n) Time Complexity int sum( int n ){ int ret = 0; for( int i = 0 ; i <= n ; i ++ ) ret += i; return ret; } void reverse( string &s ){ int n = s.size(); for( int i = 0 ; i < n/2 ; i ++ ) swap( s[i] , s[n-1-i] ); return; } // O(n^2) Time Complexity void selectionSort(int arr[], int n){ for(int i = 0 ; i < n ; i ++){ int minIndex = i; for( int j = i + 1 ; j < n ; j ++ ) if( arr[j] < arr[minIndex] ) minIndex = j; swap( arr[i] , arr[minIndex] ); } } // O(n) Time Complexity void printInformation(int n){ for( int i = 1 ; i <= n ; i ++ ) for( int j = 1 ; j <= 30 ; j ++ ) cout<<"Class "<<i<<" - "<<"No. "<<j<<endl; return; } // O(logn) Time Complexity int binarySearch(int arr[], int n, int target){ int l = 0, r = n-1; while( l <= r ){ int mid = l + (r-l)/2; if( arr[mid] == target ) return mid; if( arr[mid] > target ) r = mid - 1; else l = mid + 1; } return -1; } string intToString( int num ){ string s = ""; string sign = "+"; if( num < 0 ){ num = -num; sign = "-"; } while( num ){ s += '0' + num%10; num /= 10; } if( s == "" ) s = "0"; reverse(s); if( sign == "-" ) return sign + s; else return s; } // O(nlogn) void hello(int n){ for( int sz = 1 ; sz < n ; sz += sz ) for( int i = 1 ; i < n ; i ++ ) cout<<"Hello, Algorithm!"<<endl; } // O(sqrt(n)) Time Complexity bool isPrime( int num ){ for( int x = 2 ; x*x <= num ; x ++ ) if( num%x == 0 ) return false; return true; } bool isPrime2( int num ){ if( num <= 1 ) return false; if( num == 2 ) return true; if( num%2 == 0 ) return false; for( int x = 3 ; x*x <= num ; x += 2 ) if( num%x == 0 ) return false; return true; } int main() { cout << intToString(123)<<endl; cout << intToString(0)<<endl; cout << intToString(-123)<<endl; cout<<endl; if( isPrime2(137) ) cout<<"137 is a prime."<<endl; else cout<<"137 is not a prime."<<endl; if( isPrime2(121) ) cout<<"121 is a prime."<<endl; else cout<<"121 is not a prime."<<endl; return 0; }
[ "1441732331@qq.com" ]
1441732331@qq.com
72dda296f80e038d71c03da09ac9aa49b6545ce9
d23f5a0fa48aae622ebb87c8444995b7212ef6f1
/file manipulation/v23s3p3/main.cpp
3a6824b834173f759ec32dbb7434c9d3ab130d1f
[]
no_license
AndreiCatalinN/college
8693207a90bbcd2a5e94b2d966941efb088dce6a
84d1450e409f477cb70258bf0150d3597c1e9475
refs/heads/master
2021-07-19T19:05:00.117902
2020-07-26T12:58:57
2020-07-26T12:58:57
199,473,120
0
0
null
null
null
null
UTF-8
C++
false
false
594
cpp
#include <iostream> #include <fstream> using namespace std; ifstream f("date.in"); void shift(int n, int x[101]) { int i,aux,ok; for(i=1; i<n; i++) { if(x[i]<x[i+1]) aux=x[i]; x[i]=x[i+1]; x[i+1]=aux; ok=0; } } int main() { int n, x[101],i,ok=1; f>>n; for(i=1; i<=n; i++) f>>x[i]; shift(n,x); for(i=1; i<=n; i++) cout<<x[i]<<" "; cout<<endl; do { ok=1; shift(n,x); } while(ok==0); for(i=1; i<=n; i++) cout<<x[i]<<" "; f.close(); return 0; }
[ "c16733435@mydit.ie" ]
c16733435@mydit.ie
0bad37bfb454a7e86dfeb114668f6a31c78384b2
91ad10182d612b90165affcfb4e80a7ece4ac7cd
/QASI_AH_PUTRI_TT3D_Project7Calculator.ino
e3484abc3bd96b77304a0626bf9ee3913dc73e78
[]
no_license
qasiahputri/calculator
c60e614c6a97bdb7aef9d0870ef62202590e8d89
4d991059275743d337ec3cbe513aeedcf196fc51
refs/heads/main
2023-01-12T02:18:24.729387
2020-11-22T15:51:38
2020-11-22T15:51:38
315,073,757
0
0
null
null
null
null
UTF-8
C++
false
false
2,056
ino
#include <LiquidCrystal.h> #include <Keypad.h> LiquidCrystal lcd(12, 11, 10, 9, 8, 7); const byte JmlBaris = 4; const byte JmlKolom = 4; char keys[JmlBaris][JmlKolom] = { {'7', '8', '9', '/'}, {'4', '5', '6', 'x'}, {'1', '2', '3', '-'}, {'C', '0', '=', '+'} }; byte PinBaris[JmlBaris] = {6, 5, 4, 3}; byte PinKolom[JmlKolom] = {2, 1, 0, 13}; Keypad myKeypad = Keypad(makeKeymap(keys), PinBaris, PinKolom, JmlBaris, JmlKolom ); boolean valOnePresent = false; boolean final = false; String num1, num2; long ans; char op; void setup(){ lcd.begin(16,2); lcd.setCursor(2,0); lcd.print("Kalkulator-Qas"); delay(1000); lcd.clear(); //lcd clear } void loop(){ char key = myKeypad.getKey(); if(key!=NO_KEY && key=='1'||key=='2'||key=='3'||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9'||key=='0'){ if (valOnePresent != true){ num1 = num1 + key; int numLength = num1.length(); lcd.setCursor(15-numLength, 0); lcd.print(num1); } else { num2 = num2 + key; int numLength = num2.length(); lcd.setCursor(15 - numLength, 1); lcd.print(num2); final = true; } } else if (valOnePresent == false && key != NO_KEY && (key == '/' || key == 'x' || key == '-' || key == '+')){ if (valOnePresent == false){ valOnePresent = true; op = key; lcd.setCursor(15,0); lcd.print(op); } } else if (final == true && key != NO_KEY && key == '='){ if (op == '+'){ ans = num1.toInt() + num2.toInt(); } else if (op == '-'){ ans = num1.toInt() - num2.toInt(); } else if (op == 'x'){ ans = num1.toInt() * num2.toInt(); } else if (op == '/'){ ans = num1.toInt() / num2.toInt(); } lcd.clear(); lcd.setCursor(15,0); lcd.autoscroll(); lcd.print(ans); lcd.noAutoscroll(); } else if (key != NO_KEY && key == 'C'){ lcd.clear(); valOnePresent = false; final = false; num1 = ""; num2 = ""; ans = 0; op = ' '; } }
[ "noreply@github.com" ]
noreply@github.com
7da3279bb38e0e0e2bc376776934d46a68cbcacb
fa17d61ab90ec93c18ccbf48def34ade8c902d42
/human.cc
a807790f1002b92c95e5af1a950d30898fc19f4f
[]
no_license
jiawangli/cc3k
84cdd4552b23ac498d520507b186e25b20d70960
13e11f761fa29e057e0d3b18e3613e4165221c86
refs/heads/master
2021-01-01T06:52:28.709141
2017-07-25T00:42:19
2017-07-25T00:42:19
97,538,378
0
0
null
2017-07-20T01:24:45
2017-07-18T01:28:42
C++
UTF-8
C++
false
false
898
cc
// // human.cpp // cc3k // // Created by w43wei on 2017-07-19. // Copyright © 2017 w43wei. All rights reserved. // #include "human.h" #include "character.h" #include <string> #include <iostream> #include <sstream> #include <stdlib.h> using namespace std; // default ability of human: 140 HP, 20 Atk, 20 Def Human::Human(): Enemy(140, 20, 20){ this->type="dwarf"; } string Human::attack(Character *pc){ int damage=(int)(atk*(100.0/(100.0+pc->getDef()))); int newHp; if(pc->getHp()-damage<0){ // hp cannot be zero newHp=0; }else{ newHp=pc->getHp()-damage; } ostringstream ss; if(rand()%100 < 50){ // 50% chance miss return type+" misses the attack on PC."; }else{ // don't miss pc->setHp(newHp); ss << type << " deals " << damage << " damage to PC."; return ss.str(); } } Human::~Human(){}
[ "noreply@github.com" ]
noreply@github.com
f11db2cf3d5964e7a8c970a67e48749c6bc70c18
f28ec0f0c5232ca9b1076313a82e77f2e68c9a65
/abc-222/c.cpp
a518c50c6d30a0c3d228492ad65718adabbb9243
[]
no_license
aquaEngineer/atcoder
b8dffb5ee292d320e4952878062d59679b7539ae
1fab7f75863d414842bccc0e3e453eff27951fae
refs/heads/master
2022-04-30T13:29:32.879605
2022-04-25T14:09:08
2022-04-25T14:09:08
245,680,211
0
0
null
null
null
null
UTF-8
C++
false
false
2,579
cpp
#include <bits/stdc++.h> // #include <atcoder/all> using namespace std; // using namespace atcoder; using ll = long long; #define rep(i,a,b) for(ll i=(a); i<(b); i++) #define YES cout << "YES" << endl; #define NO cout << "NO" << endl; #define yes cout << "Yes" << endl; #define no cout << "No" << endl; #define pai 3.14159265358979323846 ll gcd(ll a, ll b){if (a%b == 0) return(b);else return(gcd(b, a%b));} ll lcm(ll a, ll b){return a * b / gcd(a, b);} const int mod = 1000000007; /* map<string,int> */ /* 大文字を小文字に変換 tolower*/ /* 小文字を大文字に変換 toupper*/ /* 辞書順 next_permutation(a.begin(),a.end()) */ /* 桁数std::setprecision(2)*/ void printVec(std::vector<char> &vec) { std::cout << ""; for (auto it = vec.begin(); it != vec.end(); ++it) { std::cout << *it << " "; } std::cout << std::endl; } int search(vector<pair<int,int>> a, int v) { for(int i = 0 ; i <a.size(); i++) { if (a[i].second == v) { return i; } } return 0; } void vecSort(vector<pair<int,int>> &a) { sort(a.begin(),a.end(),[](pair<int,int> a, pair<int,int> b) { if (a.first != b.first) { return a.first > b.first; } else { return a.second < b.second; } }); } int judge (char a,char b) { if (a == b) return 0; if (a == 'G' && b == 'C') return 1; if (a == 'G' && b == 'P') return 2; if (a == 'C' && b == 'P') return 1; if (a == 'C' && b == 'G') return 2; if (a == 'P' && b == 'G') return 1; if (a == 'P' && b == 'C') return 2; } int main() { int n; int m; cin >> n >>m; vector <vector <char>> a(2*n +1,vector<char> (m +1)); for (int i = 1;i<2*n+1; i++) { for (int j = 1; j <m+1; j++) { cin >> a[i][j]; } } vector <pair<int,int>> b(2*n); pair <int,int> c; for (int i =1; i <2*n +1; i++) { c.first = 0; c.second = i; b[i-1] = c; } int s; int result = 0; for (int i = 1; i <m+1; i++) { for (int j = 0; j < b.size() -1 ; j +=2) { int x = b[j].second; int y = b[j+1].second; result = judge(a[x][i], a[y][i]); if (result == 1) { s = search(b, x); b[s].first++; } else if (result == 2) { s = search(b, y); b[s].first++; } else { } } vecSort(b); } for (int i =0 ;i < b.size(); i++) { cout << b[i].second<< endl; } }
[ "aqua.server.tech@gmail.com" ]
aqua.server.tech@gmail.com
311392ea9ac9431eb8d8cc365170f9c469dc6337
55f3f5bd3ddd3ea45a9a1c3cd9f54f2eb8157175
/alpaca_zorro_plugin/market_data/polygon.cpp
f13a81c65641a68cc626250bd692b629e54843ac
[ "MIT" ]
permissive
webclinic017/alpaca_zorro_plugin
80adf5d84bfc63fb3d68d16cc8308f891d7076a7
6edc53a385dcf7b893f6c401e6b7c870fb358a5d
refs/heads/main
2023-08-04T18:24:35.540643
2021-09-17T14:27:01
2021-09-17T14:27:01
408,220,653
1
0
MIT
2021-09-19T19:41:32
2021-09-19T19:41:32
null
UTF-8
C++
false
false
3,452
cpp
#include "stdafx.h" #include "market_data/polygon.h" #include "date/date.h" using namespace alpaca; Response<std::vector<Bar>> Polygon::getBars( const std::string& symbol, __time32_t start, __time32_t end, int nTickMinutes, uint32_t limit, int32_t price_type) const { if (end == 0) { end = static_cast<__time32_t>(std::time(nullptr)); } auto t_end = end; Response<std::vector<Bar>> result; auto& rtBars = result.content(); rtBars.reserve(limit); __time32_t upperBound = t_end; do { std::stringstream url; url << baseUrl_ << "/v2/aggs/ticker/" << symbol << "/range/" << nTickMinutes << "/minute"; try { using namespace date; url << "/" << format("%F", date::sys_seconds{ std::chrono::seconds{ start } }); url << "/" << format("%F", date::sys_seconds{ std::chrono::seconds{ t_end } }); } catch (const std::exception& e) { assert(false); return Response<std::vector<Bar>>(1, "invalid time. " + std::string(e.what())); } url << "?sort=desc&limit="<<limit; // in desending order LOG_DEBUG("--> %s\n", url.str().c_str()); url << "&" << apiKey_; auto response = request<std::vector<Bar>, Polygon>(url.str(), nullptr, nullptr); if (!response) { BrokerError(response.what().c_str()); break; } auto& bars = response.content(); size_t nExclude = 0; LOG_DEBUG("%d bars downloaded.\n", bars.size()); if (!bars.empty()) { using namespace date; auto from = bars.front().time; auto to = bars.back().time; LOG_DEBUG("%s(%d) - %s(%d)\n", format("%F %T", date::sys_seconds{ std::chrono::seconds{ from } }).c_str(), from, format("%F %T", date::sys_seconds{ std::chrono::seconds{ to } }).c_str(), to); } else { // no more data break; } // remove record passed end time auto it = bars.cbegin(); for (; it != bars.cend();) { if ((__time32_t)(*it).time <= upperBound) { break; } ++it; } if (it != bars.cbegin()) { bars.erase(bars.cbegin(), it); } if (bars.empty()) { break; } rtBars.insert(rtBars.end(), bars.begin(), bars.end()); if (!rtBars.empty()) { upperBound = rtBars.back().time - 1; } } while (rtBars.size() < limit); // remove order older than start auto it = rtBars.end(); while (it != rtBars.begin()) { --it; if ((*it).time >= (uint32_t)start) { break; } it = rtBars.erase(it); } // keep number of records up to limit if (rtBars.size() > limit) { rtBars.resize(limit); } LOG_DEBUG("return %d bars.\n", rtBars.size()); if (!rtBars.empty()) { using namespace date; LOG_DEBUG("%s(%d) - %s(%d)\n", format("%F %T", date::sys_seconds{ std::chrono::seconds{ rtBars.front().time } }).c_str(), rtBars.front().time, format("%F %T", date::sys_seconds{ std::chrono::seconds{ rtBars.back().time } }).c_str(), rtBars.back().time); } // change to asending order, BrokerHistory2 handles asending order std::reverse(rtBars.begin(), rtBars.end()); return result; }
[ "kzhdev@gmail.com" ]
kzhdev@gmail.com
6aa12635099e87d3642cde2d3628714b0c16c108
42a072d3c53cd78c1ce82b974442d998298284cc
/libalgo/source/structures/projection/projection.h
65a0429b29434ba17c2f1fcbf49f39155c4a68c6
[]
no_license
bayertom/detectproj
b359991e2457aa91cb8adf22b585215f768ccf12
1ba138ae9a1541ab504e000d5961a4ca3c5cec51
refs/heads/master
2021-01-23T03:05:33.525489
2017-01-02T00:06:41
2017-01-02T00:06:41
19,872,193
6
0
null
null
null
null
UTF-8
C++
false
false
6,885
h
// Description: General cartographic projection with pure wirtual methods // For evaluations, its equations in the postfix notation are stored // Supported equations in the non-closed form, // Copyright (c) 2010 - 2015 // Tomas Bayer // Charles University in Prague, Faculty of Science // bayertom@natur.cuni.cz // This library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library. If not, see <http://www.gnu.org/licenses/>. #ifndef Projection_H #define Projection_H #include <algorithm> #include <iostream> #include <ostream> #include <string.h> #include "libalgo/source/structures/point/Point3DGeographic.h" #include "libalgo/source/structures/matrix/Matrix.h" #include "libalgo/source/algorithms/carttransformation/CartTransformation.h" #include "libalgo/source/algorithms/arithmeticparser/ArithmeticParser.h" #include "libalgo/source/io/File.h" //Structure stores min-max values template <typename T> struct TMinMax { T min_val, max_val; typedef T value_type; TMinMax <T> ( ) : min_val ( 0.0 ), max_val ( 0.0 ) {} TMinMax <T> ( const T min_val_, const T max_val_ ) : min_val ( min_val_ ), max_val ( max_val_ ) {} }; //Common cartographic projection: abstract class template <typename T> class Projection { protected: T R; //Sphere radius T lon0; //Projection central parallel T dx; //Aditive constant dx T dy; //Aditive constant dy T c; //Additional constant of the projection char * x_equat; //Equation X char * y_equat; //Equation Y TPostfixNotationDel x_equat_postfix; //Equation X converted to the postfix notation TPostfixNotationDel y_equat_postfix; //Equation Y converted to the postfix notation char * projection_family; //Projection family char * projection_name; //Projection name public: Projection() : R(1.0), lon0(0.0), dx(0.0), dy(0.0), c(0.5), x_equat(NULL), y_equat(NULL), x_equat_postfix(0), y_equat_postfix(0), projection_family(NULL), projection_name(NULL) {} Projection(const T R_, const T lon0_, const T dx_, const T dy_, const T c_, const char * x_equat_, const char * y_equat_, const TPostfixNotationDel &x_equat_postfix_, const TPostfixNotationDel &y_equat_postfix_); Projection(const T R_, const T lon0_, const T dx_, const T dy_, const T c_, const char * x_equat_, const char * y_equat_, const TPostfixNotationDel &x_equat_postfix_, const TPostfixNotationDel &y_equat_postfix_, const char * projection_family_, const char * projection_name_); Projection(const Projection <T> *proj); Projection(const Projection <T> &proj); virtual ~Projection() = 0; public: //Methods common for all derived classes (methods are not virtual) T getR() const {return R;} T getLon0() const {return lon0;} T getDx() const {return dx;} T getDy() const {return dy;} T getC() const {return c;} const char * getXEquat() const { return x_equat; } const char * getYEquat() const { return y_equat; } const TPostfixNotationDel * getXEquatPostfix() const { return &x_equat_postfix; } const TPostfixNotationDel * getYEquatPostfix() const { return &y_equat_postfix; } TPostfixNotationDel * getXEquatPostfix() { return &x_equat_postfix; } TPostfixNotationDel * getYEquatPostfix() { return &y_equat_postfix; } const char * getFamily() const { return projection_family; } const char * getName() const { return projection_name; } void setR(const T R_) { R = R_; } void setLon0(const T lon0_) { lon0 = lon0_; } void setDx(const T dx_) { dx = dx_; } void setDy(const T dy_) { dy = dy_; } void setC(const T c_) { c = c_; } void XEquatToPostfix(); void YEquatToPostfix(); void setXEquat(const char * x_equat_); void setYEquat(const char * y_equat_); void setXEquatPostfix(const TPostfixNotationDel &x_equat_postfix_) { x_equat_postfix = x_equat_postfix_; } void setYEquatPostfix(const TPostfixNotationDel &y_equat_postfix_) { y_equat_postfix = y_equat_postfix_; } void setFamily(const char * projection_family_); void setName(const char * projection_name_); public: //Methods different for all derived classes ( methods are virtual ) virtual Point3DGeographic <T> getCartPole() const = 0; virtual T getLat0() const = 0; virtual T getLat1() const = 0; virtual T getLat2() const = 0; virtual T getA() const = 0; virtual T getB() const = 0; virtual TMinMax <T> getLatPInterval() const = 0; virtual TMinMax <T> getLonPInterval() const = 0; virtual TMinMax <T> getLat0Interval() const = 0; virtual TMinMax <T> getLatPIntervalH(const TMinMax <T> &lat) const = 0; virtual TMinMax <T> getLonPIntervalH(const TMinMax <T> &lon) const = 0; virtual TTransformedLongitudeDirection getLonDir() const = 0; virtual const char * getFThetaEquat() const = 0; virtual const char * getTheta0Equat() const = 0; virtual const TPostfixNotationDel * getFThetaEquatPostfix() const = 0; virtual const TPostfixNotationDel * getTheta0EquatPostfix() const = 0; virtual TPostfixNotationDel * getFThetaEquatPostfix() = 0; virtual TPostfixNotationDel * getTheta0EquatPostfix() = 0; virtual void setCartPole(const Point3DGeographic <T> & pole) = 0; virtual void setLat0(const T lat0) = 0; virtual void setLat1(const T lat1) = 0; virtual void setLat2(const T lat2) = 0; virtual void setA(const T a) = 0; virtual void setB(const T b) = 0; virtual void setLonDir(const TTransformedLongitudeDirection lon_dir_) = 0; virtual void setFThetaEquat(const char * ftheta_equat_) = 0; virtual void setTheta0Equat(const char * theta0_equat_) = 0; virtual void setFThetaEquatPostfix(const TPostfixNotationDel & ftheta_equat_postfix_) = 0; virtual void setTheta0EquatPostfix(const TPostfixNotationDel & theta0_equat_postfix_) = 0; virtual void FThetaEquatToPostfix() = 0; virtual void Theta0EquatToPostfix() = 0; virtual void getShortCut(char * shortcut) const = 0; virtual Projection <T> *clone() const = 0; virtual void print(std::ostream * file = &std::cout) const = 0; }; #include "Projection.hpp" #endif
[ "bayertom@natur.cuni.cz" ]
bayertom@natur.cuni.cz
a93dfa7c63df541cc22b8a836ab9659702bdc133
110dd6de6eef5f2a8804dc0d1d89aaaa56767393
/Source/Guesser.cpp
a4aafb259d308150a2604f37b3de75c6b15c1f28
[]
no_license
eperegrine/NumberGuesser-CPP
4cc6adab57e8166006844c8c0709960a479122b3
8a3c5fab38225ffcbc4a7b4ab1adfbc795b2a9d0
refs/heads/master
2021-05-29T18:08:04.711527
2015-07-18T22:53:40
2015-07-18T22:53:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
377
cpp
//Guesser.cpp #include "Guesser.h" #include "GuessType.h" Guesser::Guesser (int numberToGuess) { this->ValToGuess = numberToGuess; } GuessType Guesser::MakeGuess (int val) { if (val == this->ValToGuess) { return GuessType::Correct; } else { this->Guesses += 1; if (val > this->ValToGuess) { return GuessType::High; } else { return GuessType::Low; } } }
[ "tomfperegrine@googlemail.com" ]
tomfperegrine@googlemail.com
165d674ffa3593e944cef1fd6af810a7dc4d7210
6593d674c7ee62545e1b3eac589dde846b91ec3d
/queue/queue.cpp
f781db6ded6cd1c53aeabe0d1c2bea4ef1ac87ef
[]
no_license
kongsicong/DataStructure
7155e434516ad2b552225ea09f11cf6f64d23ac6
a3e74ecbccbf05a684f5e99d77751f1d0557fd4a
refs/heads/master
2021-01-10T08:27:49.656592
2016-04-18T03:24:00
2016-04-18T03:24:00
55,040,395
0
0
null
null
null
null
UTF-8
C++
false
false
2,505
cpp
#include "queue.h" #include <stdlib.h> namespace queue { Status InitQueue(LinkQueue &Q) { Q.front = Q.rear = (QNode*)malloc(sizeof(QNode)); if (!Q.front) exit(OVERFLOW); Q.front->next = nullptr; return OK; } Status DestroyQueue(LinkQueue &Q) { while (Q.front) { Q.rear = Q.front->next; free(Q.front); Q.front = Q.rear; } return OK; } Status ClearQueue(LinkQueue &Q) { QNode * cur = Q.front->next; while (cur) { Q.rear = cur->next; free(cur); cur = Q.rear; } Q.rear = Q.front; Q.front->next = nullptr; return OK; } Status QueueEmpty(LinkQueue Q) { if (Q.front == Q.rear) return TRUE; else return FALSE; } int QueueLength(LinkQueue Q) { int i = 0; for (QNode* cur = Q.front->next; cur != nullptr; cur = cur->next, i++); return i; } Status EnQueue(LinkQueue &Q, QElemType e) { QNode *node = (QNode*)malloc(sizeof(QNode)); if (!node) return OVERFLOW; node->data = e; node->next = nullptr; Q.rear->next = node; Q.rear = node; return OK; } Status DeQueue(LinkQueue &Q, QElemType &e) { if (Q.front == Q.rear) return OVERFLOW; e = Q.front->next->data; if (Q.front->next == Q.rear) { free(Q.front->next); Q.front->next = nullptr; Q.rear = Q.front; } else { QNode* cur = Q.front->next; Q.front->next = cur->next; free(cur); } return OK; } Status GetHead(LinkQueue Q, QElemType &e) { if (Q.rear == Q.front) return ERROR; e = Q.front->next->data; return OK; } /*********************************************************************************************************************************************************/ Status InitQueue(SqQueue &Q) { Q.base = (QElemType*)malloc(MAXQSIZE * sizeof(QElemType)); if (!Q.base) return OVERFLOW; Q.front = Q.rear = 0; return OK; } Status DestroyQueue(SqQueue &Q) { free(Q.base); Q.base = nullptr; Q.front = Q.rear = 0; return OK; } Status ClearQueue(SqQueue &Q) { Q.front = Q.rear = 0; return OK; } Status QueueEmpty(SqQueue Q) { if (Q.front == Q.rear) return TRUE; else return FALSE; } int QueueLength(SqQueue Q) { return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE; } Status EnQueue(SqQueue &Q, QElemType e) { if ((Q.rear + 1) % MAXQSIZE == Q.front) return ERROR; Q.base[Q.rear] = e; Q.rear = (Q.rear + 1) % MAXQSIZE; return OK; } Status DeQueue(SqQueue &Q, QElemType &e) { if (QueueEmpty(Q)) return ERROR; e = Q.base[Q.front]; Q.front = (Q.front + 1) % MAXQSIZE; return OK; } }
[ "1390159970@qq.com" ]
1390159970@qq.com
efc4c85ea917696643acd184c0d1decf78cbeb1d
2fa31ae8d02cd92bf24bd8cf0f2a611a02a28519
/before2018/baekjoon/5586.cpp
31f35f413189bb45beeb5db4dd093e0a0912e402
[]
no_license
dlftls38/algorithms
3619186d8d832cda695dfbf985e5d86ef6f2f06e
18ab96bbb3c8512a2da180477e4cc36a25edd30d
refs/heads/master
2021-07-10T06:09:53.211350
2020-10-17T00:04:43
2020-10-17T00:04:43
206,953,967
0
0
null
null
null
null
UTF-8
C++
false
false
277
cpp
#include <stdio.h> #include <string.h> int main(){ char gg[10001]={0}; gets(gg); int i,a=0,b=0,len; len=strlen(gg); for(i=0;i<len;i++){ if(strncmp(&gg[i],"JOI",3)==0){ a++; i++; } if(strncmp(&gg[i],"IOI",3)==0){ b++; i++; } } printf("%d\n%d",a,b); }
[ "dlftls38@naver.com" ]
dlftls38@naver.com
9f280dc45857a3a8dd46cc7953e59bd8393600f0
abf8712d81d9a1cf4ffd8b738cf453db5ddf0e6a
/ДЗ на 11.11.18/12.cpp
3fa24ec9b4194f768bb034e69b64acb615b0301d
[]
no_license
OpossumCrash/Maria-Levina-11K
4d9c81e35ac5718ed10939cc95fbda07f3197bae
c8c98ccf8787b370f909cfc2ed435c7e6db5ff64
refs/heads/master
2020-04-08T05:04:31.008866
2019-11-04T20:42:58
2019-11-04T20:42:58
159,044,742
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
861
cpp
/*Напишите процедуру, дописывающую к каждому элементу динамически выделенного массива справа его квадрат. ({1,2,3,4}->{1,1,2,4,3,9,4,16}). По окончании работы процедуры количество выделенной памяти должно увеличиться.*/ #include <iostream> using namespace std; /*int sqr(int b){ return b * b;} void pere(int* &a, int n){ int* nov = new int[2 * n]; int k = 0; for(int i = 0; i < 2 * n; i++){ *(nov + k) = *(a + i); k++; *(nov + k) = sqr(*(a + i)); } a = nov; } int main(){ int N; cin >> N; int* A = new int[N]; for (int i = 0; i < N; i++){ cin >> *(A + i); }; pere(A, N); for (int i = 0; i < (2 * N); i++){ cout << *(A + i) << " "; }; delete []A; return 0;}*/
[ "44146018+OpossumCrash@users.noreply.github.com" ]
44146018+OpossumCrash@users.noreply.github.com
c90ccaa73ddc490676ce17bdd637170a3cff2258
6d77e738c66bdf8809e47ad9be85f9c7361a1bd9
/src/server/game/Movement/Spline/MoveSpline.h
35522617c332524e9ef2f23a9e6fb49becd6a0f2
[]
no_license
Ramys/Hooaahcore
e768e8b8a2b2c1dba7501495161cf6c0419b9de2
dad11ee863d34a9f02186936b1dbbca168912ecd
refs/heads/main
2023-02-27T16:18:27.916812
2021-02-07T23:38:52
2021-02-07T23:38:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,264
h
/* * Copyright (C) 2021 Hooaahcore * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef TRINITYSERVER_MOVEPLINE_H #define TRINITYSERVER_MOVEPLINE_H #include "Spline.h" #include "MoveSplineInitArgs.h" #include <G3D/Vector3.h> namespace WorldPackets { namespace Movement { class CommonMovement; class MonsterMove; } } namespace Movement { struct Location : public Vector3 { Location() : orientation(0) { } Location(float x, float y, float z, float o) : Vector3(x, y, z), orientation(o) { } Location(const Vector3& v) : Vector3(v), orientation(0) { } Location(const Vector3& v, float o) : Vector3(v), orientation(o) { } float orientation; }; // MoveSpline represents smooth catmullrom or linear curve and point that moves belong it // curve can be cyclic - in this case movement will be cyclic // point can have vertical acceleration motion component (used in fall, parabolic movement) class TC_GAME_API MoveSpline { friend class WorldPackets::Movement::CommonMovement; friend class WorldPackets::Movement::MonsterMove; public: typedef Spline<int32> MySpline; enum UpdateResult { Result_None = 0x01, Result_Arrived = 0x02, Result_NextCycle = 0x04, Result_NextSegment = 0x08 }; protected: MySpline spline; FacingInfo facing; uint32 m_Id; MoveSplineFlag splineflags; int32 time_passed; // currently duration mods are unused, but its _currently_ //float duration_mod; //float duration_mod_next; float vertical_acceleration; float initialOrientation; int32 effect_start_time; int32 point_Idx; int32 point_Idx_offset; int32 last_point_Idx; Optional<SpellEffectExtraData> spell_effect_extra; Optional<AnimTierTransition> anim_tier; void init_spline(const MoveSplineInitArgs& args); protected: MySpline::ControlArray const& getPath() const { return spline.getPoints(); } Location computePosition(int32 time_point, int32 point_index) const; void computeParabolicElevation(int32 time_point, float& el) const; void computeFallElevation(int32 time_point, float& el) const; UpdateResult _updateState(int32& ms_time_diff); int32 next_timestamp() const { return spline.length(point_Idx + 1); } int32 segment_time_elapsed() const { return next_timestamp() - time_passed; } int32 timeElapsed() const { return Duration() - time_passed; } int32 timePassed() const { return time_passed; } public: int32 Duration() const { return spline.length(); } MySpline const& _Spline() const { return spline; } int32 _currentSplineIdx() const { return point_Idx; } int32 _lastSplineIdx() const { return last_point_Idx; } void _Finalize(); void _Interrupt() { splineflags.done = true; } public: void Initialize(const MoveSplineInitArgs&); bool Initialized() const { return !spline.empty(); } MoveSpline(); template<class UpdateHandler> void updateState(int32 difftime, UpdateHandler& handler) { ASSERT(Initialized()); last_point_Idx = point_Idx; do handler(_updateState(difftime)); while (difftime > 0); } void updateState(int32 difftime) { ASSERT(Initialized()); last_point_Idx = point_Idx; do _updateState(difftime); while (difftime > 0); } Location ComputePosition() const; Location ComputePosition(int32 time_offset) const; uint32 GetId() const { return m_Id; } bool Finalized() const { return splineflags.done; } bool isCyclic() const { return splineflags.cyclic; } bool isFalling() const { return splineflags.falling; } Vector3 const& FinalDestination() const { return Initialized() ? spline.getPoint(spline.last()) : Vector3::zero(); } Vector3 const& CurrentDestination() const { return Initialized() ? spline.getPoint(point_Idx + 1) : Vector3::zero(); } int32 currentPathIdx() const; bool onTransport; bool splineIsFacingOnly; std::string ToString() const; }; } #endif // TRINITYSERVER_MOVEPLINE_H
[ "43292003+Hooaah@users.noreply.github.com" ]
43292003+Hooaah@users.noreply.github.com
d3b86e76b4d9fbc5bbde43e48e8d11d1fe59b657
1063c05173aba89a7ce859190aed30e7a6494402
/ClrClassLib/ClrClassLib.h
bb79f48b244bcbc96d6d80e3efa65dcc293480d5
[ "MIT" ]
permissive
CMHAS/RealtimeSolver
8b8c4aff1680485978339c4510bb6c755dd51fe3
113ba8f8011a0ec2b70a3600367339f4f7f39f3f
refs/heads/master
2021-07-16T08:47:05.539873
2021-04-27T21:19:31
2021-04-27T21:19:31
245,894,688
0
0
null
null
null
null
UTF-8
C++
false
false
1,170
h
#pragma once #include "CalcTime.h" using namespace System; using namespace System::Diagnostics; namespace ClrClassLib { template<class T> public ref class MyObject { protected: T* m_instance; public: MyObject() { m_instance = new T; } virtual ~MyObject() { this->!MyObject(); } !MyObject() { if (m_instance != nullptr) { delete m_instance; } } }; public ref class Class1 : MyObject<CppNative::CalcTime> { template<typename T> array<array<double>^>^ makeArray(T&& vec); public: ~Class1() { m_instance->~CalcTime(); } array<array<double>^>^ setAcc(const double val); array<array<double>^>^ setRet(const double val); array<array<double>^>^ setDist(const double val); array<array<double>^>^ setStart(const double val); array<array<double>^>^ setCruise(const double val); array<array<double>^>^ setEnd(const double val); }; template<typename T> inline array<array<double>^>^ Class1::makeArray(T&& vec) { array<array<double>^>^ arr = gcnew array<array<double>^>(static_cast<int>(vec.size())); int i{0}; for (const auto& [time, vel] : vec) { arr[i++] = gcnew array<double>{ time, vel }; } return arr; } }
[ "magnus1974@hotmail.com" ]
magnus1974@hotmail.com
9ff04fad2d33d00793abd8dce2ff0336b536f0cf
c2777a178fa6e7fb0c8788ede784ed9645c09723
/mypredictor.h
093c6fc4b3ab883635418d001bfea7e266858cc2
[]
no_license
vinusankars/Value-predicton
56085d7928bb136173bbf2b196b16802f50c8eae
7b462293d6212f80c330b025322ca443df891efd
refs/heads/master
2020-04-05T03:17:35.338092
2018-11-07T07:46:28
2018-11-07T07:46:28
156,508,846
1
1
null
null
null
null
UTF-8
C++
false
false
1,778
h
#include <vector> #include <deque> // Coded by S. Vinu Sankar and S. Deepak Narayanan struct MyFCMPredictor { struct FirstLevelEntry { uint64_t predictTimeIndex; uint64_t commitTimeIndex; uint64_t inflight; FirstLevelEntry() : predictTimeIndex(0), commitTimeIndex(0), inflight(0) {} }; std::vector<FirstLevelEntry> firstLevelTable; struct SecondLevelEntry { uint64_t pred; uint8_t conf; SecondLevelEntry() : pred(0), conf(0) {}; }; std::vector<SecondLevelEntry> secondLevelTable; struct InflightInfo { uint64_t seqNum; uint64_t firstLevelIndex; uint64_t secondLevelIndex; InflightInfo() : seqNum(0), firstLevelIndex(0) {} InflightInfo(uint64_t sn, uint64_t fidx, uint64_t sidx) : seqNum(sn), firstLevelIndex(fidx), secondLevelIndex(sidx) {} }; struct Stride // Structure for the stride { uint64_t pc; // stores the program counter value, 64 bits uint64_t stride; // stores the stride value, the step taken by PC, 64 bits uint64_t value; // the actual address value, 64 bits }; std::vector<Stride> strideTable; std::deque<InflightInfo> inflightPreds; uint64_t globalHistoryRegister; uint64_t pathHistoryRegister; uint64_t addressHistoryRegister; uint64_t firstLevelMask; uint64_t lastPrediction; uint32_t strideCount; // 32 bit count for stride, if it exceeds 10, clear the structure public: MyFCMPredictor() : globalHistoryRegister(0), pathHistoryRegister(0), addressHistoryRegister(0), strideCount(0) { firstLevelTable.resize(4096 * 4); secondLevelTable.resize(4096 * 4); strideTable.resize(300); // Total 300*64*3 bits = 7.03125 KB firstLevelMask = (4096 * 4) - 1; lastPrediction = 0xdeadbeef; } };
[ "noreply@github.com" ]
noreply@github.com
dee997d5093e0ca909bd9d0a3b23696b81a6b711
0c5d28d213850ee836de83f377e191e34e7d7fc7
/test.cpp
308f92339586223e4ca5faf01b32a9e2fc8a96c1
[]
no_license
bodgergely/PathFinder
fe8729282dbac60de2290b3b566784a41d963a90
62fc04cf215baea04fa000f0387e52a2a2949cda
refs/heads/master
2021-01-22T17:38:32.655075
2019-02-09T20:26:35
2019-02-09T20:26:35
64,288,969
0
0
null
null
null
null
UTF-8
C++
false
false
6,496
cpp
#include "DictionaryDash.h" #include <gtest/gtest.h> #include <random> #include <string> #include <cstdlib> #include <ctime> #include <chrono> #include <fstream> #include <cstring> #include <algorithm> using namespace std; using Path = DictionaryDash::Path; string generateRandomWord(int len) { string s(len,'a'); unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::minstd_rand0 generator (seed); std::uniform_int_distribution<int> distribution(0,'z'-'a'); for(int i=0;i<len;i++) { int num = distribution(generator); char c = 'a' + num; s[i] = c; } return s; } #ifndef _WIN32 void populateDictionary(unordered_set<string>& wordSet, int i) { ifstream dictFile("/usr/share/dict/words", std::ifstream::in); string word; while(getline(dictFile, word)) { if(word.size()== i && !strchr(word.c_str(), '\'')) { std::transform(word.begin(), word.end(), word.begin(), ::tolower); wordSet.insert(word); } } } #endif TEST(DictionaryDash,sample) { string start = "hit"; string target = "cog"; vector<string> words {"hit","dot","dog","cog","hot"}; DictionaryDash dd_astar(words, start.size(), Algo::AStar); DictionaryDash dd_bfs(words, start.size(), Algo::BreadthFirstSearch); Path astarPath = dd_astar.path(start, target); Path bfsPath = dd_bfs.path(start, target); ASSERT_EQ(4,astarPath.pathLen()); ASSERT_EQ(4,bfsPath.pathLen()); } TEST(DictionaryDash,unreachable) { string start = "hit"; string target = "cog"; vector<string> words {"hit","dog","cog"}; DictionaryDash dd_astar(words, start.size(), Algo::AStar); DictionaryDash dd_bfs(words, start.size(), Algo::BreadthFirstSearch); Path astarPath = dd_astar.path(start, target); Path bfsPath = dd_bfs.path(start, target); ASSERT_EQ(-1,astarPath.pathLen()); ASSERT_EQ(-1,bfsPath.pathLen()); } TEST(DictionaryDash,reachItself) { string start = "hit"; string target = "hit"; vector<string> words {"hit","dot","dog","cog","hot"}; DictionaryDash dd_astar(words, start.size(), Algo::AStar); DictionaryDash dd_bfs(words, start.size(), Algo::BreadthFirstSearch); Path astarPath = dd_astar.path(start, target); Path bfsPath = dd_bfs.path(start, target); ASSERT_EQ(0,astarPath.pathLen()); ASSERT_EQ(0,bfsPath.pathLen()); } #ifndef _WIN32 struct TimingAvgs { TimingAvgs() : astar(0.0), bfs(0.0){} TimingAvgs(double astar_, double bfs_) : astar(astar_), bfs(bfs_) {} double astar; double bfs; }; TimingAvgs testWordSize(int wordlen, bool verbose) { unordered_set<string> wordSet; vector<string> words; if(verbose) cout << "Word size: " << wordlen << endl; populateDictionary(wordSet, wordlen); for(const string& w : wordSet) { words.push_back(w); } wordSet.clear(); double astarDurAvg = 0; double bfsDurAvg = 0; int attempts = 0; while(true) { unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::minstd_rand0 generator (seed); std::uniform_int_distribution<int> distribution(0,words.size()-1); string start = words[distribution(generator)]; string target = words[distribution(generator)]; DictionaryDash dd_astar(words, start.size(), Algo::AStar); DictionaryDash dd_bfs(words, start.size(), Algo::BreadthFirstSearch); auto startAStar = std::chrono::system_clock::now(); Path astarPath = dd_astar.path(start, target); auto endAStar = std::chrono::system_clock::now(); Path bfsPath = dd_bfs.path(start, target); auto endBFS = std::chrono::system_clock::now(); auto astarDur = std::chrono::duration_cast<std::chrono::microseconds>(endAStar-startAStar); auto bfsDur = std::chrono::duration_cast<std::chrono::microseconds>(endBFS-endAStar); ++attempts; astarDurAvg+=(double)astarDur.count(); astarDurAvg/=(double)attempts; bfsDurAvg+=(double)bfsDur.count(); bfsDurAvg/=(double)attempts; EXPECT_EQ(astarPath.pathLen(),bfsPath.pathLen()); if(astarPath.pathLen()!=-1) { if(verbose) { cout << "start: " << start << " target: " << target << endl; cout << "AStar steps: " << astarPath.pathLen() << " Path: " << astarPath.toString() << endl; cout << "BFS steps: " << bfsPath.pathLen() << " Path: " << bfsPath.toString() << endl; } break; } } return TimingAvgs(astarDurAvg, bfsDurAvg); } map<int, TimingAvgs> testWordSizes(int minLen, int maxLen, bool verbose) { map<int, TimingAvgs> timings; for(int wordlen=minLen;wordlen<=maxLen;wordlen++) { TimingAvgs times = testWordSize(wordlen, verbose); timings[wordlen] = times; } return timings; } TEST(DictionaryDash, realDictionary) { testWordSizes(3,8, true); } TEST(DictionaryDash, realDictionaryStressTest) { int totalTests = 15; map<int, TimingAvgs> stressTimes; for(int i=1;i<=totalTests;i++) { cout << "Test: " << i << " of " << totalTests << endl; map<int, TimingAvgs> times = testWordSizes(3,8, false); for(const pair<int, TimingAvgs>& time : times) { TimingAvgs& avg = stressTimes[time.first]; avg.astar+=time.second.astar; avg.astar/=(double)i; avg.bfs+=time.second.bfs; avg.bfs/=(double)i; } } cout << "Avg calculation times (microsecs): \n"; for(const auto& p : stressTimes) { cout << "Word len : " << p.first << "\tAStar: " << p.second.astar << " BFS: " << p.second.bfs << " Diff: " << abs(p.second.astar - p.second.bfs) << endl; } } #endif /* * Combinatorial explosion makes the below test useless * */ /* TEST(DictionaryDash, random_8) { unordered_set<string> wordSet; vector<string> words; int wordNum = 100000; while(true) { wordSet.insert(generateRandomWord(8)); if(wordSet.size() == wordNum) break; } for(const string& w : wordSet) { words.push_back(w); } wordSet.clear(); int attempts = 0; while(true) { cout << "Attempts to reach: " << ++attempts << endl; unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::minstd_rand0 generator (seed); std::uniform_int_distribution<int> distribution(0,wordNum-1); string start = words[distribution(generator)]; string target = words[distribution(generator)]; cout << "start: " << start << " target: " << target << endl; DictionaryDash dd_astar(words, start.size(), Algo::AStar); DictionaryDash dd_bfs(words, start.size(), Algo::BreadthFirstSearch); int stepsAstar = dd_astar.path(start, target); int stepsBfs = dd_bfs.path(start, target); ASSERT_EQ(stepsAstar,stepsBfs); if(stepsAstar!=-1) { cout << "AStar steps: " << stepsAstar << endl; cout << "BFS steps: " << stepsBfs << endl; break; } } } */
[ "bodgergely@hotmail.com" ]
bodgergely@hotmail.com
9d815571513fd792c0bd64f58620f44d9568a126
98e811648bf3e2342d8c36c03caee0bb92a7d8d5
/code/prototype/include/allscale/runtime/data/data_item_manager.h
8ec41336466bc2ade869d443b9719d3ce4c59309
[]
no_license
allscale/allscale_runtime_prototype
08b49f734921e43cf0f97e487f0a3819b64e0e8d
3b50870c63f4d09c7780fd6159cf2db6cb8ae156
refs/heads/master
2020-05-02T08:55:10.379887
2019-03-08T14:18:54
2019-03-08T14:18:54
177,855,770
0
0
null
null
null
null
UTF-8
C++
false
false
16,693
h
/* * The prototype implementation of the data item interface. * * Created on: Jul 23, 2018 * Author: herbert */ #pragma once #include <map> #include <unordered_map> #include <memory> #include <mutex> #include <typeinfo> #include <typeindex> #include "allscale/utils/assert.h" #include "allscale/utils/fiber/read_write_lock.h" #include "allscale/runtime/com/node.h" #include "allscale/runtime/com/network.h" #include "allscale/runtime/com/hierarchy.h" #include "allscale/runtime/data/data_item_reference.h" #include "allscale/runtime/data/data_item_requirement.h" #include "allscale/runtime/data/data_item_location.h" #include "allscale/runtime/data/data_item_migration.h" #include "allscale/runtime/data/data_item_statistic.h" namespace allscale { namespace runtime { namespace data { // -- setup -- // start up the treeture service within the given network void installDataItemManagerService(com::Network&); // --- forward declarations of data index interfaces --- class DataItemIndexService; // ----------------------------------------------------- /** * A fragment manager is managing the locally maintained data of a single data item. * It thus manages the fragment, its content, and the shared data. */ template<typename DataItem> class DataFragmentHandler { // Test that the passed data item type is valid. static_assert(allscale::api::core::is_data_item<DataItem>::value, "Can only be instantiated for data items!"); // ------ some type definitions ------ using shared_data_type = typename DataItem::shared_data_type; using region_type = typename DataItem::region_type; using fragment_type = typename DataItem::fragment_type; using facade_type = typename DataItem::facade_type; // -- node-local management information -- // the management data shared among all instances shared_data_type shared_data; // the locally maintained data fragment fragment_type fragment; // the locally maintained exclusive regions region_type exclusive; // the total reserved region (must be a super-set of exclusive) region_type reserved; // a lock for operation synchronization mutable allscale::utils::fiber::ReadWriteLock lock; // the kind of guards used for synchronization using read_guard = allscale::utils::fiber::ReadGuard; using write_guard = allscale::utils::fiber::WriteGuard; public: DataFragmentHandler(const shared_data_type& shared_data) : shared_data(shared_data), fragment(this->shared_data) { // make sure that nothing is owned yet assert_true(exclusive.empty()); assert_true(reserved.empty()); assert_true(fragment.getCoveredRegion().empty()); } // no copy but move DataFragmentHandler(const DataFragmentHandler&) = delete; DataFragmentHandler(DataFragmentHandler&&) = default; /** * Obtains access to the managed fragment through a facade. * The fragment itself is not exposed to avoid messing with covered regions. */ facade_type getDataItem() { return fragment.mask(); } private: friend class DataItemManager; /** * Provides access to the maintained fragment type to friend types. */ fragment_type& getFragment() { return fragment; } public: region_type getDataItemSize() const { return fragment.getTotalSize(); } void resizeExclusive(const region_type& newSize) { // reserve the area reserve(newSize); // update the ownership write_guard g(lock); exclusive = newSize; } const region_type& getExclusiveRegion() const { return exclusive; } void reserve(const region_type& area) { // lock down this fragment write_guard g(lock); // test whether a change is necessary if (allscale::api::core::isSubRegion(area,reserved)) return; // grow reserved area reserved = region_type::merge(reserved,area); // resize fragment fragment.resize(reserved); } allscale::utils::optional<allscale::utils::Archive> extract(const region_type& region) const { allscale::utils::ArchiveWriter out; { // lock down this fragment read_guard g(lock); if (!allscale::api::core::isSubRegion(region,exclusive)) return {}; // do not extract non-exclusive content! fragment.extract(out,region_type::intersect(region,getDataItemSize())); } return std::move(out).toArchive(); } void insert(allscale::utils::Archive& data) { // lock down this fragment write_guard g(lock); allscale::utils::ArchiveReader in(data); fragment.insert(in); } }; /** * The service running on each node for handling data items of various types. */ class DataItemManagerService { /** * A common base type of all data item registers. */ class DataItemRegisterBase { public: virtual ~DataItemRegisterBase() {}; virtual void import(const DataItemMigrationData&) =0; virtual void extract(const DataItemRegions&, DataItemMigrationData&) =0; virtual void takeOwnership(const DataItemMigrationData&) =0; virtual void collectExclusiveRegions(DataItemRegions&) const =0; virtual void addExclusiveRegions(const DataItemRegions&) =0; virtual void removeExclusiveRegions(const DataItemRegions&) =0; }; /** * A register for data items of a specific type. */ template<typename DataItem> class DataItemRegister : public DataItemRegisterBase { using reference_type = DataItemReference<DataItem>; using region_type = typename DataItem::region_type; using shared_data_type = typename DataItem::shared_data_type; using facade_type = typename DataItem::facade_type; // the index of registered items std::unordered_map<DataItemReference<DataItem>,std::unique_ptr<DataFragmentHandler<DataItem>>> items; // the network this service is a part of com::Network& network; // the rank this service is running on com::rank_t rank; public: DataItemRegister(com::Network& network, com::rank_t rank) : network(network), rank(rank) {}; DataItemRegister(const DataItemRegister&) = delete; DataItemRegister(DataItemRegister&&) = delete; // registers a new data item in the local registry void registerItem(const reference_type& ref, const shared_data_type& shared) { assert_not_pred1(contains,ref); items.emplace(ref,std::make_unique<DataFragmentHandler<DataItem>>(shared)); } region_type getDataItemSize(const reference_type& ref) const { auto pos = items.find(ref); assert_true(pos != items.end()); return pos->second->getDataItemSize(); } void extract(const DataItemRegions& regions, DataItemMigrationData& res) override { regions.forAll<DataItem>([&](const reference_type& ref, const region_type& region){ auto pos = items.find(ref); // one can not extract what one does not have if (pos == items.end()) return; // obtain data auto data = pos->second->extract(region); // if successful, add data to result if (bool(data)) res.add(ref,region,std::move(*data)); }); } allscale::utils::optional<allscale::utils::Archive> extract(const reference_type& ref, const region_type& region) { return get(ref).extract(region); } void insert(const reference_type& ref, allscale::utils::Archive& archive) { get(ref).insert(archive); } void import(const DataItemMigrationData& data) override { data.forEach<DataItem>([&](reference_type ref, const region_type& region, allscale::utils::Archive& archive){ if (region.empty()) return; auto& fragment = get(ref); fragment.reserve(region); fragment.insert(archive); }); } void takeOwnership(const DataItemMigrationData& data) override { data.forEach<DataItem>([&](reference_type ref, const region_type& region, allscale::utils::Archive& archive){ if (region.empty()) return; auto& fragment = get(ref); assert_pred2(allscale::api::core::isSubRegion,region,fragment.getExclusiveRegion()); fragment.insert(archive); }); } void collectExclusiveRegions(DataItemRegions& res) const override { for(const auto& cur : items) { auto region = region_type::intersect(cur.second->getExclusiveRegion(),cur.second->getDataItemSize()); if (region.empty()) continue; res.add(cur.first,region); } } void addExclusiveRegions(const DataItemRegions& regions) override { regions.forAll<DataItem>([&](reference_type ref, const region_type& region){ if (region.empty()) return; auto& fragment = get(ref); fragment.resizeExclusive(region_type::merge(fragment.getExclusiveRegion(),region)); }); } void removeExclusiveRegions(const DataItemRegions& regions) override { regions.forAll<DataItem>([&](reference_type ref, const region_type& region){ if (region.empty()) return; auto& fragment = get(ref); fragment.resizeExclusive(region_type::difference(fragment.getExclusiveRegion(),region)); }); } // obtains access to a selected fragment handler DataFragmentHandler<DataItem>& get(const reference_type& ref) { assert_pred1(contains,ref) << "Known Items: " << allscale::utils::join(",",items,[](std::ostream& out, const auto& entry) { out << entry.first; }); return *items.find(ref)->second; } private: bool contains(const reference_type& ref) const { return items.find(ref) != items.end(); } }; // the maintained register of data item registers (type specific) std::unordered_map<std::type_index,std::unique_ptr<DataItemRegisterBase>> registers; // the network this service is a part of com::Network& network; // the rank this service is running on com::rank_t rank; // the list of all regions registered in the system DataItemRegions fullRegions; // the lock to protect the exclusive region information mutable allscale::utils::fiber::ReadWriteLock exclusiveRegionsLock; // the list of exclusively owned regions DataItemRegions exclusiveRegions; // a cache for resolved data locations mutable DataItemLocationCache locationCache; // -- statistics -- std::atomic<uint64_t> allocate_call_count; std::atomic<uint64_t> release_call_count; std::atomic<uint64_t> locate_call_count; std::atomic<uint64_t> retrieve_call_count; std::atomic<uint64_t> acquire_call_count; public: DataItemManagerService(com::Node&); // a function to retrieve the local instance of this service static DataItemManagerService& getLocalService(); /** * Creates a new data item instance. */ template<typename DataItem, typename ... Args> DataItemReference<DataItem> create(Args&& ... args) { using shared_data_t = typename DataItem::shared_data_type; // create a new ID auto res = DataItemReference<DataItem>::getFresh(); // create shared data object shared_data_t sharedInfo(std::forward<Args>(args)...); // register data item in network (also locally) com::Network::getNetwork().broadcastAndSync(&DataItemManagerService::registerDataItem<DataItem>)(res,sharedInfo); // return reference return res; } /** * Obtains access to a data item maintained by this manager. */ template<typename DataItem> typename DataItem::facade_type get(const DataItemReference<DataItem>& ref) { return getRegister<DataItem>().get(ref).getDataItem(); } private: friend class DataItemManager; /** * Obtains access to the fragment handler managing the referenced data item. */ template<typename DataItem> DataFragmentHandler<DataItem>& getFragmentHandlerOf(const DataItemReference<DataItem>& ref) { return getRegister<DataItem>().get(ref); } public: /** * Requests the allocation of the requested data item regions. Blocks until available. */ void allocate(const DataItemRequirements& reqs); /** * Releases the specified data requirements. * TODO: this could also be matched to an allocate call through some handler */ void release(const DataItemRequirements& reqs); /** * Instructs the data item manager to refresh the given data regions locally. */ void retrieve(const DataItemRegions& regions); /** * Acquires ownership on the stated requirements (where missing). */ void acquire(const DataItemRegions& regions); /** * Determines whether the given requirements care fully covered by the locally available data. */ bool isCoveredLocally(const DataItemRequirements& reqs); // --- protocol interface --- template<typename DataItem> void registerDataItem(DataItemReference<DataItem> ref, const typename DataItem::shared_data_type& shared_data) { // register shared data auto& reg = getRegister<DataItem>(); reg.registerItem(ref,shared_data); // add new data item to full regions fullRegions.add(ref,reg.getDataItemSize(ref)); } /** * Retrieves a serialized version of a data item stored at this locality. */ template<typename DataItem> allscale::utils::optional<allscale::utils::Archive> extract(DataItemReference<DataItem> ref, const typename DataItem::region_type& region) { return getRegister<DataItem>().extract(ref,region); } /** * Retrieves a serialized version of the data stored at this locality. */ DataItemMigrationData extractRegions(const DataItemRegions& regions) const; /** * Retrieves a serialized version of a data item stored at this locality. */ template<typename DataItem> void insert(DataItemReference<DataItem> ref, allscale::utils::Archive& archive) { return getRegister<DataItem>().insert(ref,archive); } // --- local interface --- void addExclusive(const DataItemRegions& regions); void removeExclusive(const DataItemRegions& regions); template<typename DataItem> void acquire(const DataItemReference<DataItem>& ref, const typename DataItem::region_type& region) { // channel through the type-erased interface DataItemRegions regions; regions.add(ref,region); acquire(regions); } void takeOwnership(const DataItemMigrationData& data); template<typename DataItem> typename DataItem::region_type getExclusiveRegion(const DataItemReference<DataItem>& ref) const { return getRegister<DataItem>().get(ref).getExclusiveRegion(); } /** * Obtains the full size of all data items registered in the system. */ const DataItemRegions& getFullRegions() const { return fullRegions; } /** * Obtains the exclusive regions maintained locally. */ DataItemRegions getExclusiveRegions() const; /** * Obtains a summary of the accesses statistics to this service instance. */ DataItemManagerStatisticEntry getLocalStatistic() const; /** * Obtains a system wide summary of the access statistics of the data item manager service. */ DataItemManagerStatistic getStatistics() const; private: // obtains the register for a given data item type template<typename DataItem> DataItemRegister<DataItem>& getRegister() { auto pos = registers.find(typeid(DataItem)); if (pos != registers.end()) { return *static_cast<DataItemRegister<DataItem>*>(pos->second.get()); } auto instance = std::make_unique<DataItemRegister<DataItem>>(network,rank); auto& res = *instance; registers[typeid(DataItem)] = std::move(instance); return res; } template<typename DataItem> DataItemRegister<DataItem>& getRegister() const { auto pos = registers.find(typeid(DataItem)); assert_true(pos != registers.end()); return *static_cast<DataItemRegister<DataItem>*>(pos->second.get()); } }; /** * The facade of the data item management. */ class DataItemManager { // a private constructor (just a utility class) DataItemManager() {} public: /** * Creates a new data item instance. */ template<typename DataItem, typename ... Args> static DataItemReference<DataItem> create(Args&& ... args) { // forward this call to the local service return DataItemManagerService::getLocalService().create<DataItem>(std::forward<Args>(args)...); } /** * Obtains access to a data item maintained by this manager. */ template<typename DataItem> static typename DataItem::facade_type get(const DataItemReference<DataItem>& ref) { // use cached fragment to obtain facade, if available if (ref.fragment) { return ref.fragment->mask(); } // obtain reference to locally maintained fragment auto& fragment = DataItemManagerService::getLocalService().getFragmentHandlerOf(ref).getFragment(); // cache lookup result ref.fragment = &fragment; // return mask return fragment.mask(); } }; } // end of namespace com } // end of namespace runtime } // end of namespace allscale // todo: merge those two files! #include "allscale/runtime/data/data_item_index.h"
[ "herbert@dps.uibk.ac.at" ]
herbert@dps.uibk.ac.at
c46a5046f456ed5b4e13b317183f0a44d5a41321
9abd3d7cc7b72500ca1592571d1b4ca2741df063
/TC/tcCtl/TCPicture.cpp
fa12947e942e476e2a3e02ebfd52a10be76f4582
[]
no_license
15831944/TCIDE
306291b81ba429553978b4bd63efa420480e6005
beb27d7375b14cf5e5126d8bb71d65844a217690
refs/heads/master
2022-01-28T07:45:29.125991
2018-07-10T08:46:35
2018-07-10T08:46:35
null
0
0
null
null
null
null
GB18030
C++
false
false
1,363
cpp
// TCPicture.cpp : 实现文件 // #include "stdafx.h" #include "../TC.h" #include "TCPicture.h" #include "../TCRunTimeManager.h" // CTCPicture IMPLEMENT_DYNAMIC(CTCPicture, CStatic) CTCPicture::CTCPicture() { m_strPicName = _T(""); m_clicked = _T(""); } CTCPicture::~CTCPicture() { } BEGIN_MESSAGE_MAP(CTCPicture, CStatic) END_MESSAGE_MAP() // CTCPicture 消息处理程序 void CTCPicture::SetRCPicture(CString name) { if( name != _T("")) { CString bmpPath; bmpPath.Format(_T("%s\\资源\\%s"),CTCRunTimeManager::g_ProjSourcePath,name); CRect rect; this->GetWindowRect(&rect); this->GetParent()->ScreenToClient(&rect); HRESULT ret = img.Load(bmpPath); if(!img.IsNull()) { HBITMAP bitmap = img.Detach(); this->SetBitmap(bitmap); m_strPicName = name; this->MoveWindow(rect.left,rect.top,rect.right-rect.left,rect.bottom-rect.top,TRUE); this->Invalidate(); } } } void CTCPicture::SetPicture(CString path) { CRect rect; this->GetWindowRect(&rect); this->GetParent()->ScreenToClient(&rect); HRESULT ret = img.Load(path); if(!img.IsNull()) { HBITMAP bitmap = img.Detach(); this->SetBitmap(bitmap); this->MoveWindow(rect.left,rect.top,rect.right-rect.left,rect.bottom-rect.top,TRUE); this->Invalidate(); } } void CTCPicture::TCSetClickEvent(CString str) { m_clicked = str; }
[ "johnwilliam@126.com" ]
johnwilliam@126.com
ad991ddcbc31ecf9e3df4a3d9865ccb9ca82a4b3
c9fde4576216a22e8d5711bbe97adda1aafa2f08
/inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/reorder/reorder_weights_kernel.h
635b3466dd4d00db872c59c682d077175c0aefe3
[ "BSL-1.0", "Apache-2.0" ]
permissive
dliang0406/dldt
c703d6a837de3f996528fc8a9543f9530b23342c
d9b10abcebafe8b10ba81e09e433de7a366c072c
refs/heads/2018
2020-04-03T08:24:47.723353
2018-10-29T07:58:05
2018-10-29T07:58:05
155,132,108
3
1
Apache-2.0
2019-10-10T08:39:46
2018-10-29T01:03:54
C++
UTF-8
C++
false
false
1,065
h
/* // Copyright (c) 2016 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #pragma once #include "reorder_kernel_base.h" namespace kernel_selector { class ReorderWeightsKernel : public ReorderKernelBase { public: ReorderWeightsKernel() : ReorderKernelBase("reorder_weights") {} virtual ~ReorderWeightsKernel() {} virtual KernelsData GetKernelsData(const Params& params, const optional_params& options) const override; virtual ParamsKey GetSupportedKey() const override; }; }
[ "openvino_pushbot@intel.com" ]
openvino_pushbot@intel.com
48562261629e5e7e6fe6a02d643410c0c9c1c2c9
480908579a03d69a3b0f08825d2d8db9e75c04cb
/src/Buffer.h
c136202a6c1df8dcc3839a78eb93177bb60e45f9
[]
no_license
m1keall1son/ffplayer
70c3ef84610e8135338088dc41cf8079f95823e5
822e10dd043c9f8ce8984ff51cd46e07d32571c4
refs/heads/master
2020-03-12T07:17:39.128036
2018-04-21T19:36:54
2018-04-21T19:36:54
130,503,152
1
0
null
null
null
null
UTF-8
C++
false
false
653
h
// // Buffer.hpp // sixmonths // // Created by Michael Allison on 4/19/18. // #pragma once #include <stdint.h> namespace ffmpeg { class Buffer { public: Buffer(); ~Buffer(); Buffer(uint8_t* data, uint32_t size); Buffer(uint32_t size); void allocate(uint32_t size); void clear(); inline uint8_t* data(){return mData;} inline uint32_t size()const{return mSize;} inline bool isAllocated()const{ return mData; } private: bool mOwnsData; uint8_t* mData; uint32_t mSize; }; }//end namespace ffmpeg
[ "michaelallison@MALLISON.local" ]
michaelallison@MALLISON.local
80084797d4cfda657e49707361fc0b6eb9ee73e1
2666da22a8ca551bd50f94e15c3e15e7a1afbf9f
/gpufilereader.cpp
5993653fe13b9d3ef700396e52dd1bfe81ca8f2d
[]
no_license
MWATelescope/cotter
c97e5ef7ff9b1a1393f96c30c8fa448e68174115
0f99a09cb21721666d2ba328ab2257484b4cd183
refs/heads/master
2022-01-30T16:45:33.803943
2022-01-20T05:41:08
2022-01-20T05:41:08
139,799,883
11
4
null
2021-04-12T09:24:08
2018-07-05T05:41:20
C++
UTF-8
C++
false
false
12,719
cpp
#include "gpufilereader.h" #include "progressbar.h" #include <complex> #include <iostream> #include <sstream> #include <stdexcept> #include <thread> void GPUFileReader::openFiles() { int status = 0; bool hasWarnedAboutDifferentTimes = false; _hasStartTime = false; std::vector<long> startTimePerFile(_filenames.size()); for(size_t i=0; i!=_filenames.size(); ++i) { const std::string &curFilename = _filenames[i]; fitsfile *fptr = 0; if(curFilename.empty()) { std::cout << "(Skipping unavailable file)\n"; _fitsFiles.push_back(0); _fitsHDUCounts.push_back(0); } else if(!fits_open_file(&fptr, curFilename.c_str(), READONLY, &status)) { _fitsFiles.push_back(fptr); int hduCount; fits_get_num_hdus(fptr, &hduCount, &status); checkStatus(status); _fitsHDUCounts.push_back(hduCount); std::cout << "There are " << hduCount << " HDUs in file " << _filenames[i]; if(_offlineFormat) std::cout << " (offline format: all are used!)"; std::cout << '\n'; long thisFileTime; fits_read_key(fptr, TLONG, "TIME", &thisFileTime, 0, &status); checkStatus(status); if(!_hasStartTime) { _startTime = thisFileTime; _hasStartTime = true; } startTimePerFile[i] = thisFileTime; if(_startTime != thisFileTime) { if(!hasWarnedAboutDifferentTimes || thisFileTime > _startTime) { std::cout << "WARNING: file number " << (i+1) << " of current time range has different start time!\n" "Current file start time: " << thisFileTime << " previous file had: " << _startTime << ".\n"; } if(thisFileTime > _startTime) { _startTime = thisFileTime; if(_doAlign) std::cout << "Using start time of " << _startTime << " and aligning other files accordingly.\n"; else std::cout << "Using start time of " << _startTime << " and NOT aligning files accordingly as requested:\n" "output will likely be mis-aligned!\n"; } hasWarnedAboutDifferentTimes = true; } } else { throwError(status, std::string("Cannot open file ") + _filenames[i]); exit(1); } } _isOpen = true; _hduOffsetsPerFile.resize(_filenames.size()); for(size_t i=0; i!=_filenames.size(); ++i) { if(_filenames[i].empty()) _hduOffsetsPerFile[i] = 0; else _hduOffsetsPerFile[i] = (int) round(double((long) _startTime - startTimePerFile[i]) / _integrationTime); if(hasWarnedAboutDifferentTimes) { if(i == 0) std::cout << "HDU offsets per file: [" << _hduOffsetsPerFile[i]; else std::cout << ',' << _hduOffsetsPerFile[i]; } } if(hasWarnedAboutDifferentTimes) std::cout << "]\n"; _onHDUOffsetsChange(_hduOffsetsPerFile); } void GPUFileReader::closeFiles() { for(size_t i=0; i!=_fitsFiles.size(); ++i) { int status = 0; fitsfile *fptr = _fitsFiles[i]; if(fptr != 0) { fits_close_file(fptr, &status); checkStatus(status); } } _fitsFiles.clear(); _isOpen = false; } bool GPUFileReader::Read(size_t &bufferPos, size_t bufferLength) { // If we are already past the end of the files, stop immediately if(_currentHDU > _stopHDU) return false; const size_t nPol = 4; const size_t nBaselines = (_nAntenna + 1) * _nAntenna / 2; const size_t gpuMatrixSizePerFile = _nChannelsInTotal * nBaselines * nPol / _filenames.size(); // cuda matrix length per file _shuffleTasks.clear(); _availableGPUMatrixBuffers.clear(); std::vector<std::vector<std::complex<float> > > gpuMatrixBuffers(_threadCount); std::vector<std::thread> threadGroup; for(size_t i=0; i!=_threadCount; ++i) { gpuMatrixBuffers[i].resize(gpuMatrixSizePerFile); _availableGPUMatrixBuffers.write(&gpuMatrixBuffers[i][0]); threadGroup.emplace_back(&GPUFileReader::shuffleThreadFunc, this); } if(!_isOpen) { openFiles(); _currentHDU = _offlineFormat ? 1 : 2; // header to start reading findStopHDU(); } initMapping(); ProgressBar progressBar("Reading GPU files"); size_t endingBufferPos = bufferLength; bool moreAvailable = false; for (size_t iFile = 0; iFile != _filenames.size(); ++iFile) { if(!_filenames[iFile].empty()) { size_t fileBufferPos = bufferPos, fileHDU = _currentHDU; if(_doAlign) { // These statements will align a file with the times given in the individual gpubox fits files. if(_hduOffsetsPerFile[iFile] <= (int) bufferPos) fileBufferPos = bufferPos - _hduOffsetsPerFile[iFile]; else { fileHDU += _hduOffsetsPerFile[iFile] - bufferPos; fileBufferPos = bufferPos; } } size_t fileStopHDU = _fitsHDUCounts[iFile]; size_t hdusAvailable = fileStopHDU - fileHDU + 1; if(endingBufferPos > bufferPos + hdusAvailable) endingBufferPos = bufferPos + hdusAvailable; while (fileHDU <= fileStopHDU && fileBufferPos < bufferLength) { progressBar.SetProgress(fileHDU + iFile*fileStopHDU, fileStopHDU*_filenames.size()); fitsfile *fptr = _fitsFiles[iFile]; int status = 0, hduType = 0; fits_movabs_hdu(fptr, fileHDU, &hduType, &status); checkStatus(status); if (hduType == BINARY_TBL) { throw std::runtime_error("GPU file seems not to contain image headers; format not understood."); } else { long fpixel = 1; float nullval = 0; int anynull = 0x0; long naxes[2]; fits_get_img_size(fptr, 2, naxes, &status); checkStatus(status); size_t channelsInFile = naxes[1]; size_t baselTimesPolInFile = naxes[0]; if(_nChannelsInTotal != (channelsInFile*_filenames.size())) { std::stringstream s; s << "Number of GPU files (" << _filenames.size() << ") in time range x row count of image chunk in file (" << channelsInFile << ") != " << "total channels count (" << _nChannelsInTotal << "): are the FITS files the dimension you expected them to be?"; throw std::runtime_error(s.str()); } // Test the first axis; note that we assert the number of floats, not complex, hence the factor of two. if(baselTimesPolInFile != nBaselines * nPol * 2) { std::stringstream s; s << "Unexpected number of visibilities in axis of GPU file. Expected=" << (nBaselines*nPol*2) << ", actual=" << baselTimesPolInFile; throw std::runtime_error(s.str()); } std::complex<float> *matrixPtr = 0; _availableGPUMatrixBuffers.read(matrixPtr); fits_read_img(fptr, TFLOAT, fpixel, channelsInFile * baselTimesPolInFile, &nullval, (float *) matrixPtr, &anynull, &status); checkStatus(status); ShuffleTask shuffleTask; shuffleTask.iFile = iFile; shuffleTask.channelsInFile = channelsInFile; shuffleTask.fileBufferPos = fileBufferPos; shuffleTask.gpuMatrix = matrixPtr; _shuffleTasks.write(shuffleTask); } ++fileHDU; ++fileBufferPos; } if(fileHDU <= fileStopHDU) moreAvailable = true; } } _shuffleTasks.write_end(); for(std::thread& t : threadGroup) t.join(); _currentHDU += endingBufferPos - bufferPos; bufferPos = endingBufferPos; if(!moreAvailable) closeFiles(); return moreAvailable; } void GPUFileReader::shuffleThreadFunc() { ShuffleTask task; while(_shuffleTasks.read(task)) { shuffleBuffer(task.iFile, task.channelsInFile, task.fileBufferPos, task.gpuMatrix); _availableGPUMatrixBuffers.write(task.gpuMatrix); } } void GPUFileReader::shuffleBuffer(size_t iFile, size_t channelsInFile, size_t fileBufferPos, const std::complex<float> *gpuMatrix) { const size_t nPol = 4; const size_t nBaselines = (_nAntenna + 1) * _nAntenna / 2; /** Note that the following antenna indices do not refer to the actual * antennae indices, but to correlator input indices. These need to be * mapped to the actual antenna indices. */ size_t correlationIndex = 0; for(size_t antenna1=0; antenna1!=_nAntenna; ++antenna1) { for(size_t antenna2=0; antenna2<=antenna1; ++antenna2) { size_t channelStart = iFile * channelsInFile; size_t channelEnd = (iFile+1) * channelsInFile; size_t index = correlationIndex * nPol; // Because possibly antenna2 <= antenna1 in the GPU file, and Casa MS expects it the other way // around, we change the order and take the complex conjugates later. BaselineBuffer &buffer = getMappedBuffer(antenna2, antenna1); size_t destChanIndex = fileBufferPos + channelStart * _bufferSize; for(size_t ch=channelStart; ch!=channelEnd; ++ch) { const std::complex<float> *dataPtr = &gpuMatrix[index]; *(buffer.real[0] + destChanIndex) = dataPtr->real(); *(buffer.imag[0] + destChanIndex) = dataPtr->imag(); ++dataPtr; *(buffer.real[2] + destChanIndex) = dataPtr->real(); *(buffer.imag[2] + destChanIndex) = dataPtr->imag(); ++dataPtr; *(buffer.real[1] + destChanIndex) = dataPtr->real(); *(buffer.imag[1] + destChanIndex) = dataPtr->imag(); ++dataPtr; *(buffer.real[3] + destChanIndex) = dataPtr->real(); *(buffer.imag[3] + destChanIndex) = dataPtr->imag(); index += nBaselines * nPol; destChanIndex += _bufferSize; } ++correlationIndex; } } } // Check the number of HDUs in each file. Only extract the amount of time // that there is actually data for in all files. void GPUFileReader::findStopHDU() { if(!_fitsHDUCounts.empty()) { bool haveUnequalHDUCount = false; _stopHDU = std::numeric_limits<size_t>::max(); for(size_t index = 0; index != _fitsHDUCounts.size(); ++index) { if(!_filenames[index].empty()) { size_t thisStopHDU = _fitsHDUCounts[index]; // If this file has different number of HDUs compared to previous, generate warning later if(_stopHDU != std::numeric_limits<size_t>::max() && _stopHDU != thisStopHDU) haveUnequalHDUCount = true; if(thisStopHDU < _stopHDU) _stopHDU = thisStopHDU; } } if(haveUnequalHDUCount) std::cout << "WARNING: Files had not the same number of HDUs.\n"; if(_stopHDU == std::numeric_limits<size_t>::max() || _stopHDU == 0) { std::cout << "ERROR: Stopping HDU equals zero, something is wrong with the input data.\n"; _stopHDU = 0; } else { std::cout << "Will stop on HDU " << _stopHDU << ".\n"; } } } void GPUFileReader::initMapping() { initializePFBMapping(); _isConjugated.resize(_nAntenna*_nAntenna*4); for(size_t a1 = 0; a1 != _nAntenna; ++a1) { for(size_t a2 = a1; a2 != _nAntenna; ++a2) { for(size_t p1 = 0; p1 != 2; ++p1) { for(size_t p2 = 0; p2 != 2; ++p2) { size_t pfbInp1 = pfb_output_to_input[a1 * 2 + p1]; size_t pfbInp2 = pfb_output_to_input[a2 * 2 + p2]; size_t actualOut1 = _corrInputToOutput[pfbInp1]; size_t actualOut2 = _corrInputToOutput[pfbInp2]; size_t actA1 = actualOut1/2; size_t actA2 = actualOut2/2; size_t actP1 = actualOut1%2; size_t actP2 = actualOut2%2; // Note that while reading, the antenna indices are reversed // again. Therefore, if the antenna indices are in the right // order here, we need to conjugate the visibility. size_t sourceIndex1 = a1*2 + p1; size_t sourceIndex2 = a2*2 + p2; bool isConjugated = (actualOut1 < actualOut2 && sourceIndex1 < sourceIndex2) || (actualOut1 > actualOut2 && sourceIndex1 > sourceIndex2); if(actA1 <= actA2) { size_t conjIndex = (actA1 * 2 + actP1) * _nAntenna * 2 + (actA2 * 2 + actP2); _isConjugated[conjIndex] = isConjugated; getMappedBuffer(a1, a2).real[p1 * 2 + p2] = getBuffer(actA1, actA2).real[actP1 * 2 + actP2]; getMappedBuffer(a1, a2).imag[p1 * 2 + p2] = getBuffer(actA1, actA2).imag[actP1 * 2 + actP2]; } else { size_t conjIndex = (actA2 * 2 + actP2) * _nAntenna * 2 + (actA1 * 2 + actP1); _isConjugated[conjIndex] = isConjugated; getMappedBuffer(a1, a2).real[p1 * 2 + p2] = getBuffer(actA2, actA1).real[actP2 * 2 + actP1]; getMappedBuffer(a1, a2).imag[p1 * 2 + p2] = getBuffer(actA2, actA1).imag[actP2 * 2 + actP1]; } } } } } } void GPUFileReader::initializePFBMapping() { // Output matrix has ordering // [channel][station][station][polarization][polarization][complexity] const size_t nPFB = 4; pfb_output_to_input.resize(nPFB * 64); for(size_t p=0;p<nPFB;p++) { for(size_t inp1=0;inp1<64;inp1++) { pfb_output_to_input[(p*64) + inp1] = single_pfb_output_to_input[inp1] + p*64; } } } const int GPUFileReader::single_pfb_output_to_input[64] = { 0, 16, 32, 48, 1, 17, 33, 49, 2, 18, 34, 50, 3, 19, 35, 51, 4, 20, 36, 52, 5, 21, 37, 53, 6, 22, 38, 54, 7, 23, 39, 55, 8, 24, 40, 56, 9, 25, 41, 57, 10, 26, 42, 58, 11, 27, 43, 59, 12, 28, 44, 60, 13, 29, 45, 61, 14, 30, 46, 62, 15, 31, 47, 63 };
[ "offringa@gmail.com" ]
offringa@gmail.com
c0c11404075485f436ca66df54316d4bff96515d
a36c8d4f36d0aab5423ba72abf7a93718be6ca7a
/goods.cc
96743621cb40c753f6cec77fafc556e1c430648c
[]
no_license
jinhowin/code_review
57fc456519f1a8aeefec3cf08ea289050b7dff55
6d7a90d940be63800b4238eb2c539228f9126323
refs/heads/master
2020-08-25T01:19:42.192258
2019-10-23T06:49:34
2019-10-23T06:49:34
216,940,821
1
1
null
null
null
null
UTF-8
C++
false
false
353
cc
#include "./goods.h" // Set member variable of goods with given index and price values void Goods::SetGoodsInfo(int index, int price) { goods_index_ = index; goods_price_ = price; } // Return index information int Goods::GetGoodsIndex() { return goods_index_; } // Return price informaiton int Goods::GetGoodsPrice() { return goods_price_; }
[ "noreply@github.com" ]
noreply@github.com
04e0c3b950e0d122fe94ff8e0f2270d5769dc8a6
48d7c0dd4c73e4bdb1198958e168376143b5b8ed
/include/timer.h
706e3636ce4d875119ab231c635f75542ab2c415
[ "MIT" ]
permissive
LaplaceKorea/vqlayer
75969df38b128d5a9b35c516af1d2d632db4b5d6
7e959ce88e9817f9490efb9e08d8d9d7a53fe277
refs/heads/master
2022-04-21T12:29:06.233569
2020-04-17T12:27:54
2020-04-17T12:27:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
548
h
/** A timer object measures elapsed time, * and it is very similar to boost::timer. */ class timer { public: timer() { restart(); } ~timer() = default; /** Restart the timer. */ void restart() { t_start = std::chrono::high_resolution_clock::now(); } /** @return The elapsed time */ double elapsed() { auto t_end = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count(); } private: std::chrono::high_resolution_clock::time_point t_start; };
[ "noreply@github.com" ]
noreply@github.com
28debd854a5fbf80ffa6766dd3039ab47159ca9e
00f73e1aa6872c8bd00ee3762208b56144a027a0
/Source/Debug.cpp
d0b5775d9485de26a169062802c9d3d79ae3ff1b
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
mxmauro/mxlib
efb80925c36e3444e630f4bc34856bb1b67c93b9
32b56d39fd235fe02fc97fbf6e7a9676c3e419ca
refs/heads/master
2023-08-31T22:34:01.100302
2023-08-20T20:21:51
2023-08-20T20:21:51
40,053,122
0
1
Apache-2.0
2020-03-14T16:08:30
2015-08-01T16:41:16
C
UTF-8
C++
false
false
3,233
cpp
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the LICENSE file distributed with * this work for additional information regarding copyright ownership. * * Also, if exists, check the Licenses directory for information about * third-party modules. * * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "..\Include\Debug.h" #include "..\Include\WaitableObjects.h" #include <stdio.h> //----------------------------------------------------------- #define MX_FORCE_OUTPUTDEBUG_ON_XP //----------------------------------------------------------- typedef ULONG (__cdecl *lpfnDbgPrint)(_In_z_ PCSTR Format, ...); typedef VOID (WINAPI *lpfnOutputDebugStringA)(_In_opt_ LPCSTR lpOutputString); //----------------------------------------------------------- namespace MX { VOID DebugPrint(_In_z_ LPCSTR szFormatA, ...) { va_list ap; va_start(ap, szFormatA); DebugPrintV(szFormatA, ap); va_end(ap); return; } VOID DebugPrintV(_In_z_ LPCSTR szFormatA, va_list ap) { static LONG volatile nAccessMtx = 0; static lpfnOutputDebugStringA fnOutputDebugStringA = NULL; static lpfnDbgPrint fnDbgPrint = NULL; #ifndef MX_FORCE_OUTPUTDEBUG_ON_XP static LONG volatile nOsVersion = 0; #endif //MX_FORCE_OUTPUTDEBUG_ON_XP CHAR szBufA[2048]; int i; #ifndef MX_FORCE_OUTPUTDEBUG_ON_XP if (nOsVersion == 0) { RTL_OSVERSIONINFOW sOviW; MxMemSet(&sOviW, 0, sizeof(sOviW)); sOviW.dwOSVersionInfoSize = (DWORD) sizeof(sOviW); if (!NT_SUCCESS(::RtlGetVersion(&sOviW))) return; _InterlockedExchange(&nOsVersion, (LONG)(sOviW.dwMajorVersion)); } if (__InterlockedRead(&nOsVersion) < 6) return; #endif //MX_FORCE_OUTPUTDEBUG_ON_XP //---- i = mx_vsnprintf(szBufA, MX_ARRAYLEN(szBufA), szFormatA, ap); if (i < 0) i = 0; else if (i > MX_ARRAYLEN(szBufA)-1) i = MX_ARRAYLEN(szBufA)-1; szBufA[i] = 0; //---- if (fnOutputDebugStringA == NULL) { PVOID DllBase = ::MxGetDllHandle(L"kernel32.dll"); fnOutputDebugStringA = (lpfnOutputDebugStringA)::MxGetProcedureAddress(DllBase, "OutputDebugStringA"); if (fnOutputDebugStringA == NULL) fnOutputDebugStringA = (lpfnOutputDebugStringA)1; } if (fnDbgPrint == NULL) { PVOID DllBase = ::MxGetDllHandle(L"ntdll.dll"); fnDbgPrint = (lpfnDbgPrint)::MxGetProcedureAddress(DllBase, "DbgPrint"); if (fnDbgPrint == NULL) fnDbgPrint = (lpfnDbgPrint)1; } //---- if (fnOutputDebugStringA == NULL || fnOutputDebugStringA == (PVOID)1) { fnDbgPrint("%s", szBufA); } else { CFastLock cAccessLock(&nAccessMtx); fnOutputDebugStringA(szBufA); } return; } } //namespace MX
[ "mxmauro@gmail.com" ]
mxmauro@gmail.com
dea07c117e256878d31aa938c66f770032bdbfd1
f1a28b194282baf3b3738b4e6cc4d0cd13d54aaa
/src/rqt_image_view/src/rqt_image_view/dataset.cpp
157b73d83f7faf7b6a2b8c19e0a33a1b77c5549b
[]
no_license
kalpgarg/Color-learning-and-recognition-in-ROS
da7cbbcbcbaf3d3deadf8367e20571b24e5694ae
ae3428e194b95a20b1dba48702f0b67e9fb94da5
refs/heads/master
2023-02-08T17:27:26.199390
2023-02-07T05:31:37
2023-02-07T05:31:37
139,662,788
0
0
null
null
null
null
UTF-8
C++
false
false
1,502
cpp
#include <memory> #include <algorithm> #include <rqt_image_view/dataset.h> #include <rqt_image_view/debug.h> #include <cstdio> dataset_base::dataset_base(size_t rows, size_t cols, size_t numLabels) : matrix_base(rows,cols) { labels = new int[rows]; this->numLabels = numLabels; DEBUGMEM("dataset: allocated int: %lu in %p\n",rows,labels); } dataset_base::~dataset_base() { DEBUGMEM("dataset: deleting: %lu in %p\n",rows,labels); delete [] labels; } void fillWithRandomIndices(int *indices, size_t nIndices) { for(size_t i = 0; i< nIndices; i++) indices[i] = i; std::random_shuffle(indices, indices + nIndices); } void dataset_base::splitDataset(DatasetPointer &train, DatasetPointer &valid, double train_percent) { int randomIndices[rows]; fillWithRandomIndices(randomIndices, rows); size_t threshold = (size_t) (train_percent * rows); train = DatasetPointer(new dataset_base(threshold, cols, numLabels)); valid = DatasetPointer(new dataset_base(rows - threshold, cols, numLabels)); size_t currentRowTrain=0; size_t currentRowValid=0; for(size_t i =0; i< rows; i++) { if (i < threshold) { for (size_t j=0; j < cols; j++) train->pos(currentRowTrain, j) = pos(randomIndices[i],j); train->label(currentRowTrain) = label(randomIndices[i]); currentRowTrain++; } else { for (size_t j=0; j < cols; j++) valid->pos(currentRowValid, j) = pos(randomIndices[i],j); valid->label(currentRowValid) = label(randomIndices[i]); currentRowValid++; } } }
[ "noreply@github.com" ]
noreply@github.com
eb2ac04aa320df377924e3d3dc082d74ca8e50b2
d72ba429177702891d94d121964cccb1ebfaa4f0
/src/highScoreModel.cpp
a8468e6215eb6562b09b2972a913fdd6cd954558
[ "MIT" ]
permissive
tatokis/minesweeper
a32cfb026bd5dc567f1b70fa1a2965f279a39062
65cd025364ea72fe7e333a7524d803e6139cfed2
refs/heads/master
2020-09-11T02:16:14.111093
2019-10-25T23:11:29
2019-10-25T23:11:29
221,907,802
1
0
MIT
2019-11-15T11:11:36
2019-11-15T11:11:36
null
UTF-8
C++
false
false
4,979
cpp
#include "highScoreModel.h" #include <cassert> constexpr int MAX_HIGH_SCORES = 10; HighScoreModel::HighScoreModel(HighScore::Difficulty difficulty, QObject* parent) : QAbstractItemModel(parent) , m_difficulty(difficulty) { } HighScoreModel::HighScoreModel(const HighScoreModel& other) : m_difficulty(other.m_difficulty) , m_highScores(other.m_highScores) { beginInsertRows(QModelIndex(), 0, other.m_highScores.size() - 1); beginInsertColumns(QModelIndex(), 0, columnCount() - 1); m_difficulty = other.m_difficulty; m_highScores = other.m_highScores; endInsertRows(); endInsertColumns(); assert(rowCount() == other.rowCount()); assert(columnCount() == other.columnCount()); } HighScoreModel& HighScoreModel::operator=(const HighScoreModel& other) { beginInsertRows(QModelIndex(), 0, other.m_highScores.size() - 1); beginInsertColumns(QModelIndex(), 0, columnCount() - 1); m_difficulty = other.m_difficulty; m_highScores = other.m_highScores; endInsertRows(); endInsertColumns(); return *this; } void HighScoreModel::addHighScore(HighScore score) { // Q_ASSERT(score.difficulty() == difficulty()); bool scoreInserted = false; beginInsertRows(QModelIndex(), rowCount(), rowCount()); if (m_highScores.isEmpty()) { m_highScores.append(score); return; } QVector<HighScore>::iterator existingScore; for (existingScore = m_highScores.begin(); existingScore != m_highScores.end(); ++existingScore) { if (score < *existingScore) { m_highScores.insert(existingScore, score); scoreInserted = true; break; } } // otherwise insert at end if(!scoreInserted) m_highScores.insert(m_highScores.end(), score); // prune to 10 high scores while (m_highScores.size() > MAX_HIGH_SCORES) m_highScores.removeLast(); endInsertRows(); } HighScore::Difficulty HighScoreModel::difficulty() const { return m_difficulty; } void HighScoreModel::setDifficulty(HighScore::Difficulty difficulty) { m_difficulty = difficulty; } QModelIndex HighScoreModel::index(int row, int column, const QModelIndex &parent /*= QModelIndex()*/) const { switch (column) { case Column::Name: return createIndex(row, column, Column::Name); case Column::Score: return createIndex(row, column, Column::Score); case Column::Date: return createIndex(row, column, Column::Date); default: return QModelIndex(); } } QModelIndex HighScoreModel::parent(const QModelIndex &child) const { return QModelIndex(); } int HighScoreModel::rowCount(const QModelIndex &parent /*= QModelIndex()*/) const { return m_highScores.size(); } int HighScoreModel::columnCount(const QModelIndex &parent /*= QModelIndex()*/) const { return 3; } QVariant HighScoreModel::data(const QModelIndex &index, int role /*= Qt::DisplayRole*/) const { if (role == Qt::DisplayRole) { switch (index.column()) { case Column::Name: return m_highScores[index.row()].name(); case Column::Score: return m_highScores[index.row()].score(); case Column::Date: return m_highScores[index.row()].date(); default: return QVariant(); } } else if (role == Qt::TextAlignmentRole) { QFlags<Qt::AlignmentFlag> alignment; switch (index.column()) { case Column::Name: alignment = Qt::AlignLeft | Qt::AlignVCenter; case Column::Score: alignment = Qt::AlignHCenter | Qt::AlignVCenter; case Column::Date: alignment = Qt::AlignHCenter | Qt::AlignVCenter; default: alignment = Qt::AlignHCenter | Qt::AlignVCenter; } return QVariant(alignment); } return QVariant(); } Qt::ItemFlags HighScoreModel::flags(const QModelIndex& index) const { return Qt::ItemIsEnabled; } QVariant HighScoreModel::headerData(int section, Qt::Orientation orientation, int role /*= Qt::DisplayRole*/) const { if (role == Qt::DisplayRole) { if(orientation == Qt::Horizontal) { switch (section) { case Column::Name: return tr("Name"); case Column::Score: return tr("Score"); case Column::Date: return tr("Date"); default: return QVariant(); } } else if (orientation == Qt::Vertical) { return (section + 1); } } return QVariant(); } const QVector<HighScore>& HighScoreModel::highScores() const { return m_highScores; } void HighScoreModel::setHighScores(QVector<HighScore> scores) { beginInsertRows(QModelIndex(), 0, scores.size() - 1); for (auto score : scores) addHighScore(score); endInsertRows(); } bool HighScoreModel::isHighScore(int time) const { return (rowCount() < MAX_HIGH_SCORES || time < index(rowCount() - 1, Score).data().toInt()); } QDataStream& operator<<(QDataStream &out, const HighScoreModel& model) { out << QVariant::fromValue(model.difficulty()).toString(); out << model.highScores(); return out; } QDataStream& operator>>(QDataStream &in, HighScoreModel& model) { QString difficulty; QVector<HighScore> scores; in >> difficulty; in >> scores; model.setDifficulty(QVariant(difficulty).value<HighScore::Difficulty>()); model.setHighScores(scores); return in; }
[ "nholthaus@gmail.com" ]
nholthaus@gmail.com
eecc4787955d262125f61364aa8a2276fce2f063
8cf5890812baa2724b51c6ca17d16e2a4ee460e4
/d05/ex05/Bureaucrat.cpp
c7f06b4ebeb2b6a5de75a9d873bd2c38e8f87186
[]
no_license
akorchyn/cpp-pool
71a1f0aeba123278a9ad0d709110035fa4d6b5de
f958548168bb08b928890b21e69700282a767023
refs/heads/master
2020-05-16T20:14:37.938083
2019-04-24T18:12:10
2019-04-24T18:12:10
183,279,603
0
0
null
null
null
null
UTF-8
C++
false
false
2,605
cpp
#include "Bureaucrat.hpp" Bureaucrat::Bureaucrat() { } Bureaucrat::Bureaucrat(std::string const &name, int grade) : _name(name) { if (grade > 150) throw GradeTooLowException(); else if (grade < 1) throw GradeTooHighException(); _grade = grade; } Bureaucrat::Bureaucrat(Bureaucrat const &x) : _name(x._name), _grade(x._grade) { } Bureaucrat &Bureaucrat::operator=(Bureaucrat const &x) { if (this == &x) return *this; _grade = x._grade; return *this; } void Bureaucrat::executeForm(Form &form) { try { form.execute(*this); std::cout << _name << " executes " << form.getName() << std::endl; } catch (std::exception &x) { std::cout << _name << " cannot execute " << form.getName() << " because " << x.what() << std::endl; throw std::runtime_error("Get more better executer"); } } Bureaucrat::~Bureaucrat() { } std::ostream &operator<<(std::ostream &s, Bureaucrat const &x) { s << x.getName() << ", bureaucrat grade " << x.getGrade() << std::endl; return s; } const std::string &Bureaucrat::getName() const { return _name; } int Bureaucrat::getGrade() const { return _grade; } void Bureaucrat::increment() { if (_grade == 1) throw GradeTooHighException(); _grade--; } void Bureaucrat::decrement() { if (_grade == 150) throw GradeTooLowException(); _grade++; } void Bureaucrat::signForm(Form &form) { try { form.beSigned(*this); std::cout << _name << " signs " << form.getName() << std::endl; } catch (std::exception &x) { std::cout << _name << " cannot sign " << form.getName() << " because " << x.what() << std::endl; throw std::runtime_error("Get more better signer"); } } /* * Exception Block */ Bureaucrat::GradeTooHighException::GradeTooHighException() : std::exception() { } const char *Bureaucrat::GradeTooHighException::what() const throw() { return "Grade too high"; } Bureaucrat::GradeTooHighException::GradeTooHighException(const Bureaucrat::GradeTooHighException &x) : std::exception(x) { } Bureaucrat::GradeTooHighException &Bureaucrat::GradeTooHighException::operator=(const Bureaucrat::GradeTooHighException &x) { static_cast<void>(x); return *this; } Bureaucrat::GradeTooLowException &Bureaucrat::GradeTooLowException::operator=(const Bureaucrat::GradeTooLowException &x) { static_cast<void>(x); return *this; } Bureaucrat::GradeTooLowException::GradeTooLowException(const Bureaucrat::GradeTooLowException &x) : std::exception(x) { } Bureaucrat::GradeTooLowException::GradeTooLowException() : std::exception() { } const char *Bureaucrat::GradeTooLowException::what() const throw() { return "Grade too low"; }
[ "akorchyn@student.unit.ua" ]
akorchyn@student.unit.ua
271a79c0de3baf1ad9cac7940b51519554149200
7d22f18714611d97175813b1e20e94d2e29d204e
/src/test/key_tests.cpp
099917d338f83c19df053add6f6c77ec9a2c1bfe
[ "MIT" ]
permissive
lavajumper/sexcoin
8179dbd95d28fc4c829fdb846f0b48db25b3dddf
4ea0d53dd23e432e8edd5a5bddd0d546ef8a0a73
refs/heads/master
2021-01-18T01:19:25.067181
2019-01-12T14:50:28
2019-01-12T14:50:28
67,519,646
0
0
MIT
2019-01-12T14:50:29
2016-09-06T15:12:56
C++
UTF-8
C++
false
false
7,061
cpp
// Copyright (c) 2012-2015 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 "key.h" #include "base58.h" #include "script/script.h" #include "uint256.h" #include "util.h" #include "utilstrencodings.h" #include "test/test_bitcoin.h" #include <string> #include <vector> #include <boost/test/unit_test.hpp> static const std::string strSecret1 ("7fyNTPYB6uYu7o5WR3NhesEpApx8szxdA3vPtN7wFHjFZ2Ym8U5"); static const std::string strSecret2 ("7hCvBCiVF829bVY1kCC3Cyah3UGbEKaqJk1ZLR7cb1jkzQXUVCD"); static const std::string strSecret1C ("WT1ohUUbb4wo2zNtq7UnS8jyCNeMn6pWawtg1iDcS4qVDyoQYAuv"); static const std::string strSecret2C ("WYTbi2i7fKz4wEwtHePijrjhjuMp5o2LDJqTihSC58FjA32WjpXd"); static const CBitcoinAddress addr1 ("VyFfk4dfUtTh7ACP3MYCk7CGTYdRZqPK11"); static const CBitcoinAddress addr2 ("Vp5nywEhmQym4QD2uwLy1Nxuj5Wvfae8kF"); static const CBitcoinAddress addr1C("Vwo8mX3LNC5XiyC43K6giUxAYLiCdRTSRo"); static const CBitcoinAddress addr2C("VmRYw18oR1Rj444g5CYLhFJYNBk7zRgRDr"); static const std::string strAddressBad("1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF"); BOOST_FIXTURE_TEST_SUITE(key_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(key_test1) { CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1; BOOST_CHECK( bsecret1.SetString (strSecret1)); BOOST_CHECK( bsecret2.SetString (strSecret2)); BOOST_CHECK( bsecret1C.SetString(strSecret1C)); BOOST_CHECK( bsecret2C.SetString(strSecret2C)); BOOST_CHECK(!baddress1.SetString(strAddressBad)); CKey key1 = bsecret1.GetKey(); BOOST_CHECK(key1.IsCompressed() == false); CKey key2 = bsecret2.GetKey(); BOOST_CHECK(key2.IsCompressed() == false); CKey key1C = bsecret1C.GetKey(); BOOST_CHECK(key1C.IsCompressed() == true); CKey key2C = bsecret2C.GetKey(); BOOST_CHECK(key2C.IsCompressed() == true); CPubKey pubkey1 = key1. GetPubKey(); CPubKey pubkey2 = key2. GetPubKey(); CPubKey pubkey1C = key1C.GetPubKey(); CPubKey pubkey2C = key2C.GetPubKey(); BOOST_CHECK(key1.VerifyPubKey(pubkey1)); BOOST_CHECK(!key1.VerifyPubKey(pubkey1C)); BOOST_CHECK(!key1.VerifyPubKey(pubkey2)); BOOST_CHECK(!key1.VerifyPubKey(pubkey2C)); BOOST_CHECK(!key1C.VerifyPubKey(pubkey1)); BOOST_CHECK(key1C.VerifyPubKey(pubkey1C)); BOOST_CHECK(!key1C.VerifyPubKey(pubkey2)); BOOST_CHECK(!key1C.VerifyPubKey(pubkey2C)); BOOST_CHECK(!key2.VerifyPubKey(pubkey1)); BOOST_CHECK(!key2.VerifyPubKey(pubkey1C)); BOOST_CHECK(key2.VerifyPubKey(pubkey2)); BOOST_CHECK(!key2.VerifyPubKey(pubkey2C)); BOOST_CHECK(!key2C.VerifyPubKey(pubkey1)); BOOST_CHECK(!key2C.VerifyPubKey(pubkey1C)); BOOST_CHECK(!key2C.VerifyPubKey(pubkey2)); BOOST_CHECK(key2C.VerifyPubKey(pubkey2C)); BOOST_CHECK(addr1.Get() == CTxDestination(pubkey1.GetID())); BOOST_CHECK(addr2.Get() == CTxDestination(pubkey2.GetID())); BOOST_CHECK(addr1C.Get() == CTxDestination(pubkey1C.GetID())); BOOST_CHECK(addr2C.Get() == CTxDestination(pubkey2C.GetID())); for (int n=0; n<16; n++) { std::string strMsg = strprintf("Very secret message %i: 11", n); uint256 hashMsg = Hash(strMsg.begin(), strMsg.end()); // normal signatures std::vector<unsigned char> sign1, sign2, sign1C, sign2C; BOOST_CHECK(key1.Sign (hashMsg, sign1)); BOOST_CHECK(key2.Sign (hashMsg, sign2)); BOOST_CHECK(key1C.Sign(hashMsg, sign1C)); BOOST_CHECK(key2C.Sign(hashMsg, sign2C)); BOOST_CHECK( pubkey1.Verify(hashMsg, sign1)); BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2)); BOOST_CHECK( pubkey1.Verify(hashMsg, sign1C)); BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2C)); BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1)); BOOST_CHECK( pubkey2.Verify(hashMsg, sign2)); BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1C)); BOOST_CHECK( pubkey2.Verify(hashMsg, sign2C)); BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1)); BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2)); BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1C)); BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2C)); BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1)); BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2)); BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1C)); BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2C)); // compact signatures (with key recovery) std::vector<unsigned char> csign1, csign2, csign1C, csign2C; BOOST_CHECK(key1.SignCompact (hashMsg, csign1)); BOOST_CHECK(key2.SignCompact (hashMsg, csign2)); BOOST_CHECK(key1C.SignCompact(hashMsg, csign1C)); BOOST_CHECK(key2C.SignCompact(hashMsg, csign2C)); CPubKey rkey1, rkey2, rkey1C, rkey2C; BOOST_CHECK(rkey1.RecoverCompact (hashMsg, csign1)); BOOST_CHECK(rkey2.RecoverCompact (hashMsg, csign2)); BOOST_CHECK(rkey1C.RecoverCompact(hashMsg, csign1C)); BOOST_CHECK(rkey2C.RecoverCompact(hashMsg, csign2C)); BOOST_CHECK(rkey1 == pubkey1); BOOST_CHECK(rkey2 == pubkey2); BOOST_CHECK(rkey1C == pubkey1C); BOOST_CHECK(rkey2C == pubkey2C); } // test deterministic signing std::vector<unsigned char> detsig, detsigc; std::string strMsg = "Very deterministic message"; uint256 hashMsg = Hash(strMsg.begin(), strMsg.end()); BOOST_CHECK(key1.Sign(hashMsg, detsig)); BOOST_CHECK(key1C.Sign(hashMsg, detsigc)); BOOST_CHECK(detsig == detsigc); BOOST_CHECK(detsig == ParseHex("304402205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d022014ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6")); BOOST_CHECK(key2.Sign(hashMsg, detsig)); BOOST_CHECK(key2C.Sign(hashMsg, detsigc)); BOOST_CHECK(detsig == detsigc); BOOST_CHECK(detsig == ParseHex("3044022052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd5022061d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d")); BOOST_CHECK(key1.SignCompact(hashMsg, detsig)); BOOST_CHECK(key1C.SignCompact(hashMsg, detsigc)); BOOST_CHECK(detsig == ParseHex("1c5dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6")); BOOST_CHECK(detsigc == ParseHex("205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6")); BOOST_CHECK(key2.SignCompact(hashMsg, detsig)); BOOST_CHECK(key2C.SignCompact(hashMsg, detsigc)); BOOST_CHECK(detsig == ParseHex("1c52d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d")); BOOST_CHECK(detsigc == ParseHex("2052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d")); } BOOST_AUTO_TEST_SUITE_END()
[ "lavajumper@lavajumper.com" ]
lavajumper@lavajumper.com
da6aa65122e810e3db3ce9a23a36d97c0f9531d5
f7622017ba718b6bcf0fcb013c4fbfcec6bc1a2c
/src/bioioMod.cpp
37460aa928dea6bc03a351603c0abccbf3f6ebc6
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
sahlenlab/HiCapTools
eaa9fc61d895c868dcd4cd5e6a4c1f345e081acc
cb717282c600595c9b076504bd1dab9aa4553b30
refs/heads/master
2022-10-18T09:07:11.119005
2022-04-25T08:06:28
2022-04-25T08:06:28
84,056,684
9
5
NOASSERTION
2022-04-28T12:08:37
2017-03-06T09:50:41
C++
UTF-8
C++
false
false
4,430
cpp
/* Copyright (C) 2015 University of Oxford. Author: Daniel Cooke <dcooke@well.ox.ac.uk> 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. */ /*** Modified and used from the bioio package ***/ #include "bioioMod.h" #include <regex> #include <stdexcept> #include <iostream> #include <fstream> #include <cstddef> #include <algorithm> using GenomicRegion = std::tuple<std::string, size_t, size_t> ; GenomicRegion bioioMod::parse_region(std::string region, const bioio::FastaIndex& index){ region.erase(std::remove(region.begin(), region.end(), ','), region.end()); const static std::regex re {"([^:]+)(?::(\\d+)(-)?(\\d*))?"}; std::smatch match; if (std::regex_match(region, match, re) && match.size() == 5) { auto contig_name = match.str(1); if (index.count(contig_name) == 0) { throw std::runtime_error {"contig " + contig_name + " not found"}; } const auto contig_size = index.at(contig_name).length; size_t begin {0}, end {0}; if (match.str(2).empty()) { end = contig_size; } else { begin = static_cast<size_t>(std::stoull(match.str(2))); if (match.str(3).empty()) { end = begin + 1; } else if (match.str(4).empty()) { end = contig_size; } else { end = static_cast<size_t>(std::stoull(match.str(4))); } if (begin > contig_size) { throw std::runtime_error {"region " + region + " is larger than contig " + contig_name + ":0-" + std::to_string(contig_size)}; } if (begin > end) { throw std::runtime_error {"begin position is past end position in region " + region}; } if (end > contig_size) { end = contig_size; } } return GenomicRegion {std::move(contig_name), begin, end}; } throw std::runtime_error {"could not parse region " + region}; } std::string bioioMod::GetFasta(std::string regionToGet){ std::ifstream fasta {fasta_path, std::ios::binary}; if (!fasta) { bLog << "Error: could not open fasta " << fasta_path << std::endl; return "Error"; } if (index_path.empty()) { //changed index_path = fasta_path; index_path.replace(index_path.begin() + index_path.find_last_of("."), index_path.end(), ".fai"); } std::ifstream index_file {index_path, std::ios::binary}; if (!index_file) { index_file.open(fasta_path + ".fai"); if (!index_file) { bLog << "Error: could not open index file, use samtools faidx <fasta> to make index file" << std::endl; return "Error"; } } try { const auto index = bioio::read_fasta_index(index_file); const auto region = parse_region(regionToGet, index); const auto& contig = std::get<0>(region); const auto begin = std::get<1>(region); const auto length = std::get<2>(region) - begin; const auto sequence = bioio::read_fasta_contig(fasta, index.at(contig), begin, length); return sequence; } catch (std::runtime_error& e) { bLog << "Error: " << e.what() << std::endl; } }
[ "aanil@kth.se" ]
aanil@kth.se
90ab7c62c5921aaeda44a05a6981064c48d2adb6
87de63798f786e8f32c171554f16cc1cb05bd61f
/SystemModels/Systems/BloodSystem/Biochemistry/BaseBiochemistryModel.cpp
6038ffc35c9e4564509d676c70b428ecab9cd7b4
[]
no_license
avgolov/virtual-human
a0bd4d88b0c76f8f9c0fbf795e9c0e3ccff43d60
82636e04489efad9efe57077b8e6369d8cf5feff
refs/heads/master
2021-07-17T17:15:47.189088
2017-10-24T08:57:21
2017-10-24T08:57:21
108,100,427
1
0
null
null
null
null
UTF-8
C++
false
false
2,311
cpp
#include "BaseBiochemistryModel.h" namespace SystemModels { /*double BaseBiochemistryModel::GetPo2() const { auto coef = 1. / 22.256; auto hb = (*values_)[2]; auto o2 = coef*(*values_)[0]; double s_o2 = GetSo2(); return (o2 -4*hb*s_o2)/a_o2_; } double BaseBiochemistryModel::GetPco2() const { auto coef = 1. / 22.256; auto hco3 = (*values_)[3]; auto co2 = coef*(*values_)[1]; return (co2- hco3)/a_co2_; } void BaseBiochemistryModel::SetPo2(double value) { auto coef = 1. / 22.256; auto o2 = coef*(*values_)[0]; (*values_)[2] = std::sqrt(0.25*hb_tot_*(o2 - value*a_o2_)); (*valuesOld_)[2] = (*values_)[2]; } void BaseBiochemistryModel::SetPco2(double value) { auto coef = 1. / 22.256; auto co2 = coef*(*values_)[1]; (*values_)[3] = co2 - a_co2_*value; (*valuesOld_)[3] = (*values_)[3]; (*values_)[4] = k2_*co2 / (k22_*(*values_)[3]); (*valuesOld_)[4] = (*values_)[4]; }*/ double BaseBiochemistryModel::GetSo2() const { return (*values_)[2] /hb_tot_; } void BaseBiochemistryModel::Compute(TimeSpan* timeSpan) { /*auto coef = 1./22.256; auto hco3 = (*values_)[3]; auto h = (*values_)[4]; auto hb = (*values_)[2]; auto co2_free = coef*(*values_)[1] - hco3; co2_free = co2_free > 0. ? co2_free : 1.e-4; auto o2_free = coef*(*values_)[0]; o2_free = (o2_free - 4 * hb*hb/ hb_tot_); o2_free = o2_free > 0. ? o2_free : 1.e-4; (*values_)[2] += timeSpan->dt*(k1_*(hb_tot_- hb)*pow(o2_free,m_)-k11_*hb); (*values_)[3] += timeSpan->dt*(k2_*co2_free -k22_*h*hco3); (*values_)[4] += timeSpan->dt*(k2_*co2_free - k22_*h*hco3);*/ } double BaseBiochemistryModel::GetPo2() const { /*auto o2 = (*values_)[0]/22.4; return (o2 - b_o2_) / a_o2_;*/ return (*values_)[0] / b_o2_; } double BaseBiochemistryModel::GetPco2() const { /*auto co2 = (*values_)[1] / 22.4; return (co2 - b_co2_) / a_co2_;*/ return (*values_)[1] / b_co2_; } void BaseBiochemistryModel::SetPo2(double value) { /*auto o2 = (*values_)[0] / 22.4; b_o2_ = o2 - value*a_o2_;*/ b_o2_ = (*values_)[0] / value; } void BaseBiochemistryModel::SetPco2(double value) { /*auto co2 = (*values_)[1] / 22.4; b_co2_ = co2 - value*a_co2_;*/ b_co2_ = (*values_)[1] / value; } }
[ "golov.andrey@hotmail.com" ]
golov.andrey@hotmail.com
9ad729267af3cbad38647effd26e792b752ba9cd
236e0fe4c7a0b239a3d930f9f476d144af6645d6
/audio_hal_interface/a2dp_encoding.h
7b104ff390d0fed203e6d17e6382388d91ad96bf
[ "Apache-2.0" ]
permissive
RevengeOS/android_system_bt
4e178e900cde15473e1d4fd49e1bd40a359777ca
57383ba301d9f19c7ab19e83ffb59c25af05da59
refs/heads/r10.0
2021-07-22T12:15:48.460364
2019-06-27T05:56:56
2020-07-01T18:35:38
166,219,788
2
5
NOASSERTION
2021-01-05T19:26:25
2019-01-17T12:09:48
C++
UTF-8
C++
false
false
1,585
h
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "audio_a2dp_hw/include/audio_a2dp_hw.h" #include "common/message_loop_thread.h" namespace bluetooth { namespace audio { namespace a2dp { // Check if new bluetooth_audio is enabled bool is_hal_2_0_enabled(); // Initialize BluetoothAudio HAL: openProvider bool init(bluetooth::common::MessageLoopThread* message_loop); // Clean up BluetoothAudio HAL void cleanup(); // Set up the codec into BluetoothAudio HAL bool setup_codec(); // Send command to the BluetoothAudio HAL: StartSession, EndSession, // StreamStarted, StreamSuspended void start_session(); void end_session(); void ack_stream_started(const tA2DP_CTRL_ACK& status); void ack_stream_suspended(const tA2DP_CTRL_ACK& status); // Read from the FMQ of BluetoothAudio HAL size_t read(uint8_t* p_buf, uint32_t len); // Update A2DP delay report to BluetoothAudio HAL void set_remote_delay(uint16_t delay_report); } // namespace a2dp } // namespace audio } // namespace bluetooth
[ "hsz@google.com" ]
hsz@google.com
c4c8156baeb032487f2d3eec474177801938a902
5debf5db5c596d19b789a8c417d83a79ce0c05c5
/test/ga_and_baseline/comp.cpp
0bb84a52cea27cb868898a658e2fe42d1c61043b
[]
no_license
Jensbeltman/masterRepo
0944358111957de8fde8f531648ba9b325d11622
765e2fe39525a90a7aada28417d8fdcf2fe23c9b
refs/heads/master
2023-06-04T03:38:12.371479
2021-06-24T07:02:03
2021-06-24T07:02:03
293,446,996
0
0
null
null
null
null
UTF-8
C++
false
false
9,591
cpp
#include <iostream> #include <chronometer.h> #include <algorithm> #include "datautil/csv_doc.hpp" #include "datautil/ga_conversions.hpp" #include "matplot/matplot.h" using namespace matplot; void to_row_percent(std::vector<int> &tp,std::vector<int> &fp,std::vector<int> &tn,std::vector<int> &fn,std::vector<double> &tp_pct,std::vector<double> &fp_pct,std::vector<double> &tn_pct,std::vector<double> &fn_pct){ for(int i = 0;i<tp.size();i++){ int ocs = tp[i] +fp[i] +tn[i] +fn[i]; tp_pct.push_back(tp[i]/static_cast<double>(ocs)); fp_pct.push_back(fp[i]/static_cast<double>(ocs)); tn_pct.push_back(tn[i]/static_cast<double>(ocs)); fn_pct.push_back(fn[i]/static_cast<double>(ocs)); } } int main(int argc, char** argv) { std::string folder_name = argv[1]; std::string results_path = folder_name+argv[2]; std::string cost_history_path_ga = folder_name+argv[3]; std::string cost_history_path_ba = folder_name+argv[4]; rapidcsv::CSVRReadDoc result_doc(results_path,rapidcsv::LabelParams(0,0)); rapidcsv::CSVRReadDoc ga_cost_history_doc(cost_history_path_ga, rapidcsv::LabelParams(-1, 0)); rapidcsv::CSVRReadDoc ba_cost_history_doc(cost_history_path_ba, rapidcsv::LabelParams(-1, 0)); std::vector<chromosomeT> ga_chromosomes= result_doc.GetColumn<chromosomeT>(result_doc.GetColumnIdx("GA_Chromosome")); std::vector<chromosomeT> ba_chromosomes= result_doc.GetColumn<chromosomeT>(result_doc.GetColumnIdx("BA_Chromosome")); std::vector<int> ga_tp = result_doc.GetColumn<int>(result_doc.GetColumnIdx("#ga_tp")); std::vector<int> ga_fp = result_doc.GetColumn<int>(result_doc.GetColumnIdx("#ga_fp")); std::vector<int> ga_tn = result_doc.GetColumn<int>(result_doc.GetColumnIdx("#ga_tn")); std::vector<int> ga_fn = result_doc.GetColumn<int>(result_doc.GetColumnIdx("#ga_fn")); std::vector<int> ba_tp = result_doc.GetColumn<int>(result_doc.GetColumnIdx("#ba_tp")); std::vector<int> ba_fp = result_doc.GetColumn<int>(result_doc.GetColumnIdx("#ba_fp")); std::vector<int> ba_tn = result_doc.GetColumn<int>(result_doc.GetColumnIdx("#ba_tn")); std::vector<int> ba_fn = result_doc.GetColumn<int>(result_doc.GetColumnIdx("#ba_fn")); std::vector<double> ga_tp_pct,ga_fp_pct,ga_tn_pct,ga_fn_pct,ba_tp_pct,ba_fp_pct,ba_tn_pct,ba_fn_pct; to_row_percent(ga_tp,ga_fp,ga_tn,ga_fn,ga_tp_pct,ga_fp_pct,ga_tn_pct,ga_fn_pct); to_row_percent(ba_tp,ba_fp,ba_tn,ba_fn,ba_tp_pct,ba_fp_pct,ba_tn_pct,ba_fn_pct); std::map<std::string,std::vector<std::string>> row_groups; std::vector<std::string> row_names = result_doc.GetRowNames(); std::vector<int> start_idxs; std::string name; for (int i = 0; i<row_names.size();i++){ auto & rn = row_names[i]; auto pos = rn.find("_"); if(pos != rn.npos) { name = rn.substr(0, pos); row_groups[name].emplace_back(rn); } } tiledlayout(1,row_groups.size()); for(auto &row_group:row_groups) { nexttile(); int ridx_start = result_doc.GetRowIdx(row_group.second[0]); int ridx_end = result_doc.GetRowIdx(row_group.second.back()); std::vector<std::vector<double>> bar_data;// = {{2, 2, 2, 2}, {2, 5, 8, 11}, {3, 6, 9, 12}}; int ga_tp_sum = std::accumulate(ga_tp.begin()+ridx_start,ga_tp.begin()+ridx_end+1,0); int ga_fp_sum = std::accumulate(ga_fp.begin()+ridx_start,ga_fp.begin()+ridx_end+1,0); int ga_tn_sum = std::accumulate(ga_tn.begin()+ridx_start,ga_tn.begin()+ridx_end+1,0); int ga_fn_sum = std::accumulate(ga_fn.begin()+ridx_start,ga_fn.begin()+ridx_end+1,0); int ba_tp_sum = std::accumulate(ba_tp.begin()+ridx_start,ba_tp.begin()+ridx_end+1,0); int ba_fp_sum = std::accumulate(ba_fp.begin()+ridx_start,ba_fp.begin()+ridx_end+1,0); int ba_tn_sum = std::accumulate(ba_tn.begin()+ridx_start,ba_tn.begin()+ridx_end+1,0); int ba_fn_sum = std::accumulate(ba_fn.begin()+ridx_start,ba_fn.begin()+ridx_end+1,0); bar_data.resize(4); bar_data[0].emplace_back(ga_tp_sum); bar_data[1].emplace_back(ga_fp_sum); bar_data[2].emplace_back(ga_tn_sum); bar_data[3].emplace_back(ga_fn_sum); bar_data[0].emplace_back(ba_tp_sum); bar_data[1].emplace_back(ba_fp_sum); bar_data[2].emplace_back(ba_tn_sum); bar_data[3].emplace_back(ba_fn_sum); bar(bar_data); title(row_group.first+" Sum"); xticklabels(std::vector<std::string>{"GA","BA"}); } save(folder_name+"results_sum.svg"); tiledlayout(1,row_groups.size()); for(auto &row_group:row_groups) { nexttile(); int ridx_start = result_doc.GetRowIdx(row_group.second[0]); int ridx_end = result_doc.GetRowIdx(row_group.second.back()); std::vector<std::vector<double>> bar_data;// = {{2, 2, 2, 2}, {2, 5, 8, 11}, {3, 6, 9, 12}}; double ga_tp_sum = std::accumulate(ga_tp.begin()+ridx_start,ga_tp.begin()+ridx_end+1,0)/(double)(ridx_end-ridx_start); double ga_fp_sum = std::accumulate(ga_fp.begin()+ridx_start,ga_fp.begin()+ridx_end+1,0)/(double)(ridx_end-ridx_start); double ga_tn_sum = std::accumulate(ga_tn.begin()+ridx_start,ga_tn.begin()+ridx_end+1,0)/(double)(ridx_end-ridx_start); double ga_fn_sum = std::accumulate(ga_fn.begin()+ridx_start,ga_fn.begin()+ridx_end+1,0)/(double)(ridx_end-ridx_start); double ba_tp_sum = std::accumulate(ba_tp.begin()+ridx_start,ba_tp.begin()+ridx_end+1,0)/(double)(ridx_end-ridx_start); double ba_fp_sum = std::accumulate(ba_fp.begin()+ridx_start,ba_fp.begin()+ridx_end+1,0)/(double)(ridx_end-ridx_start); double ba_tn_sum = std::accumulate(ba_tn.begin()+ridx_start,ba_tn.begin()+ridx_end+1,0)/(double)(ridx_end-ridx_start); double ba_fn_sum = std::accumulate(ba_fn.begin()+ridx_start,ba_fn.begin()+ridx_end+1,0)/(double)(ridx_end-ridx_start); bar_data.resize(4); bar_data[0].emplace_back(ga_tp_sum); bar_data[1].emplace_back(ga_fp_sum); bar_data[2].emplace_back(ga_tn_sum); bar_data[3].emplace_back(ga_fn_sum); bar_data[0].emplace_back(ba_tp_sum); bar_data[1].emplace_back(ba_fp_sum); bar_data[2].emplace_back(ba_tn_sum); bar_data[3].emplace_back(ba_fn_sum); bar(bar_data); title(row_group.first+" Average"); xticklabels(std::vector<std::string>{"GA","BA"}); } save(folder_name+"results_avr.svg"); tiledlayout(1,row_groups.size()); for(auto &row_group:row_groups) { nexttile(); int ridx_start = result_doc.GetRowIdx(row_group.second[0]); int ridx_end = result_doc.GetRowIdx(row_group.second.back()); std::vector<std::vector<double>> bar_data;// = {{2, 2, 2, 2}, {2, 5, 8, 11}, {3, 6, 9, 12}}; double ga_tp_sum = std::accumulate(ga_tp_pct.begin()+ridx_start,ga_tp_pct.begin()+ridx_end+1,0.0)/(double)(ridx_end-ridx_start); double ga_fp_sum = std::accumulate(ga_fp_pct.begin()+ridx_start,ga_fp_pct.begin()+ridx_end+1,0.0)/(double)(ridx_end-ridx_start); double ga_tn_sum = std::accumulate(ga_tn_pct.begin()+ridx_start,ga_tn_pct.begin()+ridx_end+1,0.0)/(double)(ridx_end-ridx_start); double ga_fn_sum = std::accumulate(ga_fn_pct.begin()+ridx_start,ga_fn_pct.begin()+ridx_end+1,0.0)/(double)(ridx_end-ridx_start); double ba_tp_sum = std::accumulate(ba_tp_pct.begin()+ridx_start,ba_tp_pct.begin()+ridx_end+1,0.0)/(double)(ridx_end-ridx_start); double ba_fp_sum = std::accumulate(ba_fp_pct.begin()+ridx_start,ba_fp_pct.begin()+ridx_end+1,0.0)/(double)(ridx_end-ridx_start); double ba_tn_sum = std::accumulate(ba_tn_pct.begin()+ridx_start,ba_tn_pct.begin()+ridx_end+1,0.0)/(double)(ridx_end-ridx_start); double ba_fn_sum = std::accumulate(ba_fn_pct.begin()+ridx_start,ba_fn_pct.begin()+ridx_end+1,0.0)/(double)(ridx_end-ridx_start); bar_data.resize(4); bar_data[0].emplace_back(ga_tp_sum); bar_data[1].emplace_back(ga_fp_sum); bar_data[2].emplace_back(ga_tn_sum); bar_data[3].emplace_back(ga_fn_sum); bar_data[0].emplace_back(ba_tp_sum); bar_data[1].emplace_back(ba_fp_sum); bar_data[2].emplace_back(ba_tn_sum); bar_data[3].emplace_back(ba_fn_sum); bar(bar_data); title(row_group.first+" Percentage Average"); xticklabels(std::vector<std::string>{"GA","BA"}); } save(folder_name+"results_avr_pct.svg"); /* std::vector<double> costhist; std::vector<std::string> names; names.emplace_back("ch "+std::to_string(0)); costhist = ga_cost_history_doc.GetRow<double>(0); plot(costhist); hold(on); for(int i = 1; i < ga_cost_history_doc.GetRowCount(); i++) { names.emplace_back("ch "+std::to_string(i)); costhist = ga_cost_history_doc.GetRow<double>(i); plot(costhist); } hold(off); title("GA cost history"); xlabel("itteration #"); ylabel("Cost"); show(); names.clear(); names.emplace_back("ch "+std::to_string(0)); costhist = ba_cost_history_doc.GetRow<double>(0); plot(costhist); hold(on); for(int i = 1; i < ba_cost_history_doc.GetRowCount(); i++) { names.emplace_back("ch "+std::to_string(i)); costhist = ba_cost_history_doc.GetRow<double>(i); plot(costhist); } hold(off); title("BA cost history"); xlabel("itteration #"); ylabel("Cost"); show();*/ }
[ "jens@beltman.dk" ]
jens@beltman.dk
b41216528238c8b891f046c2f6cab89502191585
1c579fcaa10c9c0ba589ff78e60e42b3fe50cdad
/es++2.0.9/opencv-4.0/ImageTransformationByDynamicColorFilter/ImageTransformationByDynamicColorFilter.cpp
800b2191ccc806a4d5df0e44671f512bdb26ad8c
[]
no_license
atlan-antillia/es
4dddc95f87bfa9ad45fb370b2db8ee0ea980338b
c8ba5b9896bb00d98f256601e44aabe8497b029d
refs/heads/master
2021-05-26T19:26:33.167700
2020-04-12T06:22:52
2020-04-12T06:22:52
254,152,715
0
0
null
null
null
null
UTF-8
C++
false
false
7,881
cpp
/****************************************************************************** * * Copyright (c) 2019 Antillia.com TOSHIYUKI ARAI. 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. 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. * * * ImageTransformationByColorFilter.cpp * *****************************************************************************/ // #include <es++/Pair.h> #include <es++/gtkmm-3.0/Application.h> #include <es++/gtkmm-3.0/Label.h> #include <es++/gtkmm-3.0/LabeledComboBox.h> #include <es++/gtkmm-3.0/LabeledTrackBar.h> #include <es++/gtkmm-3.0/ColorComposer.h> #include <es++/gtkmm-3.0/FileOpenDialog.h> #include <es++/opencv-4.0/OpenCVMainView.h> #include <es++/opencv-4.0/OpenCVScrolledImageView.h> #include <es++/opencv-4.0/OpenCVScaleComboBox.h> #include <es++/opencv-4.0/OpenCVColorFilter.h> using namespace Gtk; namespace Es { class MainView :public Es::OpenCVMainView { private: /////////////////////////////////////////////////////// //Inner classes start. class OriginalImageView :public Es::OpenCVScrolledImageView { public: OriginalImageView() { } void rescale(int scaling_ratio) { OpenCVScrolledImageView::scaleImage(scaling_ratio); } }; class TransformedImageView :public Es::OpenCVScrolledImageView { private: cv::Mat transformed_image; public: TransformedImageView() { } void loadImage(const std::string& filename, int imageLoadingFlag= CV_LOAD_IMAGE_COLOR, int scaling_ratio=100) { OpenCVScrolledImageView::loadImage(filename, imageLoadingFlag, scaling_ratio); cv::Mat& original_image = getOriginalImage(); transformed_image = original_image.clone(); scaleImage(transformed_image, scaling_ratio); } void transform(cv::Mat& filter, int scaling_ratio) { cv::Mat& original_image = getOriginalImage(); try { cv::Mat newImage = original_image.clone(); cv::transform(original_image, newImage, filter); transformed_image = newImage; scaleImage(transformed_image, scaling_ratio); } catch (Es::Exception& ex) { caught(ex); } } void rescale(int scaling_ratio) { OpenCVScrolledImageView::scaleImage(transformed_image, scaling_ratio); } }; // Inner classes end. /////////////////////////////////////////////////////// Es::Label filepath; Es::HorizontalLayout horiz_layout; Es::VerticalLayout control_pane; OriginalImageView original_image; TransformedImageView transformed_image; int loading_flag; Es::OpenCVScaleComboBox scale_combobox; Es::OpenCVColorFilter color_filter; static const int THREE = 3; Es::ColorComposer color_composer[THREE]; int scaling_ratio; //Percentage. static const int CONTROLPANE_WIDTH = 200; std::string filename; Es::FileOpenDialog file_dialog; public: ////////////////////////////////////////////// //Constructor // MainView(Es::Application& applet, std::string& name, Es::Args& args) :OpenCVMainView(applet, name, args) ,scaling_ratio(100) //100% ,file_dialog(*this, Es::FileOpenDialog::IMAGE_FILES) { int w = (int)args.get(XmNwidth); int h = (int)args.get(XmNheight); int ratio = (int)args.get(XmNscalingRatio); scaling_ratio = OpenCVImageView::validateScale(ratio); Es::MainLayout& main_layout = get_main_layout(); main_layout.pack_start(filepath, FALSE, FALSE, 0); main_layout.pack_start(horiz_layout); filename = "../../images/flower.png"; filepath.set_label(filename); int ww = (w - CONTROLPANE_WIDTH)/2; filepath.set_size_request(w, 30); original_image.set_size_request(ww, h); transformed_image.set_size_request(ww, h); control_pane.set_size_request( CONTROLPANE_WIDTH, h); horiz_layout.pack_start(original_image); horiz_layout.pack_start(transformed_image); horiz_layout.pack_start(control_pane, FALSE, FALSE, 0); scale_combobox.set_selection(scaling_ratio); scale_combobox.set_changed_callback( sigc::mem_fun(*this, &MainView::scale_changed) ); control_pane.pack_start(scale_combobox, Gtk::PACK_SHRINK); control_pane.pack_start(color_filter, Gtk::PACK_SHRINK); color_filter.set_read_only(); float r = 0.4; float g = 0.2; float b = 0.2; for (int i = 0; i<THREE; i++) { control_pane.pack_start(color_composer[i], Gtk::PACK_SHRINK); color_filter.set_value(i, r, g, b); color_composer[i].set_values(r, g, b); color_composer[i].set_value_changed_callback( sigc::mem_fun(*this, &MainView::color_composer_value_changed) ); } loading_flag = IMREAD_COLOR; original_image.loadImage(filename, loading_flag, scaling_ratio); transformed_image.loadImage(filename, loading_flag, scaling_ratio); cv::Mat& filter = color_filter.get_filter(); transformed_image.transform(filter, scaling_ratio); show_all(); } void scale_changed() { std::string scale = scale_combobox.get_active_text(); printf("scale_changed %s\n", scale.c_str()); scaling_ratio = scale_combobox.get_selection(); original_image.rescale(scaling_ratio); transformed_image.rescale(scaling_ratio); } void color_composer_value_changed() { for (int i = 0; i<THREE; i++) { float r, g, b; color_composer[i].get_values(r, g, b); color_filter.set_value(i, r, g, b); } cv::Mat& filter = color_filter.get_filter(); transformed_image.transform(filter, scaling_ratio); } void file_open() { int rc = file_dialog.popup(); if (rc == Gtk::RESPONSE_OK) { const std::string filename = file_dialog.get_filename(); filepath.set_label(filename); original_image.loadImage(filename, loading_flag, scaling_ratio); transformed_image.loadImage(filename, loading_flag, scaling_ratio); cv::Mat& filter = color_filter.get_filter(); transformed_image.transform(filter, scaling_ratio); } } }; } int main(int argc, char** argv) { Es::Environment env; try { std::string name = argv[0]; Es::Application applet(argc, argv); Es::Args args; args.set(XmNx, 20); args.set(XmNy, 40); args.set(XmNwidth, 900); args.set(XmNheight, 400); args.set(XmNscalingRatio, 60); //60% Es::MainView mainv(applet, name, args); mainv.show(); applet.run(mainv); } catch (Es::Exception& ex) { caught(ex); } catch (...) { printf("Get exception \n"); } return 0; }
[ "to-arai@antillia.com" ]
to-arai@antillia.com
d71751de9c09732a8b928f8ab5d92a6063efea80
297497957c531d81ba286bc91253fbbb78b4d8be
/third_party/libwebrtc/test/run_loop.h
bb3a2121d0b04f87e5c28b42c457e69c9d7ec361
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
marco-c/gecko-dev-comments-removed
7a9dd34045b07e6b22f0c636c0a836b9e639f9d3
61942784fb157763e65608e5a29b3729b0aa66fa
refs/heads/master
2023-08-09T18:55:25.895853
2023-08-01T00:40:39
2023-08-01T00:40:39
211,297,481
0
0
NOASSERTION
2019-09-29T01:27:49
2019-09-27T10:44:24
C++
UTF-8
C++
false
false
1,126
h
#ifndef TEST_RUN_LOOP_H_ #define TEST_RUN_LOOP_H_ #include <utility> #include "absl/functional/any_invocable.h" #include "api/task_queue/task_queue_base.h" #include "rtc_base/thread.h" namespace webrtc { namespace test { class RunLoop { public: RunLoop(); ~RunLoop(); TaskQueueBase* task_queue(); void Run(); void Quit(); void Flush(); void PostTask(absl::AnyInvocable<void() &&> task) { task_queue()->PostTask(std::move(task)); } private: class FakeSocketServer : public rtc::SocketServer { public: FakeSocketServer(); ~FakeSocketServer(); void FailNextWait(); private: bool Wait(webrtc::TimeDelta max_wait_duration, bool process_io) override; void WakeUp() override; rtc::Socket* CreateSocket(int family, int type) override; private: bool fail_next_wait_ = false; }; class WorkerThread : public rtc::Thread { public: explicit WorkerThread(rtc::SocketServer* ss); private: CurrentTaskQueueSetter tq_setter_; }; FakeSocketServer socket_server_; WorkerThread worker_thread_{&socket_server_}; }; } } #endif
[ "mcastelluccio@mozilla.com" ]
mcastelluccio@mozilla.com
87ca2546d683b6a6a95131a6389714128f085baa
77ac268c70ec0353a5b0bf62e6555c2b0ffe70c7
/src/qt/guiutil.cpp
84ba5e8c9ec4bdc872716ab7c1c6024764494c15
[ "MIT" ]
permissive
dhanesh-epixel/greenshilling
ac8cc96811c754bbd0c365cfdd80c50177db441c
2786239bb5c4aef982a5d01ab4df26000f2dce59
refs/heads/master
2021-05-11T22:46:43.520543
2017-09-19T10:47:52
2017-09-19T10:47:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,765
cpp
#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include <QString> #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { if(uri.scheme() != QString("GreenShilling")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert bitcoin:// to bitcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lowercase it (and thus invalidate the address). if(uri.startsWith("GreenShilling://")) { uri.replace(0, 9, "GreenShilling:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if(!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width()/2, w->height()/2), w)); } } // namespace GUIUtil
[ "mosdoms@mail.com" ]
mosdoms@mail.com
f032e461c7927c7998cf09d87a01d2a6389a260a
691c8269223ec970c1e230344385d53d82b85e7c
/FormeCompliquee.cpp
85fa13f0eea38614ec85695fabfcdd742300b79d
[]
no_license
schuma57/ProjetSynthese-Client
f04d1e5fe6f96f7bb25af48bbcedd4dc80e2aee9
f8fcc72369bcb98290877b2274f95e6110647ce3
refs/heads/master
2021-01-19T06:25:20.875900
2014-12-09T22:27:03
2014-12-09T22:27:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,852
cpp
//! //! \file FormeCompliquee.cpp //! #include "FormeCompliquee.h" #include "VisitorTCP.h" #include "Erreur.h" FormeCompliquee::FormeCompliquee(const Couleur::couleurs & c) : FormeGeometrique(c) { } FormeCompliquee::~FormeCompliquee() { } void FormeCompliquee::ajouterForme(FormeGeometrique* f) { if (f != NULL) { if ( f->isLibre() ) { if (f->getCouleur() != this->getCouleur()) f->setCouleur(this->getCouleur()); listeFormes.push_back(f); f->setLibre(false); } else { cout << "Ajout impossible : La forme est deja utilisee" << endl; } } } vector<FormeGeometrique*> FormeCompliquee::getListeFormes() const { return listeFormes; } double FormeCompliquee::calculAire() const { double somme = 0; for (auto forme : listeFormes) somme += forme->calculAire(); return somme; } FormeGeometrique* FormeCompliquee::translation(double l, double h) { FormeCompliquee* resultat = new FormeCompliquee(getCouleur()); for (auto forme : this->getListeFormes()) resultat->ajouterForme(forme->translation(l,h)); return resultat; } FormeGeometrique* FormeCompliquee::homothetie(double x, double y, double coeff) { FormeCompliquee* resultat = new FormeCompliquee(getCouleur()); for (auto forme : this->getListeFormes()) resultat->ajouterForme(forme->homothetie(x, y, coeff)); return resultat; } FormeGeometrique* FormeCompliquee::rotation(double x, double y, double angle) { FormeCompliquee* resultat = new FormeCompliquee(getCouleur()); for (auto forme : this->getListeFormes()) resultat->ajouterForme(forme->rotation(x, y, angle)); return resultat; } FormeCompliquee::operator string() const { string str = "Comp/" + getCouleurToString(); for (auto forme : listeFormes) str += "/" + string(*forme); return str+"/#"; } void FormeCompliquee::accept(Visitor * v) { v->visiteFormeCompliquee(*this); }
[ "iggiotti.florian@gmail.com" ]
iggiotti.florian@gmail.com
58177d09673fd8bdbc3bb6f51c9e9e74534b5722
c7120eeec717341240624c7b8a731553494ef439
/src/cplusplus/freezone-samp/src/core/messages/server_properties.cpp
33d0d92229f41f0efe06306071457ef9939edd33
[]
no_license
neverm1ndo/gta-paradise-sa
d564c1ed661090336621af1dfd04879a9c7db62d
730a89eaa6e8e4afc3395744227527748048c46d
refs/heads/master
2020-04-27T22:00:22.221323
2010-09-04T19:02:28
2010-09-04T19:02:28
174,719,907
1
0
null
2019-03-09T16:44:43
2019-03-09T16:44:43
null
UTF-8
C++
false
false
2,856
cpp
#include "config.hpp" #include <functional> #define SERVER_NAME "[RUS] GTA - Paradise" #define SERVER_SITE "www.gta-paradise.ru" #define SERVER_MODE "FreeZone" #define SERVER_MAP "Russia" #define SERVER_CRC 0x00000000 #include "server_properties.hpp" #include "core/application.hpp" #include "core/samp/samp_api.hpp" #include "core/ver.hpp" #include <boost/format.hpp> REGISTER_IN_APPLICATION(server_properties); server_properties::ptr server_properties::instance() { return application::instance()->get_item<server_properties>(); } server_properties::server_properties(): name(SERVER_NAME) ,site(SERVER_SITE) ,mode(SERVER_MODE) ,map(SERVER_MAP) ,crc(SERVER_CRC) ,mode_suffix(only_ver) ,is_mode_loaded(false) { } server_properties::~server_properties() { } void server_properties::on_gamemode_init(AMX* amx, samp::server_ver ver) { refresh_server(); is_mode_loaded = true; } void server_properties::create() { } void server_properties::configure_pre() { name_suffix = "SA"; address = "$(server_bind_ip)"; map = SERVER_MAP; } void server_properties::configure(buffer::ptr const& buff, def_t const& def) { SERIALIZE_ITEM(name_suffix); SERIALIZE_ITEM(address); SERIALIZE_ITEM(map); } void server_properties::configure_post() { if (is_mode_loaded) { refresh_server(); } } std::string server_properties::get_name() const { if (name_suffix.empty()) { return name; } else { return name + " " + name_suffix; } } std::string server_properties::get_name_suffix() const { return name_suffix; } std::string server_properties::get_site() const { return site; } std::string server_properties::get_site_full() const { return "http://" + site + "/"; } std::string server_properties::get_mode() const { if (mode_suffix.empty()) { return mode; } else { return mode + " " + mode_suffix; } } std::string server_properties::get_map() const { return map; } int server_properties::get_port() const { return samp::api::instance()->get_server_var_as_int("port"); } std::string server_properties::get_address() const { return (boost::format("%1%:%2%") % address % get_port()).str(); } std::string server_properties::get_mode_name() const { return mode; } void server_properties::refresh_server() { samp::api::ptr api_ptr = this->get_root()->get_item<samp::api>(); api_ptr->send_rcon_command("hostname " + get_name()); api_ptr->send_rcon_command("weburl " + get_site()); api_ptr->set_game_mode_text(get_mode()); api_ptr->send_rcon_command("mapname " + get_map()); } void server_properties::on_timer60000() { refresh_server(); }
[ "dimonml@19848965-7475-ded4-60a4-26152d85fbc5" ]
dimonml@19848965-7475-ded4-60a4-26152d85fbc5
2469a32578899269b630d99c6823074b63c278fd
0f599071b9ef9160700937b776cdc70123d00428
/pvconvertor/src/public/synnode/rcsSynProcNode.h
765082de77e271020fe2988b531c618df4250e51
[ "BSD-3-Clause" ]
permissive
kiwa3927/PVconverter
7dbccb49fedc905673ae488c3be34de88ef82257
5186e23c2af2c46bbf4d2916198de6473a88f26b
refs/heads/master
2023-08-14T05:48:49.202937
2021-09-23T12:36:23
2021-09-23T12:36:23
316,509,955
9
3
null
null
null
null
UTF-8
C++
false
false
410
h
#ifndef RCSSYNPROCNODE_H_ #define RCSSYNPROCNODE_H_ #include "rcsSynNode.h" class rcsSynProcNode_T: public rcsSynNode_T { public: rcsSynProcNode_T(); ~rcsSynProcNode_T(); void addChildNode(rcsSynNode_T *); const std::vector<rcsSynNode_T *> &getChildNodes() const; virtual void accept(rcsNodeVisitor_T &visitor); private: std::vector<rcsSynNode_T *> m_vChildNodes; }; #endif
[ "kiwa3927@google.com" ]
kiwa3927@google.com
2fc3e85f828271fdc5fba3fdbd20dc85708faa39
ddf45c03e0ccad94e309a5602aede3c89a911494
/src/RcppExports.cpp
33325a0db0886700f4732314716b3e6855b18d81
[]
no_license
ylleonv/sasd
06f22dc6cd1f886b296d59d94238b88ad19e07d9
f2ba98627d52c1db943565c6f15935adb82778a4
refs/heads/master
2020-12-19T04:14:01.831069
2020-01-24T16:12:07
2020-01-24T16:12:07
235,617,395
0
0
null
null
null
null
UTF-8
C++
false
false
2,063
cpp
// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include <RcppArmadillo.h> #include <RcppEigen.h> #include <Rcpp.h> using namespace Rcpp; // rcpp_hello_world List rcpp_hello_world(); RcppExport SEXP _anRpackage_rcpp_hello_world() { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = Rcpp::wrap(rcpp_hello_world()); return rcpp_result_gen; END_RCPP } RcppExport SEXP _rcpp_module_boot_mimod(); RcppExport SEXP _rcpp_module_boot_NumEx(); RcppExport SEXP _rcpp_module_boot_DERIVEDMODULE(); RcppExport SEXP _rcpp_module_boot_exportmod(); RcppExport SEXP _rcpp_module_boot_exportmoddev(); RcppExport SEXP _rcpp_module_boot_fishder(); RcppExport SEXP _rcpp_module_boot_BASEMODULE(); RcppExport SEXP _rcpp_module_boot_yada(); RcppExport SEXP _rcpp_module_boot_referencemodule(); RcppExport SEXP _rcpp_module_boot_stdVector(); static const R_CallMethodDef CallEntries[] = { {"_anRpackage_rcpp_hello_world", (DL_FUNC) &_anRpackage_rcpp_hello_world, 0}, {"_rcpp_module_boot_mimod", (DL_FUNC) &_rcpp_module_boot_mimod, 0}, {"_rcpp_module_boot_NumEx", (DL_FUNC) &_rcpp_module_boot_NumEx, 0}, {"_rcpp_module_boot_DERIVEDMODULE", (DL_FUNC) &_rcpp_module_boot_DERIVEDMODULE, 0}, {"_rcpp_module_boot_exportmod", (DL_FUNC) &_rcpp_module_boot_exportmod, 0}, {"_rcpp_module_boot_exportmoddev", (DL_FUNC) &_rcpp_module_boot_exportmoddev, 0}, {"_rcpp_module_boot_fishder", (DL_FUNC) &_rcpp_module_boot_fishder, 0}, {"_rcpp_module_boot_BASEMODULE", (DL_FUNC) &_rcpp_module_boot_BASEMODULE, 0}, {"_rcpp_module_boot_yada", (DL_FUNC) &_rcpp_module_boot_yada, 0}, {"_rcpp_module_boot_referencemodule", (DL_FUNC) &_rcpp_module_boot_referencemodule, 0}, {"_rcpp_module_boot_stdVector", (DL_FUNC) &_rcpp_module_boot_stdVector, 0}, {NULL, NULL, 0} }; RcppExport void R_init_anRpackage(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); }
[ "ylleonv@unal.edu.co" ]
ylleonv@unal.edu.co
a673def945f528db14a8ddafeae579e39de07b77
c9a462194b9146cc2141124ddaeae660a3d8e8bd
/cactusprojects/emtf/daq/hal/x86_64_slc6/include/hal/StaticVMEConfigurationASCIIFileReader.hh
94a032ddd6ff060f2025fa0fcef92a821a4caf62
[]
no_license
batinkov/emtf_cell
3d27422766aa43d57a3065bc1f34eafe7c460019
9b8beee47b04e0384662bf7b8d1134c6ca744e21
refs/heads/master
2020-04-12T05:35:18.236416
2017-06-13T15:06:34
2017-06-13T15:06:34
65,220,494
0
1
null
2017-05-26T14:58:49
2016-08-08T16:28:15
C++
UTF-8
C++
false
false
442
hh
#ifndef __StaticVMEConfigurationASCIIFileReader #define __StaticVMEConfigurationASCIIFileReader #include <string> #include "hal/NoSuchFileException.hh" #include "hal/StaticVMEConfigurationReader.hh" namespace HAL { class StaticVMEConfigurationASCIIFileReader : public StaticVMEConfigurationReader { public: StaticVMEConfigurationASCIIFileReader(std::string fileName) throw (NoSuchFileException); }; } /* namespace HAL */ #endif
[ "batinkov@kvm-s3562-1-ip149-12.cms" ]
batinkov@kvm-s3562-1-ip149-12.cms
90bfd3343792cb4b52dc2441b072bc97f5ffd16e
6e56540d3e1bfacd4ab20439bd6f67764617b077
/Algorithms/search_find_end.cpp
fec4524e11eb9031535b8f6304cf9b8980c0f842
[]
no_license
luciandinu93/STL
7d89314afe520d5fd6a7e97c4069022682182299
5f1e38fd2d9b69763ffa39c1d08e587183aeeb66
refs/heads/master
2020-04-30T13:50:04.168183
2019-04-29T07:49:45
2019-04-29T07:49:45
176,870,729
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> v = {0, 1, 2, 3, 6, 9, 8 , 1, 2, 3, 5, 8 ,9}; vector<int> sub = {1, 2, 3}; vector<int>::iterator pos1 = search(v.begin(), v.end(), sub.begin(), sub.end()); vector<int>::iterator pos2 = find_end(v.begin(), v.end(), sub.begin(), sub.end()); // display initial elements cout << "initial elements:" << endl; for(const auto& elem : v) cout << elem << " "; cout << endl; // print element from [pos1, pos2) for(pos1; pos1 != pos2; ++pos1) { cout << *pos1 << " "; } cout << endl; // remove elements from [pos1, pos2] v.erase(pos1, ++pos2); // display remaining elements cout << "remaining elements are:" << endl; for(const auto& elem : v) cout << elem << " "; cout << endl; }
[ "lucian.dinu93@yahoo.com" ]
lucian.dinu93@yahoo.com
f10acf787512873d8d7a279ba6e963c93ad38f4d
24f2e7876f825bafdba944336e371a00367f06b2
/src/Passes/FeatureMiner.cpp
408e5e143e31dc6b9f2cad763c0372d7b991425f
[ "NCSA" ]
permissive
pkuwangh/BOLT
1ecb9d5c2d55e048b8139398b3b4ebcad8cbdfda
571da22d6a9732271fe55a679a19f486a0b99a86
refs/heads/master
2022-12-15T22:41:58.614380
2020-07-08T06:01:22
2020-07-08T06:10:07
278,739,285
0
0
null
2020-07-10T21:46:14
2020-07-10T21:46:13
null
UTF-8
C++
false
false
29,115
cpp
#include "Passes/FeatureMiner.h" #include "Passes/DataflowInfoManager.h" #undef DEBUG_TYPE #define DEBUG_TYPE "bolt-feature-miner" namespace llvm { namespace bolt { class BinaryFunction; int8_t FeatureMiner::getProcedureType(BinaryFunction &Function, BinaryContext &BC) { int8_t ProcedureType = 1; for (auto &BB : Function) { for (auto &Inst : BB) { if (BC.MIB->isCall(Inst)) { ProcedureType = 0; // non-leaf type if (const auto *CalleeSymbol = BC.MIB->getTargetSymbol(Inst)) { const auto *Callee = BC.getFunctionForSymbol(CalleeSymbol); if (Callee && Callee->getFunctionNumber() == Function.getFunctionNumber()) { return 2; // call self type } } } } } return ProcedureType; // leaf type } void FeatureMiner::addSuccessorInfo(DominatorAnalysis<false> &DA, DominatorAnalysis<true> &PDA, SBIPtr const &SBI, BinaryFunction &Function, BinaryContext &BC, MCInst &Inst, BinaryBasicBlock &BB, bool SuccType) { BinaryBasicBlock *Successor = BB.getConditionalSuccessor(SuccType); if (!Successor) return; unsigned NumLoads{0}; unsigned NumStores{0}; unsigned NumCallsExit{0}; unsigned NumCalls{0}; unsigned NumCallsInvoke{0}; unsigned NumTailCalls{0}; unsigned NumIndirectCalls{0}; for (auto &Inst : BB) { if (BC.MIB->isLoad(Inst)) { ++NumLoads; } else if (BC.MIB->isStore(Inst)) { ++NumStores; } else if (BC.MIB->isCall(Inst)) { ++NumCalls; if (BC.MIB->isIndirectCall(Inst)) ++NumIndirectCalls; if (BC.MIB->isInvoke(Inst)) ++NumCallsInvoke; if (BC.MIB->isTailCall(Inst)) ++NumTailCalls; if (const auto *CalleeSymbol = BC.MIB->getTargetSymbol(Inst)) { StringRef CalleeName = CalleeSymbol->getName(); if (CalleeName == "__cxa_throw@PLT" || CalleeName == "_Unwind_Resume@PLT" || CalleeName == "__cxa_rethrow@PLT" || CalleeName == "exit@PLT" || CalleeName == "abort@PLT") ++NumCallsExit; } } } BBIPtr SuccBBInfo = std::make_unique<struct BasicBlockInfo>(); // Check if the successor basic block is a loop header and store it. SuccBBInfo->LoopHeader = BPI->isLoopHeader(Successor); SuccBBInfo->BasicBlockSize = Successor->size(); // Check if the edge getting to the successor basic block is a loop // exit edge and store it. SuccBBInfo->Exit = BPI->isExitEdge(&BB, Successor); // Check if the edge getting to the successor basic block is a loop // back edge and store it. SuccBBInfo->Backedge = BPI->isBackEdge(&BB, Successor); MCInst *SuccInst = Successor->getTerminatorBefore(nullptr); // Store information about the branch type ending sucessor basic block SuccBBInfo->EndOpcode = (SuccInst && BC.MIA->isBranch(*SuccInst)) ? SuccInst->getOpcode() : 0; // 0 = NOTHING if (SuccBBInfo->EndOpcode != 0) SuccBBInfo->EndOpcodeStr = BC.MII->getName(SuccInst->getOpcode()); else SuccBBInfo->EndOpcodeStr = "NOTHING"; // Check if the successor basic block contains // a procedure call and store it. SuccBBInfo->Call = (NumCalls > 0) ? 1 // Contains a call instruction : 0; // Does not contain a call instruction SuccBBInfo->NumStores = NumStores; SuccBBInfo->NumLoads = NumLoads; SuccBBInfo->NumCallsExit = NumCallsExit; SuccBBInfo->NumCalls = NumCalls; SuccBBInfo->NumCallsInvoke = NumCallsInvoke; SuccBBInfo->NumIndirectCalls = NumIndirectCalls; SuccBBInfo->NumTailCalls = NumTailCalls; auto InstSucc = Successor->getLastNonPseudoInstr(); if (InstSucc) { // Check if the source basic block dominates its // target basic block and store it. SuccBBInfo->BranchDominates = (DA.doesADominateB(Inst, *InstSucc) == true) ? 1 // Dominates : 0; // Does not dominate // Check if the target basic block postdominates // the source basic block and store it. SuccBBInfo->BranchPostdominates = (PDA.doesADominateB(*InstSucc, Inst) == true) ? 1 // Postdominates : 0; // Does not postdominate } /// The follwoing information is used as an identifier only for /// the purpose of matching the inferred probabilities with the branches /// in the binary. SuccBBInfo->FromFunName = Function.getPrintName(); SuccBBInfo->FromBb = BB.getInputOffset(); BinaryFunction *ToFun = Successor->getFunction(); SuccBBInfo->ToFunName = ToFun->getPrintName(); SuccBBInfo->ToBb = Successor->getInputOffset(); auto Offset = BC.MIB->tryGetAnnotationAs<uint64_t>(Inst, "Offset"); if (Offset) { int64_t Delta = Successor->getInputOffset() - Offset.get(); SBI->DeltaTaken = std::abs(Delta); } if (SuccType) { SBI->TrueSuccessor = std::move(SuccBBInfo); // Check if the taken branch is a forward // or a backwards branch and store it. SBI->Direction = (Function.isForwardBranch(&BB, Successor) == true) ? 1 // Forward branch : 0; // Backwards branch auto TakenBranchInfo = BB.getTakenBranchInfo(); SBI->Count = TakenBranchInfo.Count; SBI->MissPredicted = TakenBranchInfo.MispredictedCount; } else { SBI->FalseSuccessor = std::move(SuccBBInfo); auto FallthroughBranchInfo = BB.getFallthroughBranchInfo(); SBI->FallthroughCount = FallthroughBranchInfo.Count; SBI->FallthroughMissPredicted = FallthroughBranchInfo.MispredictedCount; } } void FeatureMiner::extractFeatures(BinaryFunction &Function, BinaryContext &BC) { int8_t ProcedureType = getProcedureType(Function, BC); auto Info = DataflowInfoManager(BC, Function, nullptr, nullptr); auto &DA = Info.getDominatorAnalysis(); auto &PDA = Info.getPostDominatorAnalysis(); const BinaryLoopInfo &LoopsInfo = Function.getLoopInfo(); bool Simple = Function.isSimple(); for (auto &BB : Function) { unsigned NumOuterLoops{0}; unsigned TotalLoops{0}; unsigned MaximumLoopDepth{0}; unsigned LoopDepth{0}; unsigned LoopNumExitEdges{0}; unsigned LoopNumExitBlocks{0}; unsigned LoopNumExitingBlocks{0}; unsigned LoopNumLatches{0}; unsigned LoopNumBlocks{0}; unsigned LoopNumBackEdges{0}; bool LocalExitingBlock{false}; bool LocalLatchBlock{false}; bool LocalLoopHeader{false}; BinaryLoop *Loop = LoopsInfo.getLoopFor(&BB); if (Loop) { SmallVector<BinaryBasicBlock *, 1> ExitingBlocks; Loop->getExitingBlocks(ExitingBlocks); SmallVector<BinaryBasicBlock *, 1> ExitBlocks; Loop->getExitBlocks(ExitBlocks); SmallVector<BinaryLoop::Edge, 1> ExitEdges; Loop->getExitEdges(ExitEdges); SmallVector<BinaryBasicBlock *, 1> Latches; Loop->getLoopLatches(Latches); NumOuterLoops = LoopsInfo.OuterLoops; TotalLoops = LoopsInfo.TotalLoops; MaximumLoopDepth = LoopsInfo.MaximumDepth; LoopDepth = Loop->getLoopDepth(); LoopNumExitEdges = ExitEdges.size(); LoopNumExitBlocks = ExitBlocks.size(); LoopNumExitingBlocks = ExitingBlocks.size(); LoopNumLatches = Latches.size(); LoopNumBlocks = Loop->getNumBlocks(); LoopNumBackEdges = Loop->getNumBackEdges(); LocalExitingBlock = Loop->isLoopExiting(&BB); LocalLatchBlock = Loop->isLoopLatch(&BB); LocalLoopHeader = ((Loop->getHeader() == (&BB)) ? 1 : 0); } unsigned NumLoads{0}; unsigned NumStores{0}; unsigned NumCallsExit{0}; unsigned NumCalls{0}; unsigned NumCallsInvoke{0}; unsigned NumTailCalls{0}; unsigned NumIndirectCalls{0}; unsigned NumSelfCalls{0}; for (auto &Inst : BB) { if (BC.MIB->isLoad(Inst)) { ++NumLoads; } else if (BC.MIB->isStore(Inst)) { ++NumStores; } else if (BC.MIB->isCall(Inst)) { ++NumCalls; if (BC.MIB->isIndirectCall(Inst)) ++NumIndirectCalls; if (BC.MIB->isInvoke(Inst)) ++NumCallsInvoke; if (BC.MIB->isTailCall(Inst)) ++NumTailCalls; if (const auto *CalleeSymbol = BC.MIB->getTargetSymbol(Inst)) { StringRef CalleeName = CalleeSymbol->getName(); if (CalleeName == "__cxa_throw@PLT" || CalleeName == "_Unwind_Resume@PLT" || CalleeName == "__cxa_rethrow@PLT" || CalleeName == "exit@PLT" || CalleeName == "abort@PLT") ++NumCallsExit; else if (CalleeName == Function.getPrintName()) { ++NumSelfCalls; } } } } int Index = -2; bool LoopHeader = BPI->isLoopHeader(&BB); for (auto &Inst : BB) { ++Index; if (!BC.MIA->isConditionalBranch(Inst)) continue; SBIPtr SBI = std::make_unique<struct StaticBranchInfo>(); SBI->Simple = Simple; SBI->NumOuterLoops = NumOuterLoops; SBI->TotalLoops = TotalLoops; SBI->MaximumLoopDepth = MaximumLoopDepth; SBI->LoopDepth = LoopDepth; SBI->LoopNumExitEdges = LoopNumExitEdges; SBI->LoopNumExitBlocks = LoopNumExitBlocks; SBI->LoopNumExitingBlocks = LoopNumExitingBlocks; SBI->LoopNumLatches = LoopNumLatches; SBI->LoopNumBlocks = LoopNumBlocks; SBI->LoopNumBackEdges = LoopNumBackEdges; SBI->LocalExitingBlock = LocalExitingBlock; SBI->LocalLatchBlock = LocalLatchBlock; SBI->LocalLoopHeader = LocalLoopHeader; SBI->Call = ((NumCalls > 0) ? 1 : 0); SBI->NumCalls = NumCalls; SBI->BasicBlockSize = BB.size(); SBI->NumBasicBlocks = Function.size(); SBI->NumSelfCalls = NumSelfCalls; SBI->NumLoads = NumLoads; SBI->NumStores = NumStores; SBI->NumCallsExit = NumCallsExit; SBI->NumCallsInvoke = NumCallsInvoke; SBI->NumIndirectCalls = NumIndirectCalls; SBI->NumTailCalls = NumTailCalls; // Check if branch's basic block is a loop header and store it. SBI->LoopHeader = LoopHeader; // Adding taken successor info. addSuccessorInfo(DA, PDA, SBI, Function, BC, Inst, BB, true); // Adding fall through successor info. addSuccessorInfo(DA, PDA, SBI, Function, BC, Inst, BB, false); // Holds the branch opcode info. SBI->Opcode = Inst.getOpcode(); SBI->OpcodeStr = BC.MII->getName(Inst.getOpcode()); // Holds the branch's procedure type. SBI->ProcedureType = ProcedureType; SBI->CmpOpcode = 0; if (Index > -1) { auto Cmp = BB.begin() + Index; if (BC.MII->get((*Cmp).getOpcode()).isCompare()) { // Holding the branch comparison opcode info. SBI->CmpOpcode = (*Cmp).getOpcode(); SBI->CmpOpcodeStr = BC.MII->getName((*Cmp).getOpcode()); auto getOperandType = [&](const MCOperand &Operand) -> int32_t { if (Operand.isReg()) return 0; else if (Operand.isImm()) return 1; else if (Operand.isFPImm()) return 2; else if (Operand.isExpr()) return 3; else return -1; }; const auto InstInfo = BC.MII->get((*Cmp).getOpcode()); unsigned NumDefs = InstInfo.getNumDefs(); int32_t NumPrimeOperands = MCPlus::getNumPrimeOperands(*Cmp) - NumDefs; switch (NumPrimeOperands) { case 6: { int32_t RBType = getOperandType((*Cmp).getOperand(NumDefs)); int32_t RAType = getOperandType((*Cmp).getOperand(NumDefs + 1)); if (RBType == 0 && RAType == 0) { SBI->OperandRBType = RBType; SBI->OperandRAType = RAType; } else if (RBType == 0 && (RAType == 1 || RAType == 2)) { RAType = getOperandType((*Cmp).getOperand(NumPrimeOperands - 1)); if (RAType != 1 && RAType != 2) { RAType = -1; } SBI->OperandRBType = RBType; SBI->OperandRAType = RAType; } else { SBI->OperandRAType = -1; SBI->OperandRBType = -1; } break; } case 2: SBI->OperandRBType = getOperandType((*Cmp).getOperand(NumDefs)); SBI->OperandRAType = getOperandType((*Cmp).getOperand(NumDefs + 1)); break; case 3: SBI->OperandRBType = getOperandType((*Cmp).getOperand(NumDefs)); SBI->OperandRAType = getOperandType((*Cmp).getOperand(NumDefs + 2)); break; case 1: SBI->OperandRAType = getOperandType((*Cmp).getOperand(NumDefs)); break; default: SBI->OperandRAType = -1; SBI->OperandRBType = -1; break; } } else { Index -= 1; for (int Idx = Index; Idx > -1; Idx--) { auto Cmp = BB.begin() + Idx; if (BC.MII->get((*Cmp).getOpcode()).isCompare()) { // Holding the branch comparison opcode info. SBI->CmpOpcode = (*Cmp).getOpcode(); SBI->CmpOpcodeStr = BC.MII->getName((*Cmp).getOpcode()); break; } } } } this->BranchesInfoSet.push_back(std::move(SBI)); } } } void FeatureMiner::dumpSuccessorFeatures(raw_ostream &Printer, BBIPtr &Successor) { int16_t BranchDominates = (Successor->BranchDominates.hasValue()) ? static_cast<bool>(*(Successor->BranchDominates)) : -1; int16_t BranchPostdominates = (Successor->BranchPostdominates.hasValue()) ? static_cast<bool>(*(Successor->BranchPostdominates)) : -1; int16_t LoopHeader = (Successor->LoopHeader.hasValue()) ? static_cast<bool>(*(Successor->LoopHeader)) : -1; int16_t Backedge = (Successor->Backedge.hasValue()) ? static_cast<bool>(*(Successor->Backedge)) : -1; int16_t Exit = (Successor->Exit.hasValue()) ? static_cast<bool>(*(Successor->Exit)) : -1; int16_t Call = (Successor->Call.hasValue()) ? static_cast<bool>(*(Successor->Call)) : -1; int32_t EndOpcode = (Successor->EndOpcode.hasValue()) ? static_cast<int32_t>(*(Successor->EndOpcode)) : -1; int64_t NumLoads = (Successor->NumLoads.hasValue()) ? static_cast<int64_t>(*(Successor->NumLoads)) : -1; int64_t NumStores = (Successor->NumStores.hasValue()) ? static_cast<int64_t>(*(Successor->NumStores)) : -1; int64_t BasicBlockSize = (Successor->BasicBlockSize.hasValue()) ? static_cast<int64_t>(*(Successor->BasicBlockSize)) : -1; int64_t NumCalls = (Successor->NumCalls.hasValue()) ? static_cast<int64_t>(*(Successor->NumCalls)) : -1; int64_t NumCallsExit = (Successor->NumCallsExit.hasValue()) ? static_cast<int64_t>(*(Successor->NumCallsExit)) : -1; int64_t NumCallsInvoke = (Successor->NumCallsInvoke.hasValue()) ? static_cast<int64_t>(*(Successor->NumCallsInvoke)) : -1; int64_t NumIndirectCalls = (Successor->NumIndirectCalls.hasValue()) ? static_cast<int64_t>(*(Successor->NumIndirectCalls)) : -1; int64_t NumTailCalls = (Successor->NumTailCalls.hasValue()) ? static_cast<int64_t>(*(Successor->NumTailCalls)) : -1; Printer << "," << BranchDominates << "," << BranchPostdominates << "," << EndOpcode << "," << Successor->EndOpcodeStr << "," << LoopHeader << "," << Backedge << "," << Exit << "," << Call << "," << Successor->FromFunName << "," << Twine::utohexstr(Successor->FromBb) << "," << Successor->ToFunName << "," << Twine::utohexstr(Successor->ToBb) << "," << NumLoads << "," << NumStores << "," << BasicBlockSize << "," << NumCalls << "," << NumCallsExit << "," << NumIndirectCalls << "," << NumCallsInvoke << "," << NumTailCalls; } void FeatureMiner::dumpFeatures(raw_ostream &Printer, uint64_t FunctionAddress) { for (auto const &SBI : BranchesInfoSet) { auto &FalseSuccessor = SBI->FalseSuccessor; auto &TrueSuccessor = SBI->TrueSuccessor; if (!FalseSuccessor && !TrueSuccessor) continue; int16_t ProcedureType = (SBI->ProcedureType.hasValue()) ? static_cast<int16_t>(*(SBI->ProcedureType)) : -1; int16_t Direction = (SBI->Direction.hasValue()) ? static_cast<bool>(*(SBI->Direction)) : -1; int16_t LoopHeader = (SBI->LoopHeader.hasValue()) ? static_cast<bool>(*(SBI->LoopHeader)) : -1; int32_t Opcode = (SBI->Opcode.hasValue()) ? static_cast<int32_t>(*(SBI->Opcode)) : -1; int32_t CmpOpcode = (SBI->CmpOpcode.hasValue()) ? static_cast<int32_t>(*(SBI->CmpOpcode)) : -1; int64_t Count = (SBI->Count.hasValue()) ? static_cast<int64_t>(*(SBI->Count)) : -1; int64_t MissPredicted = (SBI->MissPredicted.hasValue()) ? static_cast<int64_t>(*(SBI->MissPredicted)) : -1; int64_t FallthroughCount = (SBI->FallthroughCount.hasValue()) ? static_cast<int64_t>(*(SBI->FallthroughCount)) : -1; int64_t FallthroughMissPredicted = (SBI->FallthroughMissPredicted.hasValue()) ? static_cast<int64_t>(*(SBI->FallthroughMissPredicted)) : -1; int64_t NumOuterLoops = (SBI->NumOuterLoops.hasValue()) ? static_cast<int64_t>(*(SBI->NumOuterLoops)) : -1; int64_t TotalLoops = (SBI->TotalLoops.hasValue()) ? static_cast<int64_t>(*(SBI->TotalLoops)) : -1; int64_t MaximumLoopDepth = (SBI->MaximumLoopDepth.hasValue()) ? static_cast<int64_t>(*(SBI->MaximumLoopDepth)) : -1; int64_t LoopDepth = (SBI->LoopDepth.hasValue()) ? static_cast<int64_t>(*(SBI->LoopDepth)) : -1; int64_t LoopNumExitEdges = (SBI->LoopNumExitEdges.hasValue()) ? static_cast<int64_t>(*(SBI->LoopNumExitEdges)) : -1; int64_t LoopNumExitBlocks = (SBI->LoopNumExitBlocks.hasValue()) ? static_cast<int64_t>(*(SBI->LoopNumExitBlocks)) : -1; int64_t LoopNumExitingBlocks = (SBI->LoopNumExitingBlocks.hasValue()) ? static_cast<int64_t>(*(SBI->LoopNumExitingBlocks)) : -1; int64_t LoopNumLatches = (SBI->LoopNumLatches.hasValue()) ? static_cast<int64_t>(*(SBI->LoopNumLatches)) : -1; int64_t LoopNumBlocks = (SBI->LoopNumBlocks.hasValue()) ? static_cast<int64_t>(*(SBI->LoopNumBlocks)) : -1; int64_t LoopNumBackEdges = (SBI->LoopNumBackEdges.hasValue()) ? static_cast<int64_t>(*(SBI->LoopNumBackEdges)) : -1; int64_t LocalExitingBlock = (SBI->LocalExitingBlock.hasValue()) ? static_cast<bool>(*(SBI->LocalExitingBlock)) : -1; int64_t LocalLatchBlock = (SBI->LocalLatchBlock.hasValue()) ? static_cast<bool>(*(SBI->LocalLatchBlock)) : -1; int64_t LocalLoopHeader = (SBI->LocalLoopHeader.hasValue()) ? static_cast<bool>(*(SBI->LocalLoopHeader)) : -1; int64_t Call = (SBI->Call.hasValue()) ? static_cast<bool>(*(SBI->Call)) : -1; int64_t DeltaTaken = (SBI->DeltaTaken.hasValue()) ? static_cast<int64_t>(*(SBI->DeltaTaken)) : -1; int64_t NumLoads = (SBI->NumLoads.hasValue()) ? static_cast<int64_t>(*(SBI->NumLoads)) : -1; int64_t NumStores = (SBI->NumStores.hasValue()) ? static_cast<int64_t>(*(SBI->NumStores)) : -1; int64_t BasicBlockSize = (SBI->BasicBlockSize.hasValue()) ? static_cast<int64_t>(*(SBI->BasicBlockSize)) : -1; int64_t NumBasicBlocks = (SBI->NumBasicBlocks.hasValue()) ? static_cast<int64_t>(*(SBI->NumBasicBlocks)) : -1; int64_t NumCalls = (SBI->NumCalls.hasValue()) ? static_cast<int64_t>(*(SBI->NumCalls)) : -1; int64_t NumSelfCalls = (SBI->NumSelfCalls.hasValue()) ? static_cast<int64_t>(*(SBI->NumSelfCalls)) : -1; int64_t NumCallsExit = (SBI->NumCallsExit.hasValue()) ? static_cast<int64_t>(*(SBI->NumCallsExit)) : -1; int64_t OperandRAType = (SBI->OperandRAType.hasValue()) ? static_cast<int32_t>(*(SBI->OperandRAType)) : -1; int64_t OperandRBType = (SBI->OperandRBType.hasValue()) ? static_cast<int32_t>(*(SBI->OperandRBType)) : -1; int64_t NumCallsInvoke = (SBI->NumCallsInvoke.hasValue()) ? static_cast<int64_t>(*(SBI->NumCallsInvoke)) : -1; int64_t NumIndirectCalls = (SBI->NumIndirectCalls.hasValue()) ? static_cast<int64_t>(*(SBI->NumIndirectCalls)) : -1; int64_t NumTailCalls = (SBI->NumTailCalls.hasValue()) ? static_cast<int64_t>(*(SBI->NumTailCalls)) : -1; Printer << SBI->Simple << "," << Opcode << "," << SBI->OpcodeStr << "," << Direction << "," << CmpOpcode << "," << SBI->CmpOpcodeStr << "," << LoopHeader << "," << ProcedureType << "," << Count << "," << MissPredicted << "," << FallthroughCount << "," << FallthroughMissPredicted << "," << NumOuterLoops << "," << NumCallsExit << "," << TotalLoops << "," << MaximumLoopDepth << "," << LoopDepth << "," << LoopNumExitEdges << "," << LoopNumExitBlocks << "," << LoopNumExitingBlocks << "," << LoopNumLatches << "," << LoopNumBlocks << "," << LoopNumBackEdges << "," << LocalExitingBlock << "," << LocalLatchBlock << "," << LocalLoopHeader << "," << Call << "," << DeltaTaken << "," << NumLoads << "," << NumStores << "," << NumCalls << "," << OperandRAType << "," << OperandRBType << "," << BasicBlockSize << "," << NumBasicBlocks << "," << NumCallsInvoke << "," << NumIndirectCalls << "," << NumTailCalls << "," << NumSelfCalls; if (FalseSuccessor && TrueSuccessor) { dumpSuccessorFeatures(Printer, TrueSuccessor); dumpSuccessorFeatures(Printer, FalseSuccessor); } Printer << "," << Twine::utohexstr(FunctionAddress) << "\n"; } BranchesInfoSet.clear(); } void FeatureMiner::runOnFunctions(BinaryContext &BC) { auto FileName = "features.csv"; outs() << "BOLT-DEBUG: Dumping Binary's Features to " << FileName << "\n"; std::error_code EC; raw_fd_ostream Printer(FileName, EC, sys::fs::F_None); if (EC) { errs() << "BOLT-WARNING: " << EC.message() << ", unable to open " << FileName << " for output.\n"; return; } auto FILENAME = "profile_data_regular.fdata"; raw_fd_ostream Printer2(FILENAME, EC, sys::fs::F_None); if (EC) { dbgs() << "BOLT-WARNING: " << EC.message() << ", unable to open" << " " << FILENAME << " for output.\n"; return; } // CSV file header Printer << "FUN_TYPE,OPCODE,OPCODE_STR,DIRECTION,CMP_OPCODE,CMP_OPCODE_STR," "LOOP_HEADER,PROCEDURE_TYPE," "COUNT_TAKEN,MISS_TAKEN,COUNT_NOT_TAKEN,MISS_NOT_TAKEN," "NUM_OUTER_LOOPS,NUM_CALLS_EXIT,TOTAL_LOOPS,MAXIMUM_LOOP_DEPTH," "LOOP_DEPTH,LOOP_NUM_EXIT_EDGES,LOOP_NUM_EXIT_BLOCKS," "LOOP_NUM_EXITING_BLOCKS,LOOP_NUM_LATCHES,LOOP_NUM_BLOCKS," "LOOP_NUM_BAKCEDGES,LOCAL_EXITING_BLOCK,LOCAL_LATCH_BLOCK," "LOCAL_LOOP_HEADER,CALL,DELTA_TAKEN,NUM_LOADS,NUM_STORES," "NUM_CALLS,OPERAND_RA_TYPE,OPERAND_RB_TYPE,BASIC_BLOCK_SIZE," "NUM_BASIC_BLOCKS,NUM_CALLS_INVOKE,NUM_INDIRECT_CALLS," "NUM_TAIL_CALLS,NUM_SELF_CALLS,TS_DOMINATES,TS_POSTDOMINATES," "TS_END_OPCODE,TS_END_OPCODE_STR,TS_LOOP_HEADER,TS_BACKEDGE,TS_" "EXIT,TS_CALL," "TS_FROM_FUN_NAME,TS_FROM_BB,TS_TO_FUN_NAME,TS_TO_BB,TS_NUM_LOADS," "TS_NUM_STORES,TS_BASIC_BLOCK_SIZE,TS_NUM_CALLS,TS_NUM_CALLS_EXIT," "TS_NUM_INDIRECT_CALL,TS_NUM_CALLS_INVOKE,TS_NUM_TAIL_CALLS," "FS_DOMINATES,FS_POSTDOMINATES,FS_END_OPCODE,FS_END_OPCODE_STR,FS_" "LOOP_HEADER," "FS_BACKEDGE,FS_EXIT,FS_CALL,FS_FROM_FUN_NAME,FS_FROM_BB," "FS_TO_FUN_NAME,FS_TO_BB,FS_NUM_LOADS,FS_NUM_STORES," "FS_BASIC_BLOCK_SIZE,FS_NUM_CALLS,FS_NUM_CALLS_EXIT," "FS_NUM_INDIRECT_CALL,FS_NUM_CALLS_INVOKE,FS_NUM_TAIL_CALLS," "FUN_ENTRY_ADDRESS\n"; auto &BFs = BC.getBinaryFunctions(); BPI = std::make_unique<BranchPredictionInfo>(); for (auto &BFI : BFs) { BinaryFunction &Function = BFI.second; if (Function.empty()) // || !Function.isSimple()) continue; if (!Function.isLoopFree()) { const BinaryLoopInfo &LoopsInfo = Function.getLoopInfo(); BPI->findLoopEdgesInfo(LoopsInfo); } extractFeatures(Function, BC); BPI->clear(); dumpFeatures(Printer, Function.getAddress()); dumpProfileData(Function, Printer2); } } void FeatureMiner::dumpProfileData(BinaryFunction &Function, raw_ostream &Printer) { BinaryContext &BC = Function.getBinaryContext(); std::string FromFunName = Function.getPrintName(); for (auto &BB : Function) { auto LastInst = BB.getLastNonPseudoInstr(); for (auto &Inst : BB) { if (!BC.MIB->isCall(Inst) && !BC.MIB->isBranch(Inst) && LastInst != (&Inst)) continue; auto Offset = BC.MIB->tryGetAnnotationAs<uint64_t>(Inst, "Offset"); if (!Offset) continue; uint64_t TakenFreqEdge = 0; auto FromBb = Offset.get(); std::string ToFunName; uint32_t ToBb; if (BC.MIB->isCall(Inst)) { auto *CalleeSymbol = BC.MIB->getTargetSymbol(Inst); if (!CalleeSymbol) continue; ToFunName = CalleeSymbol->getName(); ToBb = 0; if (BC.MIB->getConditionalTailCall(Inst)) { if (BC.MIB->hasAnnotation(Inst, "CTCTakenCount")) { auto CountAnnt = BC.MIB->tryGetAnnotationAs<uint64_t>(Inst, "CTCTakenCount"); if (CountAnnt) { TakenFreqEdge = (*CountAnnt); } } } else { if (BC.MIB->hasAnnotation(Inst, "Count")) { auto CountAnnt = BC.MIB->tryGetAnnotationAs<uint64_t>(Inst, "Count"); if (CountAnnt) { TakenFreqEdge = (*CountAnnt); } } } if (TakenFreqEdge > 0) Printer << "1 " << FromFunName << " " << Twine::utohexstr(FromBb) << " 1 " << ToFunName << " " << Twine::utohexstr(ToBb) << " " << 0 << " " << TakenFreqEdge << "\n"; } else { for (BinaryBasicBlock *SuccBB : BB.successors()) { TakenFreqEdge = BB.getBranchInfo(*SuccBB).Count; BinaryFunction *ToFun = SuccBB->getFunction(); ToFunName = ToFun->getPrintName(); ToBb = SuccBB->getInputOffset(); if (TakenFreqEdge > 0) Printer << "1 " << FromFunName << " " << Twine::utohexstr(FromBb) << " 1 " << ToFunName << " " << Twine::utohexstr(ToBb) << " " << 0 << " " << TakenFreqEdge << "\n"; } } } } } } // namespace bolt } // namespace llvm
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
64e6083ae8b0f1f22c9093fe181defb2bb9627a4
02ad63343b1ddd4e43fd25e10b65522cac416447
/DifferenceAndProduct.cpp
9807620d4ec0eca36eb4cb56f414842c28035813
[]
no_license
Tarun-Sharma9168/ProgrammingForMathsHAckerrank
09f0b9bfd008fdba5e92757c5801203a9fc100c9
abcc666845700aa4dba4233ad05b0b1f4b4a6d44
refs/heads/master
2020-08-13T16:09:57.935501
2019-10-14T09:13:55
2019-10-14T09:13:55
214,998,460
0
0
null
null
null
null
UTF-8
C++
false
false
1,598
cpp
#include<iostream> #include<algorithm> #include<cstdio> #include<cmath> #include<cstring> #include<vector> #include<iomanip> #include<map> #define ull unsigned long long int #define fl(i,n) for(i=0;i<n;i++) #define ls(i,s) for(i=0;s[i]!='\0';i++) #define gi(x) fastscan(x) #define pi(x) printf("%d",x) #define checkline(x) while(x!='\0' && x!='\n') #define pn printf('\n') #define ps printf(' ') #define lli long long int using namespace std; int main() { ull t,ans; lli xy,D,p,d; double x; cin>>t; while(t--) { ans=0; cin>>d>>p; if(d<0) { cout<<0<<'\n'; } else if(p==0 && d==0) cout<<1<<'\n'; else if(d==0) { xy = (lli)sqrt(p); if(xy*xy==p ) cout<<2<<'\n'; else cout<<0<<'\n'; } else if(p==0) { cout<<4<<'\n'; } else { D= (d*d) + (4*p); xy = (lli)sqrt(D); ans=0; if(D==0) if(d%2==0) cout<<2<<'\n'; else cout<<0<<'\n'; else if(xy*xy == D) { //ans = 0; if((d+xy)%2==0) ans+=2; if((d-xy)%2==0) ans+=2; cout<<ans<<'\n'; } else { cout<<0<<'\n'; } } } return 0; }
[ "noreply@github.com" ]
noreply@github.com
9cd673622dd787594e950d248b1adda617ebcdf8
167bd22e7f77cd76d1883e9b65062775cb937de5
/2DEngine/Project/Project/Reflectionshaderclass.cpp
4ab1bdaca727773de67a1bfd2fb23bc90435acb6
[]
no_license
Eganhimself/2DEngine
479fb10941201d2170f1f4771e5ea2fcd1173e6a
855b24ba2ef822e51de334144f732ea9d13bc1d7
refs/heads/master
2016-09-11T12:55:47.562295
2012-08-26T00:55:47
2012-08-26T00:55:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,067
cpp
//////////////////////////////////////////////////////////////////////////////// // Filename: reflectionshaderclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "reflectionshaderclass.h" ReflectionShaderClass::ReflectionShaderClass() { m_vertexShader = 0; m_pixelShader = 0; m_layout = 0; m_matrixBuffer = 0; m_sampleState = 0; m_reflectionBuffer = 0; } ReflectionShaderClass::ReflectionShaderClass(const ReflectionShaderClass& other) { } ReflectionShaderClass::~ReflectionShaderClass() { } bool ReflectionShaderClass::Initialize(ID3D11Device* device, HWND hwnd) { bool result; // Initialize the vertex and pixel shaders. result = InitializeShader(device, hwnd, L"../Project/reflection.vs", L"../Project/reflection.ps"); if(!result) { return false; } return true; } void ReflectionShaderClass::Shutdown() { // Shutdown the vertex and pixel shaders as well as the related objects. ShutdownShader(); return; } bool ReflectionShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, ID3D11ShaderResourceView* reflectionTexture, D3DXMATRIX reflectionMatrix) { bool result; // Set the shader parameters that it will use for rendering. result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture, reflectionTexture, reflectionMatrix); if(!result) { return false; } // Now render the prepared buffers with the shader. RenderShader(deviceContext, indexCount); return true; } bool ReflectionShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; unsigned int numElements; D3D11_BUFFER_DESC matrixBufferDesc; D3D11_SAMPLER_DESC samplerDesc; D3D11_BUFFER_DESC reflectionBufferDesc; // Initialize the pointers this function will use to null. errorMessage = 0; vertexShaderBuffer = 0; pixelShaderBuffer = 0; // Compile the vertex shader code. result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "ReflectionVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL); if(FAILED(result)) { // If the shader failed to compile it should have writen something to the error message. if(errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, vsFilename); } // If there was nothing in the error message then it simply could not find the shader file itself. else { MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK); } return false; } // Compile the pixel shader code. result = D3DX11CompileFromFile(psFilename, NULL, NULL, "ReflectionPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL); if(FAILED(result)) { // If the shader failed to compile it should have writen something to the error message. if(errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, psFilename); } // If there was nothing in the error message then it simply could not find the file itself. else { MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK); } return false; } // Create the vertex shader from the buffer. result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); if(FAILED(result)) { return false; } // Create the vertex shader from the buffer. result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); if(FAILED(result)) { return false; } // Create the vertex input layout description. // This setup needs to match the VertexType stucture in the ModelLoader and in the shader. polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "TEXCOORD"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; // Get a count of the elements in the layout. numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // Create the vertex input layout. result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); if(FAILED(result)) { return false; } // Release the vertex shader buffer and pixel shader buffer since they are no longer needed. vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; // Setup the description of the matrix dynamic constant buffer that is in the vertex shader. matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); if(FAILED(result)) { return false; } // Create a texture sampler state description. samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; // Create the texture sampler state. result = device->CreateSamplerState(&samplerDesc, &m_sampleState); if(FAILED(result)) { return false; } // Setup the description of the reflection dynamic constant buffer that is in the vertex shader. reflectionBufferDesc.Usage = D3D11_USAGE_DYNAMIC; reflectionBufferDesc.ByteWidth = sizeof(ReflectionBufferType); reflectionBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; reflectionBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; reflectionBufferDesc.MiscFlags = 0; reflectionBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. result = device->CreateBuffer(&reflectionBufferDesc, NULL, &m_reflectionBuffer); if(FAILED(result)) { return false; } return true; } void ReflectionShaderClass::ShutdownShader() { // Release the reflection constant buffer. if(m_reflectionBuffer) { m_reflectionBuffer->Release(); m_reflectionBuffer = 0; } // Release the sampler state. if(m_sampleState) { m_sampleState->Release(); m_sampleState = 0; } // Release the matrix constant buffer. if(m_matrixBuffer) { m_matrixBuffer->Release(); m_matrixBuffer = 0; } // Release the layout. if(m_layout) { m_layout->Release(); m_layout = 0; } // Release the pixel shader. if(m_pixelShader) { m_pixelShader->Release(); m_pixelShader = 0; } // Release the vertex shader. if(m_vertexShader) { m_vertexShader->Release(); m_vertexShader = 0; } return; } void ReflectionShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename) { char* compileErrors; unsigned long bufferSize, i; ofstream fout; // Get a pointer to the error message text buffer. compileErrors = (char*)(errorMessage->GetBufferPointer()); // Get the length of the message. bufferSize = errorMessage->GetBufferSize(); // Open a file to write the error message to. fout.open("shader-error.txt"); // Write out the error message. for(i=0; i<bufferSize; i++) { fout << compileErrors[i]; } // Close the file. fout.close(); // Release the error message. errorMessage->Release(); errorMessage = 0; // Pop a message up on the screen to notify the user to check the text file for compile errors. MessageBox(hwnd, L"Error compiling shader. Check shader-error.txt for message.", shaderFilename, MB_OK); return; } bool ReflectionShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, ID3D11ShaderResourceView* reflectionTexture, D3DXMATRIX reflectionMatrix) { HRESULT result; D3D11_MAPPED_SUBRESOURCE mappedResource; MatrixBufferType* dataPtr; unsigned int bufferNumber; ReflectionBufferType* dataPtr2; // Transpose the matrices to prepare them for the shader. D3DXMatrixTranspose(&worldMatrix, &worldMatrix); D3DXMatrixTranspose(&viewMatrix, &viewMatrix); D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix); // Transpose the relfection matrix to prepare it for the shader. D3DXMatrixTranspose(&reflectionMatrix, &reflectionMatrix); // Lock the matrix constant buffer so it can be written to. result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if(FAILED(result)) { return false; } // Get a pointer to the data in the matrix constant buffer. dataPtr = (MatrixBufferType*)mappedResource.pData; // Copy the matrices into the matrix constant buffer. dataPtr->world = worldMatrix; dataPtr->view = viewMatrix; dataPtr->projection = projectionMatrix; // Unlock the matrix constant buffer. deviceContext->Unmap(m_matrixBuffer, 0); // Set the position of the matrix constant buffer in the vertex shader. bufferNumber = 0; // Now set the matrix constant buffer in the vertex shader with the updated values. deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer); // Lock the reflection constant buffer so it can be written to. result = deviceContext->Map(m_reflectionBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if(FAILED(result)) { return false; } // Get a pointer to the data in the matrix constant buffer. dataPtr2 = (ReflectionBufferType*)mappedResource.pData; // Copy the matrix into the reflection constant buffer. dataPtr2->reflectionMatrix = reflectionMatrix; // Unlock the reflection constant buffer. deviceContext->Unmap(m_reflectionBuffer, 0); // Set the position of the reflection constant buffer in the vertex shader. bufferNumber = 1; // Now set the reflection constant buffer in the vertex shader with the updated values. deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_reflectionBuffer); // Set shader texture resource in the pixel shader. deviceContext->PSSetShaderResources(0, 1, &texture); // Set the reflection texture resource in the pixel shader. deviceContext->PSSetShaderResources(1, 1, &reflectionTexture); return true; } void ReflectionShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount) { // Set the vertex input layout. deviceContext->IASetInputLayout(m_layout); // Set the vertex and pixel shaders that will be used to render this triangle. deviceContext->VSSetShader(m_vertexShader, NULL, 0); deviceContext->PSSetShader(m_pixelShader, NULL, 0); // Set the sampler state in the pixel shader. deviceContext->PSSetSamplers(0, 1, &m_sampleState); // Render the triangle. deviceContext->DrawIndexed(indexCount, 0, 0); return; }
[ "jamesphillipegan@gmail.com" ]
jamesphillipegan@gmail.com
1cb9d4472fa19eeae3bbe53dce7692c6d0ed84c0
8a55d6fff45a1be44411151875f3ad1efdff49f0
/src/zelva/MainFrm.h
9179fb1126f5619011f8a83613713aa6163c3532
[]
no_license
MarVybCZ/zelva
dceee8808ae0a0b6f506d805bea01a95dc84a6c2
86c99f3f054bef2b1b67da2b802e8ffcb54dbf11
refs/heads/master
2020-03-08T21:29:38.345226
2018-04-09T09:04:59
2018-04-09T09:04:59
128,407,588
0
0
null
null
null
null
UTF-8
C++
false
false
1,388
h
// MainFrm.h : interface of the CMainFrame class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_MAINFRM_H__DB9A5DBA_8607_4805_8C68_0FBC6492E238__INCLUDED_) #define AFX_MAINFRM_H__DB9A5DBA_8607_4805_8C68_0FBC6492E238__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMainFrame : public CFrameWnd { protected: // create from serialization only CMainFrame(); DECLARE_DYNCREATE(CMainFrame) // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMainFrame) virtual BOOL PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL // Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // control bar embedded members CStatusBar m_wndStatusBar; // CToolBar m_wndToolBar; // Generated message map functions protected: //{{AFX_MSG(CMainFrame) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MAINFRM_H__DB9A5DBA_8607_4805_8C68_0FBC6492E238__INCLUDED_)
[ "vybiralm81@gmail.com" ]
vybiralm81@gmail.com
73660165803284943ec1cb895c3f3d1ffd00e138
33124c022f61e3dbab0070cdb71cecc039ba1953
/real/qnorthflowinfodisplaywidget.cpp
c8ea5168590aed5fbe664fb658534811f2aee237
[]
no_license
wooeng/Hq
0676ce810a4ecd095e6e1455b9ead94639e019ae
162e1570be9ad6ffbe08d0f431cbef151f59ea92
refs/heads/master
2023-03-12T21:38:37.541587
2021-03-01T09:35:52
2021-03-01T09:35:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,964
cpp
#include "qnorthflowinfodisplaywidget.h" #include "ui_qnorthflowinfodisplaywidget.h" #include <QPainter> #include <QDebug> #include "data_structure/hqutils.h" NorthFlowCurveWidget::NorthFlowCurveWidget(QWidget *parent) : QWidget(parent) { mSH.setNamedColor("#f47920"); mSZ.setNamedColor("#4e72b8"); mTotal.setNamedColor("#45b97c"); mDataList.clear(); mMax = 1; mMin = 0; mPathWidth = 8; } void NorthFlowCurveWidget::setLineColor(const QColor &sh, const QColor &sz, const QColor &total) { mSH = sh; mSZ = sz; mTotal = total; update(); } void NorthFlowCurveWidget::setPathWidth(int width) { mPathWidth = width; update(); } void NorthFlowCurveWidget::setNorthRealInfo(const QList<NorthBoundData> &list, int max, int min) { mDataList = list; if(max > mMax) mMax = max; mMin = min; update(); } void NorthFlowCurveWidget::paintEvent(QPaintEvent *e) { //设定当前的区域的背景色 QPainter painters(this); painters.fillRect(this->rect(), Qt::transparent); //刻度值宽度高度的设定 int yTextWidth = painters.fontMetrics().width("10000"); int xTextHeight = painters.fontMetrics().height(); QRect draw_rect = this->rect().marginsAdded(QMargins(-yTextWidth, -yTextWidth, -yTextWidth, -yTextWidth)); //画图区域设定,曲线区域和图例区域比例为9:1 QRect curve_rect = draw_rect; // curve_rect.setWidth(curve_rect.width() - yTextWidth); // curve_rect.moveLeft(curve_rect.left() + yTextWidth); // int curve_rect_height = (int)(ceil(draw_rect.height() * 0.9)); // curve_rect.setHeight(curve_rect_height); // QRect symbol_rect = draw_rect; // symbol_rect.moveTopLeft(QPoint(draw_rect.x(), draw_rect.y() + curve_rect_height + xTextHeight + 10)); // symbol_rect.setHeight(draw_rect.height() - curve_rect_height - xTextHeight - 10); painters.save(); QPen pen = painters.pen(); pen.setColor(Qt::white); //开始画横坐标 double x_pitch = curve_rect.width() / 4.0; double y = curve_rect.bottom(); double x = curve_rect.left(); for(int i=0; i<5; i++) { QString text = ""; if(i < 3) { painters.drawText(QPointF(x+x_pitch*i, y + xTextHeight), QString("%1:30").arg(9+i)); } else { painters.drawText(QPointF(x+x_pitch*i, y + xTextHeight), QString("%1:00").arg(11+i)); } } painters.restore(); //开始Y方向的刻度 double val_per_pitch = (mMax - mMin) * 1.0 / 10; double y_pitch = curve_rect.height() * 1.0 / 10; for(int i=0; i<11; i++) { double left_x = curve_rect.left(); double left_y = curve_rect.bottom() - i * y_pitch; double val = mMin + i * val_per_pitch; //开始画坐标刻度,上下各5个,共11个刻度 painters.save(); pen.setColor(Qt::lightGray); pen.setStyle(Qt::DashLine); painters.setPen(pen); painters.drawLine(QPointF(left_x, left_y), QPointF(curve_rect.right(), left_y)); painters.restore(); if(i+1 % 2) { painters.save(); pen.setColor(Qt::white); painters.setPen(pen); //计算文本的举行大小 QRect text_rect(0, 0, yTextWidth, xTextHeight); text_rect.moveLeft(curve_rect.left() - yTextWidth); text_rect.moveBottom(left_y + 0.5 * xTextHeight); painters.drawText(text_rect, Qt::AlignRight | Qt::AlignVCenter, QString::number(val, 'f', 1)); painters.restore(); } // qDebug()<<"draw value:"<<mMax<<mMin<<val; } //开始画实时的曲线 QPolygonF sh, sz, total; QTime start_time(9, 30, 0); double x_px = curve_rect.width() * 1.0 / (4 * 3600); double y_px = curve_rect.height() * 1.0 / (mMax-mMin); for(int i=0; i<mDataList.size(); i++) { NorthBoundData data = mDataList[i]; // qDebug()<<"data time:"<<data.time.toString("hh:mm:ss")<<data.sh_flow<<data.sz_flow; //计算数据对应的X坐标 QTime cur = data.time.time(); int time_elapsed = start_time.secsTo(cur); if(time_elapsed < 0) continue; if(cur.hour() == 11 && cur.minute() > 30) continue; if(cur.hour() == 12 ) continue; if(cur.hour() == 15 && cur.minute() > 1) continue; if(cur.hour() > 12) time_elapsed -= (3600 + 1800); // form 11:30 - 13;00 double x = curve_rect.left() + time_elapsed * x_px; double sh_y = curve_rect.bottom() - (data.sh_flow - mMin) * y_px; double sz_y = curve_rect.bottom() - (data.sz_flow - mMin) * y_px; double total_y = curve_rect.bottom() - (data.total_flow - mMin) * y_px; sh.append(QPointF(x, sh_y)); sz.append(QPointF(x, sz_y)); total.append(QPointF(x, total_y)); } painters.save(); painters.setPen(QPen(mSH, mPathWidth)); painters.drawPolyline(sh); if(mDataList.size() > 0 && sh.size() > 0) { painters.drawText(sh.last() + QPointF(10, 0), QString::number(mDataList.last().sh_flow, 'f', 2)); } painters.setPen(QPen(mSZ, mPathWidth)); painters.drawPolyline(sz); if(mDataList.size() > 0 && sz.size() > 0) { painters.drawText(sz.last() + QPointF(10, 0), QString::number(mDataList.last().sz_flow, 'f', 2)); } painters.setPen(QPen(mTotal, mPathWidth)); painters.drawPolyline(total); if(mDataList.size() > 0 && total.size() > 0) { painters.drawText(total.last() + QPointF(10, 0), QString::number(mDataList.last().total_flow, 'f', 2)); } painters.restore(); } QNorthFlowInfoDisplayWidget::QNorthFlowInfoDisplayWidget(QWidget *parent) : QWidget(parent), ui(new Ui::QNorthFlowInfoDisplayWidget), mDisplayWidget(0) { ui->setupUi(this); mDisplayWidget = new NorthFlowCurveWidget(this); if(!ui->widget->layout()) { ui->widget->setLayout(new QHBoxLayout); } int text_height_mm = 4; int pixel_size = HqUtils::convertMM2Pixel(text_height_mm-1); qDebug()<<"text height:"<<text_height_mm<<" pixel size:"<<pixel_size; QString style = this->styleSheet(); style.append(QString("QLabel { font-family:Microsoft Yahei; font-size:%1px;}").arg(pixel_size)); this->setStyleSheet(style); ui->title_frame->setFixedHeight(pixel_size + 3); ui->widget->layout()->setMargin(0); ui->widget->layout()->addWidget(mDisplayWidget); int line_width = HqUtils::convertMM2Pixel(0.6); ui->sh->setLineWidth(0); ui->sz->setLineWidth(0); ui->north->setLineWidth(0); ui->sh->setFixedHeight(line_width); ui->sz->setFixedHeight(line_width); ui->north->setFixedHeight(line_width); mDisplayWidget->setPathWidth(line_width); ui->sh->setStyleSheet(QString("background-color:%1").arg(mDisplayWidget->mSH.name())); ui->sz->setStyleSheet(QString("background-color:%1").arg(mDisplayWidget->mSZ.name())); ui->north->setStyleSheet(QString("background-color:%1").arg(mDisplayWidget->mTotal.name())); mRealInfoThread = new QSinaNorthRealInfoThread; connect(mRealInfoThread, SIGNAL(signalUpdateNorthBoundList(QList<NorthBoundData>, int, int, QDate)), this, SLOT(setNorthRealInfo(QList<NorthBoundData>,int, int, QDate))); mRealInfoThread->start(); } void QNorthFlowInfoDisplayWidget::setDate(const QString &date) { ui->date->setText(date); } QNorthFlowInfoDisplayWidget::~QNorthFlowInfoDisplayWidget() { delete ui; } void QNorthFlowInfoDisplayWidget::setNorthRealInfo(const QList<NorthBoundData> &list, int max, int min, const QDate &date) { setDate(date.toString("MM-dd")); if(mDisplayWidget) mDisplayWidget->setNorthRealInfo(list, max, min); }
[ "bnufree@163.com" ]
bnufree@163.com
47d846418f683c4380732dc404bf6d1cf39c4eae
1483c385951fb2bc8e8f72059f92e863c4f3abe3
/Catkin_WS/src/velodyne/velodyne_pointcloud/src/conversions/convert.cc
2a0dc694c496d40a317c10c958fab5affdc2697b
[ "BSD-3-Clause" ]
permissive
MichiganRobotX/robotrepo
ce28eac23dd979a41d1056a8f5cfa12ab09e5e10
b6f965723263fee4a591e09a0261d5b30b39d1c0
refs/heads/master
2021-05-03T19:40:33.595383
2018-10-22T00:13:04
2018-10-22T00:13:04
120,418,971
1
4
null
2018-09-01T02:43:01
2018-02-06T07:39:21
C++
UTF-8
C++
false
false
2,694
cc
/* * Copyright (C) 2009, 2010 Austin Robot Technology, Jack O'Quin * Copyright (C) 2011 Jesse Vera * Copyright (C) 2012 Austin Robot Technology, Jack O'Quin * License: Modified BSD Software License Agreement * * $Id$ */ /** @file This class converts raw Velodyne 3D LIDAR packets to PointCloud2. */ #include "velodyne_pointcloud/convert.h" #include <pcl_conversions/pcl_conversions.h> namespace velodyne_pointcloud { /** @brief Constructor. */ Convert::Convert(ros::NodeHandle node, ros::NodeHandle private_nh): data_(new velodyne_rawdata::RawData()) { data_->setup(private_nh); // advertise output point cloud (before subscribing to input data) output_ = node.advertise<sensor_msgs::PointCloud2>("velodyne_points", 10); srv_ = boost::make_shared <dynamic_reconfigure::Server<velodyne_pointcloud:: CloudNodeConfig> > (private_nh); dynamic_reconfigure::Server<velodyne_pointcloud::CloudNodeConfig>:: CallbackType f; f = boost::bind (&Convert::callback, this, _1, _2); srv_->setCallback (f); // subscribe to VelodyneScan packets velodyne_scan_ = node.subscribe("velodyne_packets", 10, &Convert::processScan, (Convert *) this, ros::TransportHints().tcpNoDelay(true)); } void Convert::callback(velodyne_pointcloud::CloudNodeConfig &config, uint32_t level) { ROS_INFO("Reconfigure Request"); data_->setParameters(config.min_range, config.max_range, config.view_direction, config.view_width); } /** @brief Callback for raw scan messages. */ void Convert::processScan(const velodyne_msgs::VelodyneScan::ConstPtr &scanMsg) { if (output_.getNumSubscribers() == 0) // no one listening? return; // avoid much work // allocate a point cloud with same time and frame ID as raw data velodyne_rawdata::VPointCloud::Ptr outMsg(new velodyne_rawdata::VPointCloud()); // outMsg's header is a pcl::PCLHeader, convert it before stamp assignment outMsg->header.stamp = pcl_conversions::toPCL(scanMsg->header).stamp; outMsg->header.frame_id = scanMsg->header.frame_id; outMsg->height = 1; // process each packet provided by the driver for (size_t i = 0; i < scanMsg->packets.size(); ++i) { data_->unpack(scanMsg->packets[i], *outMsg); } // publish the accumulated cloud message ROS_DEBUG_STREAM("Publishing " << outMsg->height * outMsg->width << " Velodyne points, time: " << outMsg->header.stamp); output_.publish(outMsg); } } // namespace velodyne_pointcloud
[ "wamv@wamv.engin.umich.edu" ]
wamv@wamv.engin.umich.edu
b72771581a8a873be2b9b303b8d384f527469b81
d701816abe5b8baaf3c325323c572c7714fefd5e
/table/princess.cpp
73773bfc6c7e376f0ad3f06e1e48094064f61822
[ "MIT" ]
permissive
TheTSD/libsaki
eaa0597932df20943439e20e917806c4455508d7
7253c78bf93a38839e287304ce0856d5b9c01099
refs/heads/develop
2021-08-31T02:49:13.148650
2017-12-20T07:21:38
2017-12-20T07:21:38
110,526,926
1
0
null
2017-11-13T09:23:57
2017-11-13T09:23:57
null
UTF-8
C++
false
false
7,512
cpp
#include "princess.h" #include "../util/rand.h" #include "../util/misc.h" #include "../util/debug_cheat.h" namespace saki { Princess::Princess(const Table &table, util::Rand &rand, Mount &mount, const std::array<std::unique_ptr<Girl>, 4> &girls) : mTable(table) , mRand(rand) , mMount(mount) , mGirls(girls) { mHasImageIndics.fill(false); } std::array<Hand, 4> Princess::deal() { std::array<TileCount, 4> inits = nonMonkey(); return monkey(inits); } bool Princess::imagedAsDora(T34 t, Princess::Indic which) const { int i = static_cast<int>(which); return mHasImageIndics[i] && mImageIndics[i] % t; } bool Princess::mayHaveDora(T34 t) const { return imagedAsDora(t, Indic::DORA) || imagedAsDora(t, Indic::URADORA) || imagedAsDora(t, Indic::KANDORA) || imagedAsDora(t, Indic::KANURA); } bool Princess::hasImageIndic(Indic which) const { return mHasImageIndics[static_cast<int>(which)]; } T34 Princess::getImageIndic(Indic which) const { assert(hasImageIndic(which)); return mImageIndics[static_cast<int>(which)]; } const Table &Princess::getTable() const { return mTable; } std::array<TileCount, 4> Princess::nonMonkey() { std::array<TileCount, 4> res; #ifdef LIBSAKI_CHEAT_PRINCESS for (size_t pos = 0; pos < cheat::wall.size(); pos++) mMount.pin(Mount::WALL, pos, cheat::wall[pos]); for (size_t pos = 0; pos < cheat::dead.size(); pos++) mMount.pin(Mount::DEAD, pos, cheat::dead[pos]); for (int w = 0; w < 4; w++) for (const T37 &t : cheat::inits[w]) res[w].inc(mMount.initPopExact(t), 1); #else std::bitset<Girl::NUM_NM_SKILL> presence; using Id = Girl::Id; static const std::vector<Id> CHECK_ORDER1 { Id::SHIBUYA_TAKAMI, Id::USUZUMI_HATSUMI, Id::SHISHIHARA_SAWAYA, Id::IWATO_KASUMI }; for (Id id : CHECK_ORDER1) { Who who = mTable.findGirl(id); if (who.somebody()) mGirls[who.index()]->nonMonkey(mRand, res[who.index()], mMount, presence, *this); } doraMatters(); static const std::vector<Id> CHECK_ORDER2 { Id::OOHOSHI_AWAI, Id::MIYANAGA_TERU }; for (Id id : CHECK_ORDER2) { Who who = mTable.findGirl(id); if (who.somebody()) mGirls[who.index()]->nonMonkey(mRand, res[who.index()], mMount, presence, *this); } #endif return res; } std::array<Hand, 4> Princess::monkey(std::array<TileCount, 4> &inits) { std::array<Hand, 4> res; std::array<Exist, 4> exists; for (auto &g : mGirls) g->onMonkey(exists, *this); // checkInit() should never rely on a moutain remaining status // because hands are checked sequentially but not globally for (int w = 0; w < 4; w++) { for (int iter = 0; true; iter++) { Mount mount(mMount); TileCount init(inits[w]); // copy Exist exist(exists[w]); // copy mount.initFill(mRand, init, exist); Hand hand(init); auto pass = [w, &hand, this, &mount, iter](int checker) { return mGirls[checker]->checkInit(Who(w), hand, *this, iter); }; if (pass(0) && pass(1) && pass(2) && pass(3)) { mMount = mount; res[w] = hand; break; } } } return res; } void Princess::doraMatters() { using namespace tiles37; // NONE: the indicator will be scientifically choosen // ANY: the indicator will be choosen from B-space by a one-hot distro // WALL: same as ANY, and the indicated dora must remain 4 in A-space enum class Fix { NONE, ANY, WALL }; std::array<Fix, 4> fixes; fixes.fill(Fix::NONE); auto update = [&fixes](Indic which, Fix rhs) { Fix &lhs = fixes[int(which)]; // overwrite by priority lhs = std::max(lhs, rhs); }; // exluded by numeric value, regardless of red/black std::array<std::array<bool, 34>, 4> ex34ss; for (auto &ex34s : ex34ss) ex34s.fill(false); Who kuro = mTable.findGirl(Girl::Id::MATSUMI_KURO); Who awai = mTable.findGirl(Girl::Id::OOHOSHI_AWAI); if (awai.somebody()) { update(Indic::DORA, Fix::ANY); update(Indic::URADORA, Fix::ANY); update(Indic::KANDORA, Fix::ANY); update(Indic::KANURA, Fix::WALL); // prevent yakuhai to ensure Awai::checkInit() always return auto &ex34s = ex34ss[static_cast<int>(Indic::KANURA)]; ex34s[(1_y).id34()] = true; ex34s[(2_y).id34()] = true; ex34s[(3_y).id34()] = true; ex34s[T34(Suit::F, mTable.getSelfWind(awai)).indicator().id34()] = true; ex34s[T34(Suit::F, mTable.getRoundWind()).indicator().id34()] = true; // exclude akadoras to limit awai's point if (mTable.getRule().akadora != TileCount::AKADORA0) { ex34s[(4_m).id34()] = true; ex34s[(4_p).id34()] = true; ex34s[(4_s).id34()] = true; } } if (kuro.somebody()) { update(Indic::DORA, Fix::WALL); // prevent akadora from being pilfered by awai or someone // by exluding number-4 to be an indicator if (mTable.getRule().akadora != TileCount::AKADORA0) { // start from '1' since the normal dora lives or dies // together with akadoras for (int i = 1; i < 4; i++) { ex34ss[i][(4_m).id34()] = true; ex34ss[i][(4_p).id34()] = true; ex34ss[i][(4_s).id34()] = true; } } } for (int i = 0; i < 4; i++) { if (fixes[i] != Fix::NONE) { fixIndicator(Indic(i), ex34ss[i], fixes[i] == Fix::WALL); // make fixed doras always unique for redundant safety // (needed by at least awai) // use id34() instread of id37() to ensure uniqueness // note that a fixed indicator might equal to a non-fixed // scientific indicator. for (int j = i; j < 4; j++) ex34ss[j][mImageIndics[i].id34()] = true; } } } void Princess::fixIndicator(Indic which, const std::array<bool, 34> &exceptId34s, bool wall) { int i = static_cast<int>(which); mImageIndics[i] = pickIndicator(exceptId34s, wall); Mount::Exit exit = i % 2 == 0 ? Mount::DORA : Mount::URADORA; int pos = i / 2 == 0 ? 0 : 1; T37 indic(mImageIndics[i].id34()); if (mMount.remainA(indic) == 0) indic = indic.toAka5(); mMount.loadB(indic, 1); mImageIndics[static_cast<int>(which)] = indic; mHasImageIndics[static_cast<int>(which)] = true; for (T34 t : tiles34::ALL34) { // TODO de-magic the '100's and parametize them mMount.power(exit, pos, t, -100, false); mMount.power(exit, pos, t, t == indic ? 100 : -100, true); } } T34 Princess::pickIndicator(const std::array<bool, 34> &ex34s, bool wall) { // be careful with the 34/37 problem // equality is checked by id34, and indicator is choosen in 37-domain std::vector<T34> indicatable; for (T34 t : tiles34::ALL34) { if (!ex34s[t.id34()] && mMount.remainA(t) > 0 && (!wall || mMount.remainA(t.dora()) == 4)) { indicatable.push_back(t); } } assert(!indicatable.empty()); return indicatable[mRand.gen(indicatable.size())]; } } // namespace saki
[ "rolevax@gmail.com" ]
rolevax@gmail.com
22685d09d4a6838a3fe232e67c6c7ffcedc45e99
63b15515c81558e856ed47e2b30325d33274962e
/Matrix/tpzverysparsematrix.h
a63d1ba8e687346902a1be9999f0c19d6e9ece76
[]
no_license
diogocecilio/neopz-master
eb14d4b6087e9655763440934d67b419f781d1a0
7fb9346f00afa883ccf4d07e3ac0af466dfadce1
refs/heads/master
2022-04-04T21:44:17.897614
2019-10-25T20:34:47
2019-10-25T20:34:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,669
h
/** * @file * @brief Contains TPZVerySparseMatrix class which implements a matrix whose nonzero elements are stored in binary tree. */ #ifndef TPZVERYSPARSEMATRIX_H #define TPZVERYSPARSEMATRIX_H #include <iostream> #include <map> #include "pzmatrix.h" /** @ingroup matrix */ #define TPZVERYSPARSEMATRIX_ID 28291001; template <class TVar> class TPZFMatrix; template <class TVar> class TPZFYsmpMatrix; /** * @author Agnaldo Monteiro Farias <agnaldo@labmec.fec.unicamp.br> * @brief Implements a matrix whose nonzero elements are stored in binary tree. \ref matrix "Matrix" * @ingroup matrix */ template<class TVar> class TPZVerySparseMatrix: public TPZMatrix<TVar> { public: friend class TPZFYsmpMatrix<TVar>; TPZVerySparseMatrix(); TPZVerySparseMatrix(long rows, long cols) : TPZMatrix<TVar>(rows, cols) { } TPZVerySparseMatrix(long rows, long cols, TVar val) : TPZMatrix<TVar>(rows, cols) { } virtual ~TPZVerySparseMatrix(); TPZVerySparseMatrix(const TPZVerySparseMatrix<TVar> &copy) : TPZMatrix<TVar>(copy), fExtraSparseData(copy.fExtraSparseData) { } TPZVerySparseMatrix(const TPZFMatrix<TVar> &cp); /** @brief Simetrizes copies the data of the matrix to make its data simetric */ void Simetrize(); /** @brief Put values checking bounds */ int PutVal(const long row, const long col, const TVar &val); /** @brief Get values checking bounds */ virtual const TVar &GetVal(const long row, const long col) const; /** * @brief The operators check on the bounds if the DEBUG variable is defined * @param row Row number. * @param col Column number. */ virtual TVar &s(const long row, const long col) { #ifdef PZDEBUG if(row >= this->Rows() || row<0 || col >= this->Cols() || col<0) { this->Error("TPZFMatrix::operator() "," Index out of bounds"); DebugStop(); } #endif return fExtraSparseData[std::pair<long, long>(row, col)]; } CLONEDEF(TPZVerySparseMatrix) /** * @brief It computes z = beta * y + alpha * opt(this)*x but z and x can not overlap in memory. * @param x Is x on the above operation * @param y Is y on the above operation * @param z Is z on the above operation * @param alpha Is alpha on the above operation * @param beta Is beta on the above operation * @param opt Indicates if is Transpose or not */ virtual void MultAdd(const TPZFMatrix<TVar> & x, const TPZFMatrix<TVar> & y, TPZFMatrix<TVar> & z, const TVar alpha = 1, const TVar beta = 0, const int opt = 0) const; /** @brief It makes *T the transpose of current matrix. */ virtual void Transpose(TPZVerySparseMatrix<TVar>* T) const; virtual void Transpose(TPZMatrix<TVar>*const T) const { TPZMatrix<TVar>::Transpose(T); } /** @brief Saveable methods */ int ClassId() const { return TPZVERYSPARSEMATRIX_ID; } virtual void Write(TPZStream &buf, int withclassid); virtual void Read(TPZStream &buf, void *context); typename std::map <std::pair<long, long>, TVar>::const_iterator MapBegin() const { return fExtraSparseData.begin(); } typename std::map <std::pair<long, long>, TVar>::const_iterator MapEnd() const { return fExtraSparseData.end(); } private: /** @brief Auxiliary functions only reading and writing a map as the third paremeter */ void WriteMap(TPZStream &buf, int withclassid, std::map<std::pair<long, long>, TVar> & TheMap); void ReadMap(TPZStream &buf, void *context, std::map<std::pair<long, long>, TVar> & TheMap); protected: /** @brief Save elements different from zero, of Sparse matrix */ std::map<std::pair<long, long>, TVar> fExtraSparseData; }; //#include "pzfmatrix.h" //#include "pzysmp.h" #endif
[ "cecilio.diogo@gmail.com" ]
cecilio.diogo@gmail.com
24340f10ea8edb4b68a5be4e0c92a67ef662586b
3fe692c3ebf0b16c0a6ae9d8633799abc93bd3bb
/Practices/Luogu/P2387.cpp
2d7dbf7385bfa987af1eaa75e2497accf035f66d
[]
no_license
kaloronahuang/KaloronaCodebase
f9d297461446e752bdab09ede36584aacd0b3aeb
4fa071d720e06100f9b577e87a435765ea89f838
refs/heads/master
2023-06-01T04:24:11.403154
2023-05-23T00:38:07
2023-05-23T00:38:07
155,797,801
14
1
null
null
null
null
UTF-8
C++
false
false
3,030
cpp
// P2387.cpp #include <bits/stdc++.h> #define lson ch[p][0] #define rson ch[p][1] using namespace std; const int MAX_N = 2e5 + 200; struct edge { int src, dst, ai, bi; bool operator<(const edge &edg) const { return ai < edg.ai || (ai == edg.ai && bi < edg.bi); } } edges[MAX_N]; int n, m, ch[MAX_N][2], fa[MAX_N], idx[MAX_N], val[MAX_N], tag[MAX_N]; inline bool isRoot(int p) { return ch[fa[p]][0] != p && ch[fa[p]][1] != p; } inline int check(int p) { return ch[fa[p]][1] == p; } inline void pushup(int p) { idx[p] = p; if (lson && val[idx[lson]] > val[idx[p]]) idx[p] = idx[lson]; if (rson && val[idx[rson]] > val[idx[p]]) idx[p] = idx[rson]; } inline void pushdown(int p) { if (tag[p]) { tag[p] = 0; if (lson) tag[lson] ^= 1, swap(ch[lson][0], ch[lson][1]); if (rson) tag[rson] ^= 1, swap(ch[rson][0], ch[rson][1]); } } inline void rotate(int p) { int y = fa[p], z = fa[y], dir = check(p), w = ch[p][dir ^ 1]; fa[p] = z; if (!isRoot(y)) ch[z][check(y)] = p; ch[y][dir] = w, fa[w] = y; ch[p][dir ^ 1] = y, fa[y] = p; pushup(y), pushup(p), pushup(z); } inline void jump(int p) { if (!isRoot(p)) jump(fa[p]); pushdown(p); } inline void splay(int p) { jump(p); for (int fat = fa[p]; fat = fa[p], !isRoot(p); rotate(p)) if (!isRoot(fat)) rotate(check(fat) == check(p) ? fat : p); } inline void access(int p) { for (int fat = 0; p != 0; fat = p, p = fa[p]) splay(p), ch[p][1] = fat, pushup(p); } inline void makeRoot(int p) { access(p), splay(p); swap(lson, rson), tag[p] ^= 1; } inline int find(int p) { access(p), splay(p); while (lson) p = lson; splay(p); return p; } inline void link(int x, int y) { makeRoot(x); fa[x] = y; } inline void split(int x, int y) { makeRoot(x); access(y), splay(y); } inline bool check(int x, int y) { makeRoot(x); return find(y) == x; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++) scanf("%d%d%d%d", &edges[i].src, &edges[i].dst, &edges[i].ai, &edges[i].bi); int ans = 2e9; sort(edges + 1, edges + 1 + m); for (int i = 1; i <= m; i++) { int id = i + n; val[id] = edges[i].bi; if (edges[i].src == edges[i].dst) continue; if (!check(edges[i].src, edges[i].dst)) link(edges[i].src, id), link(id, edges[i].dst); else { split(edges[i].src, edges[i].dst); int now = idx[edges[i].dst], maxb = val[now]; if (maxb <= edges[i].bi) continue; splay(now), fa[ch[now][0]] = fa[ch[now][1]] = 0; link(edges[i].src, id), link(id, edges[i].dst); } if (check(1, n)) split(1, n), ans = min(ans, edges[i].ai + val[idx[n]]); } if (ans < 2e9) printf("%d", ans); else puts("-1"); return 0; } // P2387.cpp
[ "kaloronahuang@gmail.com" ]
kaloronahuang@gmail.com
b4fd43f15c141178da358ba6ddb657a792523445
a52c3443bdddc0a6f1bcd7b09a6395e1c9cb35f0
/operacoesaritmetica/main.cpp
6d58df9e447d81ce04ea36508af92ee1a2c803aa
[]
no_license
PedroHeber07/estudosc-
cef63fba2c49e343f40ac324980ab2b55226ed52
7d04bf5e3ce99e8352984a587467d769aae4c80c
refs/heads/master
2022-12-18T18:54:40.761510
2020-09-13T15:15:57
2020-09-13T15:15:57
295,176,655
0
0
null
null
null
null
UTF-8
C++
false
false
490
cpp
#include <iostream> using namespace std; int main() { int x,y; x = 3; y = 9; cout << "O valor de x e y e: " << x << ", " << y << endl; cout << "A soma entre x e y e: "<< x + y << endl; cout << "A subtracao entre x e y e: " << x - y << endl; cout << "A divisao entre x e y e: " << y / x << endl; cout << "A multiplicacao entre x e y e: " << x * y << endl; double d = y / (x + 1.0); cout << "A divisao entre x e y e: " << d << endl; system("pause"); return 0; }
[ "pedrohebercunha34@gmail.com" ]
pedrohebercunha34@gmail.com
2608f6c2aed438c50b575d3b0642be895325eda3
e641bd95bff4a447e25235c265a58df8e7e57c84
/components/autofill_assistant/browser/script_executor.h
53c0bf05f6ff45079f2c106818d95cb48f602a68
[ "BSD-3-Clause" ]
permissive
zaourzag/chromium
e50cb6553b4f30e42f452e666885d511f53604da
2370de33e232b282bd45faa084e5a8660cb396ed
refs/heads/master
2023-01-02T08:48:14.707555
2020-11-13T13:47:30
2020-11-13T13:47:30
312,600,463
0
0
BSD-3-Clause
2022-12-23T17:01:30
2020-11-13T14:39:10
null
UTF-8
C++
false
false
23,071
h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_SCRIPT_EXECUTOR_H_ #define COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_SCRIPT_EXECUTOR_H_ #include <deque> #include <map> #include <memory> #include <ostream> #include <set> #include <string> #include <vector> #include "base/callback_forward.h" #include "base/memory/weak_ptr.h" #include "components/autofill_assistant/browser/actions/action.h" #include "components/autofill_assistant/browser/actions/action_delegate.h" #include "components/autofill_assistant/browser/client_settings.h" #include "components/autofill_assistant/browser/details.h" #include "components/autofill_assistant/browser/info_box.h" #include "components/autofill_assistant/browser/retry_timer.h" #include "components/autofill_assistant/browser/script.h" #include "components/autofill_assistant/browser/script_executor_delegate.h" #include "components/autofill_assistant/browser/service.pb.h" #include "components/autofill_assistant/browser/top_padding.h" #include "components/autofill_assistant/browser/web/element_finder.h" namespace autofill_assistant { class UserModel; class WaitForDocumentOperation; // Class to execute an assistant script. class ScriptExecutor : public ActionDelegate, public ScriptExecutorDelegate::NavigationListener, public ScriptExecutorDelegate::Listener { public: // Listens to events on ScriptExecutor. // TODO(b/806868): Make global_payload a part of callback instead of the // listener. class Listener { public: virtual ~Listener() = default; // Called when new server payloads are available. // // TODO(b/806868): Stop reporting the script payload once the server has // transitioned to global payloads. virtual void OnServerPayloadChanged(const std::string& global_payload, const std::string& script_payload) = 0; // Called when an update list of scripts is available. virtual void OnScriptListChanged( std::vector<std::unique_ptr<Script>> scripts) = 0; }; // |delegate|, |listener|, |script_state| and |ordered_interrupts| should // outlive this object and should not be nullptr. ScriptExecutor(const std::string& script_path, std::unique_ptr<TriggerContext> additional_context, const std::string& global_payload, const std::string& script_payload, ScriptExecutor::Listener* listener, std::map<std::string, ScriptStatusProto>* scripts_state, const std::vector<std::unique_ptr<Script>>* ordered_interrupts, ScriptExecutorDelegate* delegate); ~ScriptExecutor() override; // What should happen after the script has run. enum AtEnd { // Continue normally. CONTINUE = 0, // Shut down Autofill Assistant. SHUTDOWN, // Shut down Autofill Assistant after a delay. SHUTDOWN_GRACEFULLY, // Shut down Autofill Assistant and CCT. CLOSE_CUSTOM_TAB, }; // Contains the result of the Run operation. struct Result { bool success = false; AtEnd at_end = AtEnd::CONTINUE; std::unique_ptr<ElementAreaProto> touchable_element_area; Result(); ~Result(); friend std::ostream& operator<<(std::ostream& out, const Result& result); }; using RunScriptCallback = base::OnceCallback<void(const Result&)>; void Run(const UserData* user_data, RunScriptCallback callback); const UserData* GetUserData() const override; UserModel* GetUserModel() override; // Override ScriptExecutorDelegate::NavigationListener void OnNavigationStateChanged() override; // Override ScriptExecutorDelegate::Listener void OnPause(const std::string& message, const std::string& button_label) override; // Override ActionDelegate: void RunElementChecks(BatchElementChecker* checker) override; void ShortWaitForElement( const Selector& selector, base::OnceCallback<void(const ClientStatus&, base::TimeDelta)> callback) override; void WaitForDom( base::TimeDelta max_wait_time, bool allow_interrupt, base::RepeatingCallback< void(BatchElementChecker*, base::OnceCallback<void(const ClientStatus&)>)> check_elements, base::OnceCallback<void(const ClientStatus&, base::TimeDelta)> callback) override; void SetStatusMessage(const std::string& message) override; std::string GetStatusMessage() override; void SetBubbleMessage(const std::string& message) override; std::string GetBubbleMessage() override; void FindElement(const Selector& selector, ElementFinder::Callback callback) const override; void FindAllElements(const Selector& selector, ElementFinder::Callback callback) const override; void ScrollIntoView( const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) override; void WaitUntilElementIsStable( int max_rounds, base::TimeDelta check_interval, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) override; void CheckOnTop( const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) override; void ClickOrTapElement( ClickType click_type, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) override; void CollectUserData( CollectUserDataOptions* collect_user_data_options) override; void SetLastSuccessfulUserDataOptions(std::unique_ptr<CollectUserDataOptions> collect_user_data_options) override; const CollectUserDataOptions* GetLastSuccessfulUserDataOptions() const override; void WriteUserData( base::OnceCallback<void(UserData*, UserData::FieldChange*)>) override; void GetFullCard(const autofill::CreditCard* credit_card, GetFullCardCallback callback) override; void Prompt(std::unique_ptr<std::vector<UserAction>> user_actions, bool disable_force_expand_sheet, base::OnceCallback<void()> end_on_navigation_callback, bool browse_mode, bool browse_mode_invisible) override; void CleanUpAfterPrompt() override; void SetBrowseDomainsAllowlist(std::vector<std::string> domains) override; void FillAddressForm( const autofill::AutofillProfile* profile, const Selector& selector, base::OnceCallback<void(const ClientStatus&)> callback) override; void FillCardForm( std::unique_ptr<autofill::CreditCard> card, const base::string16& cvc, const Selector& selector, base::OnceCallback<void(const ClientStatus&)> callback) override; void RetrieveElementFormAndFieldData( const Selector& selector, base::OnceCallback<void(const ClientStatus&, const autofill::FormData& form_data, const autofill::FormFieldData& field_data)> callback) override; void SelectOption( const std::string& value, DropdownSelectStrategy select_strategy, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) override; void HighlightElement( const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) override; void ScrollToElementPosition( const Selector& selector, const TopPadding& top_padding, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) override; void SetTouchableElementArea( const ElementAreaProto& touchable_element_area) override; void GetFieldValue( const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&, const std::string&)> callback) override; void GetStringAttribute( const std::vector<std::string>& attributes, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&, const std::string&)> callback) override; void SetValueAttribute( const std::string& value, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) override; void SetAttribute( const std::vector<std::string>& attributes, const std::string& value, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) override; void SelectFieldValue( const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) override; void FocusField( const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) override; void SendKeyboardInput( const std::vector<UChar32>& codepoints, int key_press_delay_in_millisecond, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) override; void GetOuterHtml( const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&, const std::string&)> callback) override; void GetOuterHtmls(const ElementFinder::Result& elements, base::OnceCallback<void(const ClientStatus&, const std::vector<std::string>&)> callback) override; void GetElementTag( const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&, const std::string&)> callback) override; void ExpectNavigation() override; bool ExpectedNavigationHasStarted() override; bool WaitForNavigation(base::OnceCallback<void(bool)> callback) override; void GetDocumentReadyState( const ElementFinder::Result& optional_frame_element, base::OnceCallback<void(const ClientStatus&, DocumentReadyState)> callback) override; void WaitForDocumentReadyState( base::TimeDelta max_wait_time, DocumentReadyState min_ready_state, const ElementFinder::Result& optional_frame_element, base::OnceCallback<void(const ClientStatus&, DocumentReadyState, base::TimeDelta)> callback) override; void WaitUntilDocumentIsInReadyState( base::TimeDelta max_wait_time, DocumentReadyState min_ready_state, const ElementFinder::Result& optional_frame_element, base::OnceCallback<void(const ClientStatus&)> callback) override; void LoadURL(const GURL& url) override; void Shutdown() override; void Close() override; autofill::PersonalDataManager* GetPersonalDataManager() override; WebsiteLoginManager* GetWebsiteLoginManager() override; content::WebContents* GetWebContents() override; std::string GetEmailAddressForAccessTokenAccount() override; std::string GetLocale() override; void SetDetails(std::unique_ptr<Details> details) override; void ClearInfoBox() override; void SetInfoBox(const InfoBox& info_box) override; void SetProgress(int progress) override; bool SetProgressActiveStepIdentifier( const std::string& active_step_identifier) override; void SetProgressActiveStep(int active_step) override; void SetProgressVisible(bool visible) override; void SetProgressBarErrorState(bool error) override; void SetStepProgressBarConfiguration( const ShowProgressBarProto::StepProgressBarConfiguration& configuration) override; void SetViewportMode(ViewportMode mode) override; ViewportMode GetViewportMode() override; void SetPeekMode(ConfigureBottomSheetProto::PeekMode peek_mode) override; ConfigureBottomSheetProto::PeekMode GetPeekMode() override; void ExpandBottomSheet() override; void CollapseBottomSheet() override; void WaitForWindowHeightChange( base::OnceCallback<void(const ClientStatus&)> callback) override; const ClientSettings& GetSettings() const override; bool SetForm( std::unique_ptr<FormProto> form, base::RepeatingCallback<void(const FormProto::Result*)> changed_callback, base::OnceCallback<void(const ClientStatus&)> cancel_callback) override; void RequireUI() override; void SetGenericUi( std::unique_ptr<GenericUserInterfaceProto> generic_ui, base::OnceCallback<void(const ClientStatus&)> end_action_callback, base::OnceCallback<void(const ClientStatus&)> view_inflation_finished_callback) override; void ClearGenericUi() override; void SetOverlayBehavior( ConfigureUiStateProto::OverlayBehavior overlay_behavior) override; base::WeakPtr<ActionDelegate> GetWeakPtr() const override; private: // Helper for WaitForElementVisible that keeps track of the state required to // run interrupts while waiting for a specific element. class WaitForDomOperation : public ScriptExecutor::Listener, ScriptExecutorDelegate::NavigationListener { public: // Let the caller know about either the result of looking for the element or // of an abnormal result from an interrupt. // // If the given result is non-null, it should be forwarded as the result of // the main script. using Callback = base::OnceCallback<void(const ClientStatus&, const ScriptExecutor::Result*, base::TimeDelta)>; // |main_script_| must not be null and outlive this instance. WaitForDomOperation( ScriptExecutor* main_script, ScriptExecutorDelegate* delegate, base::TimeDelta max_wait_time, bool allow_interrupt, base::RepeatingCallback< void(BatchElementChecker*, base::OnceCallback<void(const ClientStatus&)>)> check_elements, WaitForDomOperation::Callback callback); ~WaitForDomOperation() override; void Run(); void Terminate(); private: void Start(); void Pause(); void Continue(); // Implements ScriptExecutorDelegate::NavigationListener void OnNavigationStateChanged() override; // Implements ScriptExecutor::Listener void OnServerPayloadChanged(const std::string& global_payload, const std::string& script_payload) override; void OnScriptListChanged( std::vector<std::unique_ptr<Script>> scripts) override; void RunChecks( base::OnceCallback<void(const ClientStatus&)> report_attempt_result); void OnPreconditionCheckDone(const std::string& interrupt_path, bool precondition_match); void OnElementCheckDone(const ClientStatus&); void OnAllChecksDone( base::OnceCallback<void(const ClientStatus&)> report_attempt_result); void RunInterrupt(const std::string& path); void OnInterruptDone(const ScriptExecutor::Result& result); void RunCallback(const ClientStatus& element_status); void RunCallbackWithResult(const ClientStatus& element_status, const ScriptExecutor::Result* result); // Saves the current state and sets save_pre_interrupt_state_. void SavePreInterruptState(); // Restores the UI states as found by SavePreInterruptState. void RestoreStatusMessage(); // if save_pre_interrupt_state_ is set, attempt to scroll the page back to // the original area. void RestorePreInterruptScroll(); ScriptExecutor* main_script_; ScriptExecutorDelegate* delegate_; const base::TimeDelta max_wait_time_; const bool allow_interrupt_; base::RepeatingCallback<void(BatchElementChecker*, base::OnceCallback<void(const ClientStatus&)>)> check_elements_; WaitForDomOperation::Callback callback_; std::unique_ptr<BatchElementChecker> batch_element_checker_; // Path of interrupts from |ordered_interrupts_| that have been found // runnable. std::set<std::string> runnable_interrupts_; ClientStatus element_check_result_; // An empty vector of interrupts that can be passed to interrupt_executor_ // and outlives it. Interrupts must not run interrupts. const std::vector<std::unique_ptr<Script>> no_interrupts_; Stopwatch wait_time_stopwatch_; Stopwatch period_stopwatch_; base::TimeDelta wait_time_total_; // The interrupt that's currently running. std::unique_ptr<ScriptExecutor> interrupt_executor_; // If true, pre-interrupt state was saved already. This happens just before // the first interrupt. bool saved_pre_interrupt_state_ = false; // The status message that was displayed when the interrupt started. std::string pre_interrupt_status_; // Paths of the interrupts that were just run. These interrupts are // prevented from firing for one round. std::set<std::string> ran_interrupts_; RetryTimer retry_timer_; base::WeakPtrFactory<WaitForDomOperation> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(WaitForDomOperation); }; void OnGetActions(base::TimeTicks start_time, int http_status, const std::string& response); bool ProcessNextActionResponse(const std::string& response); void ReportPayloadsToListener(); void ReportScriptsUpdateToListener( std::vector<std::unique_ptr<Script>> scripts); void RunCallback(bool success); void RunCallbackWithResult(const Result& result); void ProcessNextAction(); void ProcessAction(Action* action); void GetNextActions(); void OnProcessedAction(base::TimeTicks start_time, std::unique_ptr<ProcessedActionProto> action); void CheckElementMatches( const Selector& selector, BatchElementChecker* checker, base::OnceCallback<void(const ClientStatus&)> callback); void CheckElementMatchesCallback( base::OnceCallback<void(const ClientStatus&)> callback, const ClientStatus& status, const ElementFinder::Result& ignored_element); void OnShortWaitForElement( base::OnceCallback<void(const ClientStatus&, base::TimeDelta)> callback, const ClientStatus& element_status, const Result* interrupt_result, base::TimeDelta wait_time); void OnWaitForElementVisibleWithInterrupts( base::OnceCallback<void(const ClientStatus&, base::TimeDelta)> callback, const ClientStatus& element_status, const Result* interrupt_result, base::TimeDelta wait_time); void OnGetUserData( base::OnceCallback<void(UserData*, const UserModel*)> callback, UserData* user_data, const UserModel* user_model); void OnAdditionalActionTriggered( base::OnceCallback<void(int, UserData*, const UserModel*)> callback, int index, UserData* user_data, const UserModel* user_model); void OnTermsAndConditionsLinkClicked( base::OnceCallback<void(int, UserData*, const UserModel*)> callback, int link, UserData* user_data, const UserModel* user_model); void OnGetFullCard(GetFullCardCallback callback, std::unique_ptr<autofill::CreditCard> card, const base::string16& cvc); void OnChosen(UserAction::Callback callback, std::unique_ptr<TriggerContext> context); void OnWaitForDocumentReadyState( base::OnceCallback<void(const ClientStatus&)> callback, const ClientStatus& status, DocumentReadyState ready_state, base::TimeDelta wait_time); void OnResume(); // Actions that can manipulate the UserActions should be interrupted, such // that they do not overwrite the paused state. bool ShouldInterruptOnPause(const ActionProto& proto); const std::string script_path_; std::unique_ptr<TriggerContext> additional_context_; std::string last_global_payload_; const std::string initial_script_payload_; std::string last_script_payload_; ScriptExecutor::Listener* const listener_; ScriptExecutorDelegate* const delegate_; // Set of interrupts that might run during wait for dom or prompt action with // allow_interrupt. Sorted by priority; an interrupt that appears on the // vector first should run first. Note that the content of this vector can // change while the script is running, as a result of OnScriptListChanged // being called. const std::vector<std::unique_ptr<Script>>* const ordered_interrupts_; std::map<std::string, ScriptStatusProto>* const scripts_state_; RunScriptCallback callback_; std::vector<std::unique_ptr<Action>> actions_; std::vector<ProcessedActionProto> processed_actions_; AtEnd at_end_ = CONTINUE; bool should_stop_script_ = false; bool should_clean_contextual_ui_on_finish_ = false; ActionProto::ActionInfoCase previous_action_type_ = ActionProto::ACTION_INFO_NOT_SET; Selector last_focused_element_selector_; TopPadding last_focused_element_top_padding_; std::unique_ptr<ElementAreaProto> touchable_element_area_; // Steps towards the requirements for calling |on_expected_navigation_done_| // to be fulfilled. enum class ExpectedNavigationStep { // No navigation is expected. UNEXPECTED = 0, // Navigation start is expected. EXPECTED, // Navigation has started, end is expected. STARTED, // Expected navigation has ended. DONE }; ExpectedNavigationStep expected_navigation_step_ = ExpectedNavigationStep::UNEXPECTED; // Callback called the next time |expected_navigation_step_| becomes DONE. base::OnceCallback<void(bool)> on_expected_navigation_done_; // Data only relevant to the currently running action. It is cleared before an // action is run. struct CurrentActionData { CurrentActionData(); ~CurrentActionData(); CurrentActionData& operator=(CurrentActionData&& other); // Navigation information relevant to the current action. NavigationInfoProto navigation_info; std::unique_ptr<WaitForDomOperation> wait_for_dom; std::unique_ptr<WaitForDocumentOperation> wait_for_document; // Set to true when a direct action was used to trigger a UserAction within // a prompt. This is reported to the backend. bool direct_action = false; // This callback is set when a navigation event should terminate an ongoing // prompt action. Only a prompt action will set a valid callback here. base::OnceCallback<void()> end_prompt_on_navigation_callback; }; CurrentActionData current_action_data_; base::Optional<size_t> current_action_index_; const UserData* user_data_ = nullptr; bool is_paused_ = false; std::string last_status_message_; base::TimeTicks batch_start_time_; RoundtripTimingStats roundtrip_timing_stats_; base::WeakPtrFactory<ScriptExecutor> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ScriptExecutor); }; } // namespace autofill_assistant #endif // COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_SCRIPT_EXECUTOR_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f021930344e97945e5957b0e03bd10fe532e5b0c
a424de85e049620131b06cec8cce1af46dd40dc7
/onnxruntime/core/providers/rocm/rocm_profiler.cc
cb808c364ee0b19967fbd80da69b25deed2bd54a
[ "MIT" ]
permissive
nietras/onnxruntime
2e14d9337b16b6cf0db6ff183f43b729954e1ed2
6b148e15e143a2143abf6687ef71dd8578c3e912
refs/heads/master
2022-09-22T17:23:58.996968
2022-08-30T23:47:36
2022-08-30T23:47:36
191,154,184
0
0
MIT
2020-02-03T11:37:58
2019-06-10T11:20:14
C++
UTF-8
C++
false
false
9,013
cc
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #if defined(USE_ROCM) && defined(ENABLE_ROCM_PROFILING) #include <chrono> #include <time.h> #include "rocm_profiler.h" #include "RoctracerLogger.h" #include "core/common/profiler_common.h" #define BSIZE 4096 typedef uint64_t timestamp_t; static timestamp_t timespec_to_ns(const timespec& time) { return ((timestamp_t)time.tv_sec * 1000000000) + time.tv_nsec; } namespace onnxruntime { namespace profiling { RocmProfiler::RocmProfiler() : d(&RoctracerLogger::singleton()) { } RocmProfiler::~RocmProfiler() { } bool RocmProfiler::StartProfiling() { d->clearLogs(); d->startLogging(); return true; } void RocmProfiler::EndProfiling(TimePoint start_time, Events& events) { d->stopLogging(); std::map<uint64_t, std::vector<EventRecord>> event_map; std::map<uint64_t, kernelRow*> kernelLaunches; // correlation id -> kernel info std::map<uint64_t, copyRow*> copyLaunches; // correlation id -> copy info // Generate EventRecords int64_t profiling_start = std::chrono::duration_cast<std::chrono::nanoseconds>(start_time.time_since_epoch()).count(); // Wrong clock again - all the cool kids are doing it timespec t0, t1, t00; clock_gettime(CLOCK_REALTIME, &t0); clock_gettime(CLOCK_MONOTONIC, &t1); clock_gettime(CLOCK_REALTIME, &t00); const uint64_t toffset = (timespec_to_ns(t0) >> 1) + (timespec_to_ns(t00) >> 1) - timespec_to_ns(t1); profiling_start = profiling_start - toffset; char buff[BSIZE]; for (auto &item : d->rows_) { std::initializer_list<std::pair<std::string, std::string>> args = {{"op_name", ""}}; addEventRecord(item, profiling_start, args, event_map); } for (auto &item : d->mallocRows_) { snprintf(buff, BSIZE, "%p", item.ptr); const std::string arg_ptr{buff}; std::initializer_list<std::pair<std::string, std::string>> args = {{"op_name", ""}, {"ptr", arg_ptr}, {"size", std::to_string(item.size)} }; addEventRecord(item, profiling_start, args, event_map); } for (auto &item : d->copyRows_) { snprintf(buff, BSIZE, "%p", item.stream); const std::string arg_stream{buff}; snprintf(buff, BSIZE, "%p", item.src); const std::string arg_src{buff}; snprintf(buff, BSIZE, "%p", item.dst); const std::string arg_dst{buff}; std::initializer_list<std::pair<std::string, std::string>> args = {{"op_name", ""}, {"stream", arg_stream}, {"src", arg_src}, {"dst", arg_dst}, {"size", std::to_string(item.size)}, {"kind", std::to_string(item.kind)}, }; addEventRecord(item, profiling_start, args, event_map); copyLaunches[item.id] = &item; } for (auto &item : d->kernelRows_) { snprintf(buff, BSIZE, "%p", item.stream); const std::string arg_stream{buff}; if (item.functionAddr) snprintf(buff, BSIZE, "%s", demangle(hipKernelNameRefByPtr(item.functionAddr, item.stream)).c_str()); else if (item.function) snprintf(buff, BSIZE, "%s", demangle(hipKernelNameRef(item.function)).c_str()); else snprintf(buff, BSIZE, " "); const std::string arg_kernel{buff}; std::initializer_list<std::pair<std::string, std::string>> args = {{"op_name", ""}, {"stream", arg_stream}, {"kernel", arg_kernel}, {"grid_x", std::to_string(item.gridX)}, {"grid_y", std::to_string(item.gridY)}, {"grid_z", std::to_string(item.gridZ)}, {"block_x", std::to_string(item.workgroupX)}, {"block_y", std::to_string(item.workgroupY)}, {"block_z", std::to_string(item.workgroupZ)}, }; addEventRecord(item, profiling_start, args, event_map); kernelLaunches[item.id] = &item; } // Async Ops - e.g. "Kernel" for (auto& buffer : *d->gpuTraceBuffers_) { const roctracer_record_t* record = (const roctracer_record_t*)(buffer.data_); const roctracer_record_t* end_record = (const roctracer_record_t*)(buffer.data_ + buffer.validSize_); while (record < end_record) { std::unordered_map<std::string, std::string> args; std::string name = roctracer_op_string(record->domain, record->op, record->kind); // Add kernel args if we have them auto kit = kernelLaunches.find(record->correlation_id); if (kit != kernelLaunches.end()) { auto &item = *(*kit).second; snprintf(buff, BSIZE, "%p", item.stream); args["stream"] = std::string(buff); args["grid_x"] = std::to_string(item.gridX); args["grid_y"] = std::to_string(item.gridY); args["grid_z"] = std::to_string(item.gridZ); args["block_x"] = std::to_string(item.workgroupX); args["block_y"] = std::to_string(item.workgroupY); args["block_z"] = std::to_string(item.workgroupZ); if (item.functionAddr != nullptr) { name = demangle(hipKernelNameRefByPtr(item.functionAddr, item.stream)).c_str(); } else if (item.function != nullptr) { name = demangle(hipKernelNameRef(item.function)).c_str(); } } // Add copy args if we have them auto cit = copyLaunches.find(record->correlation_id); if (cit != copyLaunches.end()) { auto &item = *(*cit).second; snprintf(buff, BSIZE, "%p", item.stream); args["stream"] = std::string(buff); snprintf(buff, BSIZE, "%p", item.src); args["dst"] = std::string(buff); snprintf(buff, BSIZE, "%p", item.dst); args["src"] = std::string(buff); args["size"] = std::to_string(item.size); args["kind"] = std::to_string(item.kind); } EventRecord event{ onnxruntime::profiling::KERNEL_EVENT, static_cast<int>(record->device_id), static_cast<int>(record->queue_id), name, static_cast<int64_t>((record->begin_ns - profiling_start) / 1000), static_cast<int64_t>((record->end_ns - record->begin_ns) / 1000), std::move(args)}; // FIXME: deal with missing ext correlation auto extId = d->externalCorrelations_[RoctracerLogger::CorrelationDomain::Default][record->correlation_id]; if (event_map.find(extId) == event_map.end()) { event_map.insert({extId, {event}}); } else { event_map[extId].push_back(std::move(event)); } roctracer_next_record(record, &record); } } // General auto insert_iter = events.begin(); for (auto& map_iter : event_map) { auto ts = static_cast<long long>(map_iter.first); while (insert_iter != events.end() && insert_iter->ts < ts) { insert_iter++; } if (insert_iter != events.end() && insert_iter->ts == ts) { for (auto& evt_iter : map_iter.second) { evt_iter.args["op_name"] = insert_iter->args["op_name"]; } insert_iter = events.insert(insert_iter+1, map_iter.second.begin(), map_iter.second.end()); } else { insert_iter = events.insert(insert_iter, map_iter.second.begin(), map_iter.second.end()); } while (insert_iter != events.end() && insert_iter->cat == EventCategory::KERNEL_EVENT) { insert_iter++; } } } void RocmProfiler::Start(uint64_t id) { d->pushCorrelationID(id, RoctracerLogger::CorrelationDomain::Default); } void RocmProfiler::Stop(uint64_t) { d->popCorrelationID(RoctracerLogger::CorrelationDomain::Default); } void RocmProfiler::addEventRecord(const roctracerRow &item, int64_t pstart, const std::initializer_list<std::pair<std::string, std::string>> &args, std::map<uint64_t, std::vector<EventRecord>> &event_map) { EventRecord event{onnxruntime::profiling::API_EVENT, static_cast<int>(item.pid), static_cast<int>(item.tid), std::string(roctracer_op_string(ACTIVITY_DOMAIN_HIP_API, item.cid, 0)), static_cast<int64_t>((item.begin - pstart) / 1000), static_cast<int64_t>((item.end - item.begin) / 1000), {args.begin(), args.end()}}; // FIXME: deal with missing ext correlation auto extId = d->externalCorrelations_[RoctracerLogger::CorrelationDomain::Default][item.id]; if (event_map.find(extId) == event_map.end()) { event_map.insert({extId, {event}}); } else { event_map[extId].push_back(std::move(event)); } } } // namespace profiling } // namespace onnxruntime #endif
[ "noreply@github.com" ]
noreply@github.com
55eef579838a086e5a4cb755cce9858010262a29
82596453a61d0bb099dcc1eef908b273e65e704f
/test/old/caffe_pred.cpp
4412e77470b59a63ee1ba411c9cfd1f7bda0be13
[]
no_license
chuangtsing/deCaffeServer
22b7380652f63d566b41fb1fae2c0636c628b85b
cfaabba4f3c4975ac4d5e27411dddc2fb54144a0
refs/heads/master
2021-01-20T17:23:46.299622
2016-07-22T02:51:12
2016-07-22T02:51:12
63,918,292
0
0
null
null
null
null
UTF-8
C++
false
false
5,157
cpp
#include <glog/logging.h> #include <ctime> #include <string> #include <numeric> #include "caffe_pred.hpp" using std::string; using std::static_pointer_cast; using std::clock; using std::clock_t; using caffe::Blob; using caffe::Caffe; using caffe::Datum; using caffe::Net; using caffe::shared_ptr; using caffe::vector; using caffe::MemoryDataLayer; namespace caffe { const char* const CaffePred::class_names[] = {"Person", "Soldier", "Army Tank", "Military Vehicle", "Truck", "Car", "Launcher", "Rifle", "Explosion", "Ship", "Helicopter", "Animal", "Background"}; template <typename T> vector<size_t> ordered(vector<T> const& values) { vector<size_t> indices(values.size()); std::iota(begin(indices), end(indices), static_cast<size_t>(0)); std::sort( begin(indices), end(indices), [&](size_t a, size_t b) { return values[a] > values[b]; } ); return indices; } CaffePred::CaffePred(string model_path, string weights_path) { CHECK_GT(model_path.size(), 0) << "Need a model definition to score."; CHECK_GT(weights_path.size(), 0) << "Need model weights to score."; Caffe::set_mode(Caffe::CPU); clock_t t_start = clock(); caffe_net = new Net<float>(model_path, caffe::TEST); caffe_net->CopyTrainedLayersFrom(weights_path); clock_t t_end = clock(); } CaffePred::~CaffePred() { free(caffe_net); caffe_net = NULL; } int CaffePred::test(string img_path) { CHECK(caffe_net != NULL); Datum datum; CHECK(ReadImageToDatum(img_path, 0, 256, 256, true, &datum)); const shared_ptr<MemoryDataLayer<float>> memory_data_layer = static_pointer_cast<MemoryDataLayer<float>>( caffe_net->layer_by_name("data")); memory_data_layer->AddDatumVector(vector<Datum>({datum})); vector<Blob<float>* > dummy_bottom_vec; float loss; clock_t t_start = clock(); const vector<Blob<float>*>& result = caffe_net->Forward(dummy_bottom_vec, &loss); clock_t t_end = clock(); const float* argmaxs = result[1]->cpu_data(); for (int i = 0; i < result[1]->num(); i++) { for (int j = 0; j < result[1]->height(); j++) { LOG(INFO) << " Image: "<< i << " class:" << argmaxs[i*result[1]->height() + j]; } } return argmaxs[0]; } vector<int> CaffePred::predict_top_k(string img_path, Caffe::Brew mode, int k) { CHECK(caffe_net != NULL); std::cout << "step 1" << std::endl; Datum datum; Caffe::set_mode(mode); CHECK(ReadImageToDatum(img_path, 0, 256, 256, true, &datum)); const shared_ptr<MemoryDataLayer<float>> memory_data_layer = static_pointer_cast<MemoryDataLayer<float>>( caffe_net->layer_by_name("data")); memory_data_layer->AddDatumVector(vector<Datum>({datum})); float loss; vector<Blob<float>* > dummy_bottom_vec; clock_t t_start = clock(); const vector<Blob<float>*>& result = caffe_net->Forward(dummy_bottom_vec, &loss); clock_t t_end = clock(); std::cout << "Time: " << (int) ((t_end - t_start) * 1000) / CLOCKS_PER_SEC << "ms\n"; const vector<float> probs = vector<float>(result[1]->cpu_data(), result[1]->cpu_data() + result[1]->count()); CHECK_LE(k, probs.size()); vector<size_t> sorted_index = ordered(probs); return vector<int>(sorted_index.begin(), sorted_index.begin() + k); } vector<int> CaffePred::predict_top_k_mat(const cv::Mat &img, Caffe::Brew mode, int k) { CHECK(caffe_net != NULL); Datum datum; Caffe::set_mode(mode); CVMatToDatum(img, &datum); const shared_ptr<MemoryDataLayer<float>> memory_data_layer = static_pointer_cast<MemoryDataLayer<float>>( caffe_net->layer_by_name("data")); memory_data_layer->AddDatumVector(vector<Datum>({datum})); float loss; vector<Blob<float>* > dummy_bottom_vec; clock_t t_start = clock(); const vector<Blob<float>*>& result = caffe_net->Forward(dummy_bottom_vec, &loss); clock_t t_end = clock(); std::cout << "Time: " << (int) ((t_end - t_start) * 1000) / CLOCKS_PER_SEC << "ms\n"; const vector<float> probs = vector<float>(result[1]->cpu_data(), result[1]->cpu_data() + result[1]->count()); CHECK_LE(k, probs.size()); vector<size_t> sorted_index = ordered(probs); return vector<int>(sorted_index.begin(), sorted_index.begin() + k); } vector<int> CaffePred::predict_top_k_batch(const vector<cv::Mat*> &imgs, Caffe::Brew mode, int k) { CHECK(caffe_net != NULL); Datum datum; vector<Datum> *data = new vector<Datum>(); Caffe::set_mode(mode); for(int i = 0; i < imgs.size(); i++) { CVMatToDatum(*imgs[i], &datum); data->push_back(datum); } const shared_ptr<MemoryDataLayer<float>> memory_data_layer = static_pointer_cast<MemoryDataLayer<float>>( caffe_net->layer_by_name("data")); memory_data_layer->AddDatumVector(*data); float loss; vector<Blob<float>* > dummy_bottom_vec; clock_t t_start = clock(); const vector<Blob<float>*>& result = caffe_net->Forward(dummy_bottom_vec, &loss); clock_t t_end = clock(); std::cout << "Time: " << (int) ((t_end - t_start) * 1000) / CLOCKS_PER_SEC << "ms\n"; const vector<float> probs = vector<float>(result[1]->cpu_data(), result[1]->cpu_data() + result[1]->count()); CHECK_LE(k, probs.size()); vector<size_t> sorted_index = ordered(probs); delete data; return vector<int>(sorted_index.begin(), sorted_index.begin() + k); } } // namespace caffe
[ "chuangtsing@gmail.com" ]
chuangtsing@gmail.com
bb033bcb3f5ed320890a6dffd1f3d00ca78be72f
511ce67e7340d9a9058057fadf4b46027c841a3d
/tests/common/test_rand.cpp
84182ba02dc2bf8efb72644b9fc65d816d58eb9e
[ "LicenseRef-scancode-mit-old-style", "Spencer-94" ]
permissive
PickXu/zero-xum
12d661c0c0c63de65bc914f600a847cb8a0a9631
251e5582e6e956610045ba36e4c16b438252d40c
refs/heads/master
2021-01-10T16:02:18.111230
2017-01-25T23:41:01
2017-01-25T23:41:01
52,102,399
1
1
null
2017-02-14T17:13:04
2016-02-19T16:53:39
C++
UTF-8
C++
false
false
8,884
cpp
#include "w.h" #include "w_defines.h" #include "rand48.h" #include "gtest/gtest.h" #include <iostream> int tries(0); #if W_DEBUG_LEVEL > 3 bool verbose(true); #else // W_DEBUG_LEVEL bool verbose(false); #endif // W_DEBUG_LEVEL bool debug(false); bool shift(false); bool use_drand(false); bool use_randn(false); bool use_alt(false); uint64_t seed = RAND48_INITIALIZER; // WORDS_BIGENDIAN is determined by autoconf -- see configure.ac typedef struct { #ifdef WORDS_BIGENDIAN // big-endian: vax, sparc unsigned int sign:1; unsigned int exponent:11; unsigned int mant1:20; unsigned int mant2:32; #else // We don't deal with little-endian machines whose float order is big-endian // little-endian : intel, powerpc, etc unsigned int mant2:32; unsigned int mant1:20; unsigned int exponent:11; unsigned int sign:1; #endif } w_ieee_double; typedef struct { unsigned int sign:1; unsigned int exponent:11; unsigned int mant1:20; unsigned int mant2:32; } w_ieee_double_big; typedef struct { unsigned int mant2:32; unsigned int mant1:20; unsigned int exponent:11; unsigned int sign:1; } w_ieee_double_little; typedef unsigned char UC; typedef UC ary[8]; typedef union { double d; signed48_t s; int64_t l; w_ieee_double ieee; w_ieee_double_big big; w_ieee_double_little lit; ary c; }PUN; static void p(const char *str, const PUN &u); static void p(const char *str, const unsigned48_t &u); static void p(const char *str, const signed48_t &u); static void p(const char *str, const double &u); struct randorig : public rand48 { randorig() { seed(RAND48_INITIAL_SEED); } randorig(const rand48 &other) { _state = other._state; } bool operator == (const randorig & other)const { return _state == other._state; } void dump( const char *str, bool debug)const ; }; void randorig::dump( const char *str, bool debug) const { union { double d; int64_t l; w_ieee_double ieee; } u; u.l = _state; cout << str << " hex: " << ::hex << u.l << ::dec; if(debug) { cout << " double: " << setprecision(21) << u.d << " sign: " << ::hex << u.ieee.sign << ::dec << " exp: " << ::hex << u.ieee.exponent << ::dec << " mant1: " << ::hex << u.ieee.mant1 << ::dec << " mant2: " << ::hex << u.ieee.mant2 << ::dec; } cout << endl; int64_t tmp = _state; const uint64_t mplier = 0x5deece66dull; tmp *= mplier; cout << " _update preview: " << " state * 0x5deece66dull: " << ::hex << tmp << ::dec ; tmp += 0xb; cout << " state + 0xb: " << ::hex << tmp << ::dec ; tmp = _mask(tmp); cout << " _mask(state): " << ::hex << tmp << ::dec ; cout << endl; } // randalt: basically the same as the library rand class, // but this gives us a change to override the generators for // testing purposes struct randalt : public randorig { randalt() { } randalt(const rand48 &other) : randorig(other) { } double drand() ; }; double randalt::drand() { union { double d; w_ieee_double ieee; } u; if(0) { uint64_t save_state = _state; unsigned48_t tmp = _update(); cout << endl; u.ieee.sign = 0x0; u.ieee.exponent = 0x0; u.ieee.mant1 = 0x0; u.ieee.mant2 = 0x0; p("ALT clear 0x0", u.d); u.ieee.exponent = 0x3ff; p("ALT set exponent 0x3ff", u.d); cout << endl; p("ALT _update()", tmp); tmp <<= 4; p("ALT _update()<<4", tmp); cout << endl; unsigned48_t tmp3 = tmp & 0xfffff00000000ull; p("ALT high part of _update()<<4", tmp3); tmp3 >>= 32; p("ALT high part shifted right", tmp3); u.ieee.mant1 = (tmp & 0xfffff00000000ull)>>32; p("ALT set mant1 to high part of _update()<<4", u.d); tmp3 = tmp & 0x0000ffffffffull; p("ALT low part of _update()<<4", tmp3); u.ieee.mant2 = tmp & 0xffffffffull; p("ALT set mant2 to low part of _update()<<4", u.d); _state = save_state; } u.ieee.sign = 0x0; u.ieee.exponent = 0x3ff; unsigned48_t tmp = _update(); tmp <<= 4; unsigned48_t tmp3 = tmp & 0xfffff00000000ull; tmp3 >>= 32; u.ieee.mant1 = (tmp & 0xfffff00000000ull)>>32; tmp3 = tmp & 0x0000ffffffffull; u.ieee.mant2 = tmp & 0xffffffffull; return u.d-1.0; } rand48 tls_rng = RAND48_INITIALIZER; randorig orig; randalt alt; void p(const char *str, const PUN &u) { cout << str << " double: " << setprecision(21) << u.d << " hex: " << ::hex << u.l << ::dec << " sign: " << ::hex << u.ieee.sign << ::dec << " exp: " << ::hex << u.ieee.exponent << ::dec << " mant1: " << ::hex << u.ieee.mant1 << ::dec << " mant2: " << ::hex << u.ieee.mant2 << ::dec; cout << " -> " ; for (int i=0;i < 8; i++) { cout << ::hex << " " << unsigned(u.c[i]) << ::dec; } cout << endl; } void p(const char *str, const double &d) { PUN u; u.d = d; p(str, u); } void p(const char *str, const unsigned48_t &g) { PUN u; u.s = g; p(str, u); } void p(const char *str, const signed48_t &g) { PUN u; u.s = g; p(str, u); } void runtest() { if(verbose) { #ifdef WORDS_BIGENDIAN cout << "BIG ENDIAN" << endl; #else cout << "LITTLE ENDIAN" << endl; #endif PUN u; u.big.sign = 0x1; // 1 bit u.big.exponent = 0x123; // 11 bits u.big.mant1 = 0xaaaaa; // 20 bits u.big.mant2 = 0xbbccddee; // 32 bits p("set u.big ", u.s); u.lit.sign = 0x1; // 1 bit u.lit.exponent = 0x123; // 11 bits u.lit.mant1 = 0xaaaaa; // 20 bits u.lit.mant2 = 0xbbccddee; // 32 bits p("set u.little", u.s); } alt._state = orig._state; // test the input and output functions (not operators) { unsigned48_t X = alt._state; const char *file = "./rand48-test"; ofstream O(file, ios::out); out (O,X); ifstream I(file); in (I, X); EXPECT_EQ(X, alt._state) << "Look at " << file << " : state should be " << alt._state << " but was input as " << X; } for(int i=0; i < tries; i++) { cout << "--------------------------------------------------------- " << endl << ::dec << (i+1) << ": " ; if(verbose || debug) orig.dump("ORIG", debug); if((verbose || debug) && use_alt) alt.dump("ALT ", debug); if( orig == alt ) { if(verbose) cout << __LINE__ << " --------- MATCH " << endl; } else { if(verbose) cout << __LINE__ << " --------- MISMATCH " << endl; if(verbose) orig.dump("ORIG", debug); if(verbose && use_alt) alt.dump("ALT ", debug); } if(use_drand) { double d=orig.drand(); double f=alt.drand(); if(verbose && use_alt) { if( orig == alt ) { cout << __LINE__ << " --------- MATCH " << endl; } else { cout << __LINE__ << " --------- MISMATCH " << endl; orig.dump("ORIG", debug); alt.dump("ALT ", debug); } } else { if(verbose) orig.dump("ORIG", debug); } cout << setprecision(21) << " drand: orig=" << d ; if(use_alt) { cout << " alt=" << f ; EXPECT_EQ(d, f) << " ************ERR" << " orig.drand:" << d << " alt.drand:" << f; } cout << endl; } // use_drand if(1) { // use rand() signed48_t g= orig.rand(); signed48_t h = alt.rand(); cout << " rand: orig=" << ::hex << g ; if(shift) { cout << " shift " << ::hex << (g<<32); } if(use_alt) { cout << " alt=" << h << ::dec ; EXPECT_EQ(g, h) << " ************ERR" << " orig.drand:" << g << " alt.drand:" << h; } cout << endl; } // rand if(use_randn) { signed48_t g= orig.randn(23*tries); signed48_t h = alt.randn(23*tries); cout << " randn(" << 23*tries << "): orig=" << g ; if(use_alt) { cout << " alt=" << h ; EXPECT_EQ(g, h) << " ************ERR" << " orig.drand:" << g << " alt.drand:" << h; } cout << endl; } // use_randn } } TEST (RandTest, RandN) { tries = 30; use_randn = true; runtest(); } TEST (RandTest, Rand) { tries = 30; use_randn = false; runtest(); }
[ "eric.anderson4@hp.com" ]
eric.anderson4@hp.com
8481b4d0fad5c2a262f17943fa9dcb729fcdb7f2
402128d394151f038888d198f17bb93c09dd0d7d
/Source/GAS/Private/GAS_AbilityUtilityInterface.cpp
4b766b918dc647316aae7577b7135f1d9a69d799
[]
no_license
fogeZombie/GAS
24a0e5fe4963e5aaa999b6f7b77c740e72a775e9
9e4db66263e5a129b630654281af386137774c4a
refs/heads/master
2020-06-23T20:43:47.118754
2019-08-04T12:02:35
2019-08-04T12:02:35
198,746,941
0
0
null
null
null
null
UTF-8
C++
false
false
182
cpp
// Copyright BroachForge 2019 #include "GAS_AbilityUtilityInterface.h" // Add default functionality here for any IGAS_AbilityUtilityInterface functions that are not pure virtual.
[ "fogeZombie@gmail.com" ]
fogeZombie@gmail.com
b28129412fe9225c08fa251922a2667e5635aa2d
0de2d677f8425eccefe162da30a9bd2ba13831de
/DX_study/DX_study/Script/Util/Time.cpp
858278d1d0ffced448d66b62a1634867bfc51fda
[]
no_license
wlsvy/2020_DirectX_Project
d5cd129e0beaf009ee961404ae68e6c8c807fed0
2578a38384a7adedb0bcf277b60dfebbcf1213b1
refs/heads/master
2021-04-01T17:49:52.770311
2020-08-04T04:37:39
2020-08-04T04:37:39
248,203,677
0
0
null
null
null
null
UTF-8
C++
false
false
371
cpp
#include "Time.h" #include "../Internal/Core/InternalHelper.h" #include "../Internal/Engine/Timer.h" #include "../Internal//Engine/Engine.h" double Time::GetTime() { return Core::GetTimer().GetTime(); } double Time::GetDeltaTime() { return Core::GetTimer().GetDeltaTime(); } float Time::GetFixedDeltaTime() { return Engine::FIXED_FRAME_RATE; }
[ "hubjpkim@gmail.com" ]
hubjpkim@gmail.com
a9a32c88540aa8fa542450542ae57ff6df97814d
135872194654e089d88f732c9976f8b9e32891fa
/trunk/Common/include/Thread.hh
9ee6afb0ae50aedcdf87e76e3b04877fb2b99e9e
[]
no_license
GuillaumeGas/Spy
468eb461cae997150bec8294a3da0d52a66fcaad
6e8660fe04f4e07113975c549c85e1594f7a04db
refs/heads/master
2021-01-19T02:14:24.854872
2016-11-05T11:22:59
2016-11-05T11:22:59
17,173,839
1
0
null
null
null
null
UTF-8
C++
false
false
706
hh
#ifndef _THREAD #define _THREAD #include <boost/thread.hpp> #include <vector> template <typename T> class Thread { public: Thread( void(T::*fct)(), T * fils) { m_fils = fils; m_fct = fct; } void start() { my_th.push_back(new boost::thread(boost::bind(m_fct, m_fils))); } void other(void(T::*fct)()) { my_th.push_back(new boost::thread(boost::bind(fct, m_fils))); } void join() { for ( int i = 0 ; i < my_th.size() ; i++ ) { my_th[i]->join(); } } void kill() { for ( int i = 0 ; i < my_th.size() ; i++ ) { my_th[i]->interrupt(); } } private: void(T::*m_fct)(); T * m_fils; std::vector<boost::thread *> my_th; }; #endif
[ "ecadorel@gmail.com" ]
ecadorel@gmail.com
61cf1f463c26c43849ce17239c9e1ffde1491f96
ffde864d4d72cdeef58ae81758f67bb27decdb07
/rill-rt/lib/runtime.cpp
d8e01926f159596ed231174b60dfa28de13c1d6e
[ "BSL-1.0" ]
permissive
rhysd/rill
a7a96cf9803c126cb18b4288ee8693f556036f5a
cb16e511c6bdd4ea0b2bcbec51bd43724cc7ddcb
refs/heads/master
2020-07-11T00:25:39.939972
2015-01-13T16:54:27
2015-01-13T16:54:37
26,599,001
0
0
null
null
null
null
UTF-8
C++
false
false
242
cpp
#if defined(RILL_RT_WINDOWS) // # include "runtime_windows-x64.cpp" #elif defined(RILL_RT_LINUX) // # include "runtime-linux-x64.cpp" #else // TODO: add more runtime supports # error "Your target environment is not supported..." #endif
[ "yutopp@gmail.com" ]
yutopp@gmail.com
426b456216f0d14119c0eb3b998008d27b084381
b4660cc8fa3ce045508105fa52228a98fa19a87d
/src/prediction/zero_query_dict.h
984b5cc0238814d008a0b3d7fca8644e699dfe6e
[ "BSD-3-Clause", "LicenseRef-scancode-unicode", "LicenseRef-scancode-public-domain" ]
permissive
hnakamur/mozc-deb
81e9b561863e57da73aa9ba90d24ff5d0bca480b
a0d6db21786ae7fc54806714cbeca6c7c74cbd36
refs/heads/master
2021-04-15T09:32:03.635220
2018-05-04T10:09:23
2018-05-04T10:09:23
126,575,465
0
1
null
null
null
null
UTF-8
C++
false
false
7,089
h
// Copyright 2010-2016, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef MOZC_PREDICTION_ZERO_QUERY_DICT_H_ #define MOZC_PREDICTION_ZERO_QUERY_DICT_H_ #include <algorithm> #include <iterator> #include <utility> #include "base/port.h" #include "base/serialized_string_array.h" namespace mozc { enum ZeroQueryType { ZERO_QUERY_NONE = 0, // "☁" (symbol, non-unicode 6.0 emoji), and rule based. ZERO_QUERY_NUMBER_SUFFIX, // "階" from "2" ZERO_QUERY_EMOTICON, // "(>ω<)" from "うれしい" ZERO_QUERY_EMOJI, // <umbrella emoji> from "かさ" // Following types are defined for usage stats. // The candidates of these types will not be stored at |ZeroQueryList|. // - "ヒルズ" from "六本木" // These candidates will be generated from dictionary entries // such as "六本木ヒルズ". ZERO_QUERY_BIGRAM, // - "に" from "六本木". // These candidates will be generated from suffix dictionary. ZERO_QUERY_SUFFIX, }; // bit fields enum ZeroQueryEmojiType { EMOJI_NONE = 0, EMOJI_UNICODE = 1, EMOJI_DOCOMO = 2, EMOJI_SOFTBANK = 4, EMOJI_KDDI = 8, }; // Zero query dictionary is a multimap from string to a list of zero query // entries, where each entry can be looked up by equal_range() method. The data // is serialized to two binary data: token array and string array. Token array // encodes an array of zero query entries, where each entry is encoded in 16 // bytes as follows: // // ZeroQueryEntry { // uint32 key_index: 4 bytes // uint32 value_index: 4 bytes // ZeroQueryType type: 2 bytes // uint16 emoji_type: 2 bytes // uint32 emoji_android_pua: 4 bytes // } // // The token array is sorted in ascending order of key_index for binary search. // String values of key and value are encoded separately in the string array, // which can be extracted by using |key_index| and |value_index|. The string // array is also sorted in ascending order of strings. For the serialization // format of string array, see base/serialized_string_array.h". class ZeroQueryDict { public: static const size_t kTokenByteSize = 16; class iterator : public std::iterator<std::random_access_iterator_tag, uint32> { public: iterator(const char *ptr, const SerializedStringArray *array) : ptr_(ptr), string_array_(array) {} iterator(const iterator& x) = default; iterator& operator=(const iterator& x) = default; uint32 operator*() const { return key_index(); } uint32 key_index() const { return *reinterpret_cast<const uint32 *>(ptr_); } uint32 value_index() const { return *reinterpret_cast<const uint32 *>(ptr_ + 4); } ZeroQueryType type() const { const uint16 val = *reinterpret_cast<const uint16 *>(ptr_ + 8); return static_cast<ZeroQueryType>(val); } uint16 emoji_type() const { return *reinterpret_cast<const uint16 *>(ptr_ + 10); } uint32 emoji_android_pua() const { return *reinterpret_cast<const uint32 *>(ptr_ + 12); } StringPiece key() const { return (*string_array_)[key_index()]; } StringPiece value() const { return (*string_array_)[value_index()]; } iterator &operator++() { ptr_ += kTokenByteSize; return *this; } iterator operator++(int) { const iterator tmp(ptr_, string_array_); ptr_ += kTokenByteSize; return tmp; } iterator &operator+=(ptrdiff_t n) { ptr_ += n * kTokenByteSize; return *this; } friend iterator operator+(iterator iter, ptrdiff_t n) { iter += n; return iter; } friend iterator operator+(ptrdiff_t n, iterator iter) { iter += n; return iter; } iterator &operator-=(ptrdiff_t n) { ptr_ -= n * kTokenByteSize; return *this; } friend iterator operator-(iterator iter, ptrdiff_t n) { iter -= n; return iter; } friend ptrdiff_t operator-(iterator x, iterator y) { return (x.ptr_ - y.ptr_) / kTokenByteSize; } friend bool operator==(iterator x, iterator y) { return x.ptr_ == y.ptr_; } friend bool operator!=(iterator x, iterator y) { return x.ptr_ != y.ptr_; } friend bool operator<(iterator x, iterator y) { return x.ptr_ < y.ptr_; } friend bool operator<=(iterator x, iterator y) { return x.ptr_ <= y.ptr_; } friend bool operator>(iterator x, iterator y) { return x.ptr_ > y.ptr_; } friend bool operator>=(iterator x, iterator y) { return x.ptr_ >= y.ptr_; } private: const char *ptr_; const SerializedStringArray * string_array_; }; void Init(StringPiece token_array_data, StringPiece string_array_data) { token_array_ = token_array_data; string_array_.Set(string_array_data); } iterator begin() const { return iterator(token_array_.data(), &string_array_); } iterator end() const { return iterator(token_array_.data() + token_array_.size(), &string_array_); } std::pair<iterator, iterator> equal_range(StringPiece key) const { const auto iter = std::lower_bound(string_array_.begin(), string_array_.end(), key); if (iter == string_array_.end() || *iter != key) { return std::pair<iterator, iterator>(end(), end()); } return std::equal_range(begin(), end(), iter.index()); } private: StringPiece token_array_; SerializedStringArray string_array_; }; } // namespace mozc #endif // MOZC_PREDICTION_ZERO_QUERY_DICT_H_
[ "hnakamur@gmail.com" ]
hnakamur@gmail.com
7d8b869dfcf86358350ee080daa7a7443eab0635
41f9e5597ed62fa14bfc2e37402116340ace2ab2
/ir/ir.ino
5dbb7baf6e923f52cce7c67746553e6b0d8a7cef
[]
no_license
Daemon256/Arduino_soundlights
186bb170e4a85e6458a695e4ce73ce226c3af437
6ce99b6ec67331a23edf5d6301e0c62a3a4671b9
refs/heads/master
2016-09-11T04:41:52.188858
2015-01-17T08:11:12
2015-01-17T08:11:12
29,384,562
1
2
null
null
null
null
UTF-8
C++
false
false
5,537
ino
/* AndyPi Spectrum Analyser for Arduino Nano http://andypi.co.uk Date: 27-09-2014 Design: AndyPi Verision: 1.0 Code based on: OpenMusicLabs.com FHT example; Adafruit WS2801 Library & example NOTE: FastLED library does NOT work due to memory conflicts Hardware: Arduino Nano An IR LED must be connected to Arduino PWM pin 3. Adafruit electret mic: A0 pin */ #include "SPI.h" // Comment out this line if using Trinket or Gemma #include <IRremote.h> #define OCTAVE 1 // // Group buckets into octaves (use the log output function LOG_OUT 1) #define OCT_NORM 0 // Don't normalise octave intensities by number of bins #define FHT_N 256 // set to 256 point fht #include <FHT.h> // include the library /* F720DF - red F7A05F - green F7609F - blue F7E01F - white F7D02F - flash F7F00F - strobe F7C837 - fade F7E817 - smooth F728D7 -elloy F76897 - pink F7C03F - on F740BF - off */ IRsend irsend; //IRrecv irrecv(0); int noise[]={204,188,68,73,150,120,88,68}; // noise level determined by playing pink noise and seeing levels [trial and error]{204,188,68,73,150,98,88,68} void setup() { Serial.begin(115200); // use the serial port // strip.begin(); // initialise WS2801 strip // strip.show(); // Update LED contents, to start they are all 'off' TIMSK0 = 0; // turn off timer0 for lower jitter ADCSRA = 0xe5; // set the adc to free running mode ADMUX = 0x40; // use adc0 DIDR0 = 0x01; // turn off the digital input for adc0 } void loop() { // Start of Fourier Transform code; takes input on ADC from mic while(1) { // reduces jitter cli(); // UDRE interrupt slows this way down on arduino1.0 for (int i = 0 ; i < FHT_N ; i++) { // save 256 samples while(!(ADCSRA & 0x10)); // wait for adc to be ready ADCSRA = 0xf5; // restart adc byte m = ADCL; // fetch adc data byte j = ADCH; int k = (j << 8) | m; // form into an int k -= 0x0200; // form into a signed int k <<= 6; // form into a 16b signed int fht_input[i] = k; // put real data into bins } fht_window(); // window the data for better frequency response fht_reorder(); // reorder the data before doing the fht fht_run(); // process the data in the fht fht_mag_octave(); // take the output of the fht fht_mag_log() sei(); // End of Fourier Transform code - output is stored in fht_oct_out[i]. // i=0-7 frequency (octave) bins (don't use 0 or 1), fht_oct_out[1]= amplitude of frequency for bin 1 // for loop a) removes background noise average and takes absolute value b) low / high pass filter as still very noisy // c) maps amplitude of octave to a colour between blue and red d) sets pixel colour to amplitude of each frequency (octave) int fht_noise_adjusted[8]; int ColourSpectrum[8]; for (int i = 4; i < 5; i++) { // For each of the 6 useful octave bins fht_noise_adjusted[i] = abs(fht_oct_out[i]-noise[i]); // take the pink noise average level out, take the asbolute value to avoid negative numbers fht_noise_adjusted[i] = constrain(fht_noise_adjusted[i], 37, 125); // 37 lowpass for noise; 125 high pass doesn't go much higher than this [found by trial and error] ColourSpectrum[i] = map(fht_noise_adjusted[i], 37, 125, 160, 0); // map to values 0 - 160, i.e. blue to red on colour spectrum - larger range gives more colour variability [found by trial and error] Serial.println(ColourSpectrum[i]); convert (ColourSpectrum[i]); //test("NEC1", NEC, color, 32); // strip.setPixelColor((i-2), Wheel(ColourSpectrum[i])); // set each pixels colour to the amplitude of that particular octave } // strip.show(); // update the LEDs } } void test(char *label, int type, unsigned long value, int bits) { // Serial.println(label); if (type == NEC) { irsend.sendNEC(value, bits); } } void convert (int con) { /* F720DF - red F7A05F - green F7609F - blue F7E01F - white F7D02F - flash F7F00F - strobe F7C837 - fade F7E817 - smooth F728D7 -elloy F76897 - pink F7C03F - on F740BF - off */ if ( con < 90) { Serial.print("Nec:"); Serial.println(con); test("NEC1", NEC, 0xF740BF, 32); } if (con < 179 && con >= 150) { Serial.print("Nec:"); Serial.println(con); test("NEC1", NEC, 0xF7C03F, 32); test("NEC1", NEC, 0xF720DF, 32); //test("NEC1", NEC, 0xF740BF, 32); } if (con <= 149 && con >= 140){ Serial.print("Nec:"); Serial.println(con); test("NEC1", NEC, 0xF7C03F, 32); test("NEC1", NEC, 0xF7A05F, 32); // test("NEC1", NEC, 0xF740BF, 32); } if (con <= 139 && con >= 130) { Serial.print("Nec:"); Serial.println(con); test("NEC1", NEC, 0xF7C03F, 32); test("NEC1", NEC, 0xF7609F, 32); //test("NEC1", NEC, 0xF740BF, 32); } if (con <= 129 && con >= 120) { Serial.print("Nec:"); Serial.println(con); test("NEC1", NEC, 0xF7C03F, 32); test("NEC1", NEC, 0xF728D7, 32); // test("NEC1", NEC, 0xF740BF, 32); } if (con <= 119 && con >= 110) { Serial.print("Nec:"); Serial.println(con); test("NEC1", NEC, 0xF7C03F, 32); test("NEC1", NEC, 0xF7A05F, 32); // test("NEC1", NEC, 0xF740BF, 32); } if (con <= 109 && con >= 100) { Serial.print("Nec:"); Serial.println(con); test("NEC1", NEC, 0xF7C03F, 32); test("NEC1", NEC, 0xF76897, 32); // test("NEC1", NEC, 0xF740BF, 32); } if (con <= 99 && con >= 91) { Serial.print("Nec:"); Serial.println(con); test("NEC1", NEC, 0xF7C03F, 32); test("NEC1", NEC, 0xF720DF, 32); // test("NEC1", NEC, 0xF740BF, 32); } }
[ "daemon256@gmail.com" ]
daemon256@gmail.com
9a7d2fa38b85af108858acaf03dbdc13c654db9a
2ba94892764a44d9c07f0f549f79f9f9dc272151
/Engine/Source/Editor/AIGraph/Private/SGraphEditorActionMenuAI.cpp
b8fdcf409362660f0ffdc85c95cd02666590e6d3
[ "BSD-2-Clause", "LicenseRef-scancode-proprietary-license" ]
permissive
PopCap/GameIdea
934769eeb91f9637f5bf205d88b13ff1fc9ae8fd
201e1df50b2bc99afc079ce326aa0a44b178a391
refs/heads/master
2021-01-25T00:11:38.709772
2018-09-11T03:38:56
2018-09-11T03:38:56
37,818,708
0
0
BSD-2-Clause
2018-09-11T03:39:05
2015-06-21T17:36:44
null
UTF-8
C++
false
false
2,755
cpp
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "AIGraphPrivatePCH.h" #include "SGraphEditorActionMenuAI.h" #include "AIGraphSchema.h" SGraphEditorActionMenuAI::~SGraphEditorActionMenuAI() { OnClosedCallback.ExecuteIfBound(); } void SGraphEditorActionMenuAI::Construct( const FArguments& InArgs ) { this->GraphObj = InArgs._GraphObj; this->GraphNode = InArgs._GraphNode; this->DraggedFromPins = InArgs._DraggedFromPins; this->NewNodePosition = InArgs._NewNodePosition; this->OnClosedCallback = InArgs._OnClosedCallback; this->AutoExpandActionMenu = InArgs._AutoExpandActionMenu; this->SubNodeFlags = InArgs._SubNodeFlags; // Build the widget layout SBorder::Construct( SBorder::FArguments() .BorderImage( FEditorStyle::GetBrush("Menu.Background") ) .Padding(5) [ // Achieving fixed width by nesting items within a fixed width box. SNew(SBox) .WidthOverride(400) [ SAssignNew(GraphActionMenu, SGraphActionMenu) .OnActionSelected(this, &SGraphEditorActionMenuAI::OnActionSelected) .OnCollectAllActions(this, &SGraphEditorActionMenuAI::CollectAllActions) .AutoExpandActionMenu(AutoExpandActionMenu) ] ] ); } void SGraphEditorActionMenuAI::CollectAllActions(FGraphActionListBuilderBase& OutAllActions) { // Build up the context object FGraphContextMenuBuilder ContextMenuBuilder(GraphObj); if (GraphNode != NULL) { ContextMenuBuilder.SelectedObjects.Add(GraphNode); } if (DraggedFromPins.Num() > 0) { ContextMenuBuilder.FromPin = DraggedFromPins[0]; } // Determine all possible actions const UAIGraphSchema* MySchema = Cast<const UAIGraphSchema>(GraphObj->GetSchema()); if (MySchema) { MySchema->GetGraphNodeContextActions(ContextMenuBuilder, SubNodeFlags); } // Copy the added options back to the main list //@TODO: Avoid this copy OutAllActions.Append(ContextMenuBuilder); } TSharedRef<SEditableTextBox> SGraphEditorActionMenuAI::GetFilterTextBox() { return GraphActionMenu->GetFilterTextBox(); } void SGraphEditorActionMenuAI::OnActionSelected( const TArray< TSharedPtr<FEdGraphSchemaAction> >& SelectedAction, ESelectInfo::Type InSelectionType ) { if (InSelectionType == ESelectInfo::OnMouseClick || InSelectionType == ESelectInfo::OnKeyPress || SelectedAction.Num() == 0) { bool bDoDismissMenus = false; if (GraphObj) { for ( int32 ActionIndex = 0; ActionIndex < SelectedAction.Num(); ActionIndex++ ) { TSharedPtr<FEdGraphSchemaAction> CurrentAction = SelectedAction[ActionIndex]; if ( CurrentAction.IsValid() ) { CurrentAction->PerformAction(GraphObj, DraggedFromPins, NewNodePosition); bDoDismissMenus = true; } } } if (bDoDismissMenus) { FSlateApplication::Get().DismissAllMenus(); } } }
[ "dkroell@acm.org" ]
dkroell@acm.org
66c37a94f0ea43189bb61632a14ce14ab60a21c5
ecdd542de3946d5f1428e35dbb2f1e8d11a189d0
/many-ways-to-blink-5.ino
c188010a56ab58c09da5e37bde42c97a6f76a35b
[]
no_license
workshopweekend/many-ways-to-blink-5
f4d0e572920c6a88698d62e74ded677f0905b80a
7cf590e536f142d3a76d1acf804aac685286cfa1
refs/heads/master
2021-01-19T13:01:16.140922
2015-02-08T00:25:59
2015-02-08T00:25:59
19,165,770
0
0
null
null
null
null
UTF-8
C++
false
false
1,962
ino
/* Adapted From: Analog Input by David Cuartielles and Tom Igoe Author: Malcolm Knapp Project: Ultrasonic Sensor to Computer Date: 4/10/14 Version: 0.1 Description: This code shows how to use a Ultrasonic Distance Sensor to control the blink rate of a computer screen. */ // ---------- included libraries ------------ #include <Servo.h> #include <NewPing.h> // ---------- hardware pin defines ----------- int triggerPin = 12; // select the pin ultrasonic trigger int echoPin = 11; // select pint // ---------- variable initialization ----------- int delayTime = 0; //variable that holds the delay time in milliseconds int scaling = 1; unsigned int uS = 0; // holds the time it took for the pulse to be recived unsigned int distance = 0; // holds the distance in centimeters int maxValue = 100; // in centimeter int minValue = 0; // in centimeter int maxDistance = 200; char Terminator = '\n'; // in centimeters // ---------- library initialization ----------- NewPing sonar(triggerPin, echoPin, maxDistance); void setup() { Serial.begin(9600); //---------- hardware declaration ---------- } void loop() { // Input delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings. uS = sonar.ping(); // Send ping, get ping time in microseconds (uS). distance = uS / US_ROUNDTRIP_CM; // convert time to distance // Debugging Serial.print("uS value: "); Serial.println(uS); Serial.print("Distance (cm): "); Serial.println(distance); // Processing //Scaling delayTime = map (distance, minValue, maxValue, 200, 1023); Serial.print ("Delay in milliseconds: "); Serial.println (delayTime); // Modes // None - put new modes here // Output Serial.print("ON"); Serial.print(Terminator); delay(delayTime); Serial.print("OFF"); Serial.print(Terminator); delay(delayTime); }
[ "mfhkconsulting@gmail.com" ]
mfhkconsulting@gmail.com
b1fd3a1f1d7003ecf22eb24236eb155439303d36
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-rds/source/model/DescribeDBParametersResult.cpp
5f3f5dce87c53bb11f017015d5dd2c2d7c4c54e4
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
2,024
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/rds/model/DescribeDBParametersResult.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/logging/LogMacros.h> #include <utility> using namespace Aws::RDS::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils::Logging; using namespace Aws::Utils; using namespace Aws; DescribeDBParametersResult::DescribeDBParametersResult() { } DescribeDBParametersResult::DescribeDBParametersResult(const Aws::AmazonWebServiceResult<XmlDocument>& result) { *this = result; } DescribeDBParametersResult& DescribeDBParametersResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result) { const XmlDocument& xmlDocument = result.GetPayload(); XmlNode rootNode = xmlDocument.GetRootElement(); XmlNode resultNode = rootNode; if (!rootNode.IsNull() && (rootNode.GetName() != "DescribeDBParametersResult")) { resultNode = rootNode.FirstChild("DescribeDBParametersResult"); } if(!resultNode.IsNull()) { XmlNode parametersNode = resultNode.FirstChild("Parameters"); if(!parametersNode.IsNull()) { XmlNode parametersMember = parametersNode.FirstChild("Parameter"); while(!parametersMember.IsNull()) { m_parameters.push_back(parametersMember); parametersMember = parametersMember.NextNode("Parameter"); } } XmlNode markerNode = resultNode.FirstChild("Marker"); if(!markerNode.IsNull()) { m_marker = Aws::Utils::Xml::DecodeEscapedXmlText(markerNode.GetText()); } } if (!rootNode.IsNull()) { XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); m_responseMetadata = responseMetadataNode; AWS_LOGSTREAM_DEBUG("Aws::RDS::Model::DescribeDBParametersResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); } return *this; }
[ "sdavtaker@users.noreply.github.com" ]
sdavtaker@users.noreply.github.com
1a9c7f3d4080723e3f5b54b2ef75eb77b6663dfe
943134a005bbf8069b149e0375ef23e020b5a908
/codes/dp/mininsertiontomakepalindrome.cpp
f3f21b44c7083ea0d9214bcbb0de461fa308e4e6
[]
no_license
msrishu65/codes
accbb4e21c6f35751b474fa8496150658efab008
e0e2e854d23f31a6906f6f817d563a0af8d8770b
refs/heads/master
2021-01-13T02:02:18.314439
2014-10-13T17:07:49
2014-10-13T17:07:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
640
cpp
#include<iostream> #include<limits.h> using namespace std; int main() { string s="abcd"; int m[4][4]; int i,j; for(i=0;i<4;i++) { for(j=0;j<4;j++) m[i][j]=0; } for(int l=1;l<4;l++) { for(i=0;i<4-l;i++) { j=i+l; //cout<<i<<endl; //cout<<s.at(i); //<<" "<<s[j]; if(s[i]==s[j]) { // cout<<"no"; m[i][j]=m[i+1][j-1]; } else { //cout<<"han"; m[i][j]=min(m[i][j-1],m[i+1][j])+1; } //cout<<m[i][j]<<endl; } //cout<<"yo"<<endl; } cout<<m[0][3]; }
[ "maninder@ubuntu.ubuntu-domain" ]
maninder@ubuntu.ubuntu-domain
975d32a5d882012fabc14b05fda3805f92e63401
377f42df2a694ee91623030c5ba8e03797593595
/headers/styling.h
ce39bb64f7b14408c25148d8ff1ba130410bf720
[]
no_license
MohammedMaaz/Calculator_version_1.1
3cf0fedea82e8802c4ea532447d553ad256850f8
aa1e9148bc3bc30213606d4ea1e19bff1ae8ec68
refs/heads/master
2021-01-23T00:54:15.117402
2020-07-13T21:12:53
2020-07-13T21:12:53
85,851,013
0
0
null
null
null
null
UTF-8
C++
false
false
13,715
h
#ifndef STYLING_H_INCLUDED #define STYLING_H_INCLUDED #include<SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <vector> #include<string> #include <iostream> int Stoi(std::string str) { int res=0; for(unsigned int i=0; i<str.size(); ++i) { res += ((int)((char)str[i]) - 48)*pow(10.0,str.size()-i-1); } return res; } sf::String toSfString(std::string str) { sf::String Str; for(unsigned int i=0; i<str.size(); ++i) { Str += (char)(str[i]); } return Str; } class Button : public sf::Transformable { public: //public data-members //NOTE: Convention for data-members followed is that there first alphabet is capitalized std::string ReturnValue; std::string ShowValue; sf::Text text; //to access the text such as obj.text.sfmlProp etc. void setDimensions(float X1, float Y1, float X2, float Y2) { x1=X1; y1=Y1; x2=X2; y2=Y2; //Drawing the button Box.setSize(sf::Vector2f(x2-x1,y2-y1)); Box.setPosition(x1,y1); } void syncWithWindow(sf::RenderWindow* userWindow) { win = userWindow; } void setColor(short r, short g, short b, short a=255) { Clr = sf::Color(r,g,b,a); Box.setFillColor(Clr); } void setTextFont(sf::Font &userFont) { font = &userFont; text.setFont(*font); } void writeText(sf::String str) { text.setString(str); textX = x1 + ( (x2-x1)-text.getGlobalBounds().width )/2; textY = y1 + ( (y2-y1)-text.getGlobalBounds().height )/2; text.setPosition(textX,textY); boxStr = str; } void setTextOffset(float x, float y) { textX = textX + x; textY = textY + y; text.setPosition(textX,textY); } void setTextColor(short r, short g, short b, short a=255) { textClr = sf::Color(r,g,b,a); text.setFillColor(textClr); } void setOutline(short r, short g, short b, short a=255, float width=1) { outlineClr = sf::Color(r,g,b,a); outlineWidth = width; Box.setOutlineColor(outlineClr); Box.setOutlineThickness(outlineWidth); } bool isHovered() { if(win==nullptr) return false; sf::Vector2i mousePos = sf::Mouse::getPosition(*win); if(mousePos.x>=x1 && mousePos.x<=x2 && mousePos.y>=y1 && mousePos.y<=y2) return true; else return false; } void setHoverDimensions(float X1, float Y1, float X2, float Y2) { hoverDimensionsTrigger = true; hoverX1=X1; hoverY1=Y1; hoverX2=X2; hoverY2=Y2; } void setHoverTextColor(short r, short g, short b, short a=255) { hoverTextClr = sf::Color(r,g,b,a); hoverTextClrTrigger = true; } void setHoverColor(short r, short g, short b, short a=255, float time = 7.5) { hoverClr = sf::Color(r,g,b,a); hoverClrTrigger = true; if(time<=0) { rT = Clr.a; startRTime = Clr.a; startHTime = hoverClr.a; hT = hoverClr.a; } else transitionTime = time; } void writeHoverText(sf::String str) { text.setString(str); hoverTextX = hoverX1 + ( (hoverX2-hoverX1)-text.getLocalBounds().width )/2; hoverTextY = hoverY1 + ( (hoverY2-hoverY1)-text.getLocalBounds().height )/2; hoverBoxStrTrigger = true; hoverBoxStr = str; } void setHoverTextOffset(float x, float y) { hoverTextX = hoverTextX + x; hoverTextY = hoverTextY + y; } void setHoverOutline(short r, short g, short b, short a=255, float width=1) { hoverOutlineClr = sf::Color(r,g,b,a); hoverOutlineWidth = width; hoverOutlineTrigger = true; } bool IsClicked(sf::Event& e) { if( isClickable && ((e.type == sf::Event::MouseButtonPressed && e.mouseButton.button==sf::Mouse::Left && this->isHovered() ) || (e.type == sf::Event::KeyPressed && e.key.code==clickKey)) ) { sound.play(); realClick = true; return true; } else if( (e.type == sf::Event::MouseButtonReleased && e.mouseButton.button==sf::Mouse::Left && this->isHovered() ) || (e.type == sf::Event::KeyReleased && e.key.code==clickKey) ) { realClick = false; return false; } } void setClickKey(sf::Keyboard::Key userKey) { clickKey = userKey; } void setClickable(bool val) { isClickable = val; } void setClickColor(short r, short g, short b, short a=255) { clickClr = sf::Color(r,g,b,a); clickClrTrigger = true; } void setClickSound(sf::SoundBuffer &buffer) { soundBuffer = &buffer; sound.setBuffer(buffer); } void setClickDimensions(float X1, float Y1, float X2, float Y2) { clickX1 = X1; clickX2 = X2; clickY1 = Y1; clickY2 = Y2; clickDeimensionsTrigger = true; } void Draw() { if(hoverDimensionsTrigger) { this->setDimensions(x1,y1,x2,y2); if( this->isHovered()) { Box.setSize(sf::Vector2f(hoverX2-hoverX1,hoverY2-hoverY1)); Box.setPosition(hoverX1,hoverY1); } } if(hoverBoxStrTrigger) { text.setString(boxStr); text.setPosition(textX,textY); if(this->isHovered()) { text.setString(hoverBoxStr); text.setPosition(hoverTextX,hoverTextY); } } if(hoverTextClrTrigger) { this->setTextColor(textClr.r,textClr.g,textClr.b,textClr.a); if( this->isHovered() ) text.setFillColor(hoverTextClr); } if(hoverOutlineTrigger) { this->setOutline(outlineClr.r,outlineClr.g,outlineClr.b,outlineClr.a,outlineWidth); if( this->isHovered() ) { Box.setOutlineColor(hoverOutlineClr); Box.setOutlineThickness(hoverOutlineWidth); } } if(hoverClrTrigger) { if(this->isHovered()) { rT=startRTime; Box.setFillColor(sf::Color(hoverClr.r,hoverClr.g,hoverClr.b,hT)); if(hT<hoverClr.a) hT+=transitionTime; } else { hT=startHTime; Box.setFillColor(sf::Color(Clr.r,Clr.g,Clr.b,rT)); if(rT<hoverClr.a) rT+=transitionTime; } } if(clickDeimensionsTrigger) { if(!hoverDimensionsTrigger) this->setDimensions(x1,y1,x2,y2); if(realClick) { Box.setSize(sf::Vector2f(clickX2-clickX1,clickY2-clickY1)); Box.setPosition(clickX1,clickY1); } } if(clickClrTrigger) { if(!hoverClrTrigger) Box.setFillColor(Clr); if(realClick) Box.setFillColor(clickClr); } win->draw(Box); win->draw(text); } private: sf::RenderWindow* win; sf::Font* font; sf::SoundBuffer* soundBuffer; sf::Sound sound; float x1,y1,x2,y2, hoverX1,hoverY1,hoverX2,hoverY2, clickX1,clickX2,clickY1,clickY2; float textX, textY, hoverTextX,hoverTextY; sf::String boxStr, hoverBoxStr; sf::Color Clr, hoverClr, clickClr; sf::Color textClr, hoverTextClr; sf::Color outlineClr, hoverOutlineClr; float outlineWidth, hoverOutlineWidth; float transitionTime, hT = 30, rT = 30, startRTime=30, startHTime = 30; sf::Keyboard::Key clickKey = sf::Keyboard::Unknown; bool hoverDimensionsTrigger = false; bool hoverClrTrigger = false; bool hoverBoxStrTrigger = false; bool hoverTextClrTrigger = false; bool hoverOutlineTrigger = false; bool clickClrTrigger = false; bool isClickable = true; bool realClick = false; bool clickDeimensionsTrigger = false; protected: // To access the shape and text properties by the inherited/Daughter class sf::RectangleShape Box; //to access the shape properties }; class displayRect { public: displayRect(sf::RenderWindow& userWin, sf::Font &userFont) { win = &userWin; text.setFont(userFont); Box.setSize(sf::Vector2f(610,100)); Box.setPosition(50,20); Box.setFillColor(sf::Color(63,63,63)); Box.setOutlineThickness(1.65); Box.setOutlineColor(sf::Color(19,139,168)); } void writeTextAtPos(std::string str,float x, float y) { boxStr = str; if(str.size() > 33) str = str.substr(boxStr.size()-33); text.setString(toSfString(str)); text.setPosition(x,y); } void Draw() { win->draw(Box); win->draw(text); } private: sf::RenderWindow* win = nullptr; sf::Text text; std::string boxStr; sf::RectangleShape Box; }; Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, bDot, bPlus, bMinus, bDivide, bMultiply, bPercent, bSq, bCube,bNpow, bFact,bLeftB,bRightB,bReciprocal,bSin,bCos, bTan, bASin, bACos, bATan, bSqrt, bCbRt,bLog, bLn, bExp, b10x, bPie,bEquals,bBackspace,bClear; //global objects std::vector<Button*> buttonArray ={&b0,&b1,&b2,&b3,&b4,&b5,&b6,&b7,&b8,&b9,&bDot,&bPlus,&bMinus,&bDivide,&bMultiply,&bPercent,&bSq, &bCube,&bNpow,&bFact,&bLeftB,&bRightB,&bReciprocal,&bSin,&bCos, &bTan, &bASin, &bACos, &bATan, &bSqrt, &bCbRt,&bLog, &bLn, &bExp, &b10x, &bPie,&bEquals,&bBackspace,&bClear}; std::vector<std::string> showValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "+", "-", "/", "x", "%", "^2", "^3", "^", "!", "(", ")", "1/(", "sin(", "cos(", "tan(", "asin(", "acos(", "atan(","sqrt(", "cbrt(", "log(", "ln(", "e^(", "10^(", "pi","=", "", "" }; std::vector<std::string> returnValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "+", "-", "/", "x", "%", "^2", "^3", "^", "!", "(", ")", "1/(", "s(", "c(", "t(", "S(", "C(", "T(","q(", "w(", "L(", "l(", "e^(", "10^(", "p","=", "", "" }; short brChecker = 0; void buttonValidator(std::vector<std::string> _stack) { for(unsigned int i=0; i<buttonArray.size(); ++i) //at every cycle set all keys click able buttonArray[i]->setClickable(true); //changing equals color bEquals.setColor(21,225,60); bEquals.setHoverColor(60,255,107); std::string lastString; if(!_stack.empty()) lastString = _stack[_stack.size()-1]; //multiply checking if(lastString=="!" || lastString=="^2" || lastString=="^3" || lastString==")" || lastString=="pi" || (Stoi(lastString)>-1 && Stoi(lastString)<10) &&(!_stack.empty()) ) { for(int i=20; i<36; ++i) { buttonArray[i]->ReturnValue = "x" + returnValues[i]; } buttonArray[21]->ReturnValue = returnValues[21]; } else { for(int i=20; i<36; ++i) { buttonArray[i]->ReturnValue = returnValues[i]; } buttonArray[21]->ReturnValue = returnValues[21]; } //-checking bMinus.ReturnValue = returnValues[12]; bMinus.ShowValue = showValues[12]; if(_stack.empty()) { for(int i=10; i<20; ++i) buttonArray[i]->setClickable(false); bRightB.setClickable(false); bBackspace.setClickable(false); bClear.setClickable(false); bEquals.setClickable(false); bEquals.setColor(245,18,47); bEquals.setHoverColor(245,18,47); bMinus.setClickable(true); bMinus.ReturnValue = "0" + returnValues[12]; brChecker = 0; //bMinus.ShowValue = "0" + showValues[12]; } else if(lastString.at(lastString.size()-1)=='(') { for(int i=10; i<20; ++i) buttonArray[i]->setClickable(false); bRightB.setClickable(false); bEquals.setClickable(false); bEquals.setColor(245,18,47); bEquals.setHoverColor(245,18,47); bMinus.setClickable(true); bMinus.ReturnValue = "0" + returnValues[12]; } else if(lastString==".") { for(unsigned int i=10; i<buttonArray.size(); ++i) { buttonArray[i]->setClickable(false); } bEquals.setColor(245,18,47); bEquals.setHoverColor(245,18,47); bBackspace.setClickable(true); bClear.setClickable(true); } else if(lastString=="+"||lastString=="-"||lastString=="x"||lastString=="/"||lastString=="%"||lastString=="^") { for(int i=10; i<22; ++i) buttonArray[i]->setClickable(false); bLeftB.setClickable(true); bEquals.setClickable(false); bEquals.setColor(245,18,47); bEquals.setHoverColor(245,18,47); } else if(lastString=="!") { for(int i=0; i<11; ++i) buttonArray[i]->setClickable(false); for(int i=16; i<20; ++i) buttonArray[i]->setClickable(false); } else if(lastString==")" || lastString=="pi" || lastString=="xpi") { for(int i=0; i<11; ++i) buttonArray[i]->setClickable(false); } //validating brackets if(brChecker!=0) { bEquals.setClickable(false); bEquals.setColor(245,18,47); bEquals.setHoverColor(245,18,47); } } #endif // STYLING_H_INCLUDED
[ "maazproductions25@gmail.com" ]
maazproductions25@gmail.com
0c961d6d67bb6b1a916c195731e94ae463471a22
a0311691bc11bb024b909521f6445e73b21fd246
/src/XHCPDispatcher.cpp
958a46887aa0e99b26c7c2fe755fa2ac11e63d82
[]
no_license
codexsmith/xPL
a624f82fd03253434ada7f0faae5c50ed380f96d
a8c06d0688c3cf65f0d78128dbb47f8b86142f6b
refs/heads/master
2021-07-15T05:41:58.613953
2013-06-23T13:49:27
2013-06-23T13:49:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,181
cpp
#include "XHCPDispatcher.h" #include "XPLRuleManager.h" #include "Poco/String.h" #include "XPLHal.h" #include "events/XHCPEvent.h" XHCPDispatcher::XHCPDispatcher ( std::string aName ) { name = aName; } XHCPDispatcher::XHCPDispatcher ( XPLHal* halin ) { hal = halin; ruleMgr = hal->ruleMgr; } std::string XHCPDispatcher::delGlobal ( std::string strIn , SocketStream& strm ) { int split = strIn.find_first_of ( " " ); string arg = strIn.substr ( 0,split ); toUpperInPlace ( trimInPlace ( arg ) ); string ret; cout << "arg is " << arg << "\n"; hal->globals->deleteGlobal ( arg ); return "233 Global deleted\n"; } std::string XHCPDispatcher::getGlobal ( std::string strIn, SocketStream& strm ) { int split = strIn.find_first_of ( " " ); string arg = strIn.substr ( 0,split ); toUpperInPlace ( trimInPlace ( arg ) ); cout << "arg is " << arg << "\n"; map<string,string> globalcp = hal->globals->getGlobals(); string ret = ""; if ( globalcp.count ( arg ) ) { ret += "291 Global value follows" + XHCPCRLF; ret += globalcp[arg] + XHCPCRLF; ret += "." + XHCPCRLF; } else { ret += "491 No such global" + XHCPCRLF; } return ret; } std::string XHCPDispatcher::listGlobals ( std::string strIn, SocketStream& strm ) { string ret = "231 List of globals follows" + XHCPCRLF; map<string,string> globalcp = hal->globals->getGlobals(); map<string,string>::iterator git; for ( git = globalcp.begin(); git != globalcp.end(); ++git ) { ret += git->first + "=" + git->second + XHCPCRLF; } ret += "." + XHCPCRLF; return ret; } std::string XHCPDispatcher::setGlobal ( std::string strIn, SocketStream& strm ) { int split = strIn.find_first_of ( " " ); string arg0 = strIn.substr ( 0,split ); if ( !arg0.length() || arg0.length() == strIn.length() ) return ( "232 Global value updated" + XHCPCRLF ); string rest = strIn.substr ( split ); trimInPlace ( rest ); if ( !rest.length() ) return ( "232 Global value updated" + XHCPCRLF ); // split = rest.find_first_of(" "); // string arg1= rest.substr(0,split); // toUpperInPlace ( trimInPlace ( arg0 ) ); hal->globals->setGlobal ( arg0,rest ); return ( "232 Global value updated" + XHCPCRLF ); } std::string XHCPDispatcher::runRule ( std::string aString , SocketStream& strm ) { int split = aString.find_first_of ( " " ); string arg = aString.substr ( 0,split ); toUpperInPlace ( trimInPlace ( arg ) ); string ret; cout << "arg is " << arg << XHCPCRLF; bool exists = ruleMgr->runDeterminator ( arg ); if ( exists ) { return ( "203 Script/determinator executed" + XHCPCRLF ); } return ( "410 No such script/determinator" + XHCPCRLF ); } std::string XHCPDispatcher::setRule ( std::string aString , SocketStream& strm ) { int split = aString.find_first_of ( " " ); string arg = aString.substr ( 0,split ); toUpperInPlace ( trimInPlace ( arg ) ); string ret; cout << "arg is " << arg << "\n"; std::string theString = "338 Send rule, end with <CrLf>.<CrLf>" + XHCPCRLF; cout << theString; strm << theString; strm.flush(); string line = ""; string detxml = ""; while ( line != "." ) { detxml += line; getline ( strm,line ); trimInPlace ( line ); //cout << "detline: " << line << "\n"; } cout << "det: " << detxml << "::\n"; Determinator* newdet = new Determinator ( detxml ); if ( arg.length() ) { cout << "modifing exisitng determinator " << arg << XHCPCRLF; newdet->setGUID ( arg ); } ruleMgr->setDeterminator ( newdet->getGUID(), newdet ); theString = "238 " + newdet->getGUID() + XHCPCRLF; return theString; } std::string XHCPDispatcher::delRule ( std::string aString , SocketStream& strm ) { int split = aString.find_first_of ( " " ); string arg = aString.substr ( 0,split ); toUpperInPlace ( trimInPlace ( arg ) ); string ret; cout << "arg is " << arg << XHCPCRLF; bool deleted = ruleMgr->removeDeterminator ( arg ); if ( deleted ) { return ( "214 Script/determinator successfully deleted" + XHCPCRLF ); } return ( "410 No such script/determinator" + XHCPCRLF ); } std::string XHCPDispatcher::listRules ( std::string aString , SocketStream& strm ) { std::string theString; theString += ( "237 List of Determinator Rules follows" + XHCPCRLF ); //TODO deal with the thread-saftey issue here //TODO handle args like a group name or "{ALL}" ruleMgr->detLock.readLock(); map<string, Determinator*>* dets = ruleMgr->determinators; for ( map<string, Determinator*>::iterator dit = dets->begin(); dit!=dets->end(); ++dit ) { string detString; detString += dit->first + "\t"; detString += dit->second->name + "\t"; detString += dit->second->isEnabled() + "\t"; theString += detString + XHCPCRLF; } ruleMgr->detLock.unlock(); theString += "." + XHCPCRLF; //String += "b\r\n"; return theString; } std::string XHCPDispatcher::listRuleGroups ( std::string aString , SocketStream& strm ) { std::string theString; theString += "240 List of determinator groups follows" + XHCPCRLF; ruleMgr->detLock.readLock(); map<string, Determinator*>* dets = ruleMgr->determinators; for ( map<string, Determinator*>::iterator dit = dets->begin(); dit!=dets->end(); ++dit ) { if ( dit->second->isGroup ) { theString += dit->first + "\t"; theString += dit->second->groupName + XHCPCRLF; } } ruleMgr->detLock.unlock(); //TODO implement rule groups //theString += "4242\tFIXME group name\t\n"; theString += "." + XHCPCRLF; return theString; } std::string XHCPDispatcher::getRule ( std::string aString , SocketStream& strm ) { string arg = trim ( aString ); string ret; Determinator* det = ruleMgr->retrieveDeterminator ( arg ); if ( det ) { ret += "210 Requested script/rule follows" + XHCPCRLF; ret += det->printXML(); ret += XHCPCRLF; ret += "." + XHCPCRLF; } else { ret += "410 No such script/rule" + XHCPCRLF; } return ret; } std::string XHCPDispatcher::capCommand ( std::string aString , SocketStream& strm ) { int split = aString.find_first_of ( " " ); string arg = aString.substr ( 0,split ); toUpperInPlace ( trimInPlace ( arg ) ); std::string theString = "236 --010L0" + XHCPCRLF; if ( arg == "SCRIPTING" ) { theString = "241 --010L0" + XHCPCRLF; //"B<tab>BeanShell<tab>1.54<tab>bsh<tab>http://www.beanshell.org" theString += "." + XHCPCRLF; } return theString; } std::string XHCPDispatcher::listDevices ( std::string aString , SocketStream& strm ) { int split = aString.find_first_of ( " " ); string arg = aString.substr ( 0,split ); toUpperInPlace ( trimInPlace ( arg ) ); string ret=""; cout << "arg is " << arg << "\n"; ret += "216 List of XPL devices follows" + XHCPCRLF; if ( arg == "AWAITINGCONFIG" ) { } else if ( arg == "CONFIGURED" ) { } else if ( arg == "MISSINGCONFIG" ) { } else { } ret += "." + XHCPCRLF; return ret; } std::string XHCPDispatcher::listSubs ( std::string aString , SocketStream& strm ) { int split = aString.find_first_of ( " " ); string arg = aString.substr ( 0,split ); toUpperInPlace ( trimInPlace ( arg ) ); string ret; cout << "arg is " << arg << XHCPCRLF; ret += "224 List of subs follows" + XHCPCRLF; ret += ".\r\n"; return ret; } std::string XHCPDispatcher::listOptions ( std::string aString , SocketStream& strm ) { int split = aString.find_first_of ( " " ); string arg = aString.substr ( 0,split ); trimInPlace ( arg ); string ret = ""; cout << "arg is " << arg << "\n"; //ret += ".\r\n"; ret = "405 No such setting" + XHCPCRLF; return ret; } std::string XHCPDispatcher::quit ( std::string aString , SocketStream& strm ) { string ret = "221 Closing transmission channel - goodbye." + XHCPCRLF; return ret; } std::string XHCPDispatcher::addEvent ( std::string aString , SocketStream& strm ) { int split = aString.find_first_of ( " " ); string arg = aString.substr ( 0,split ); toUpperInPlace ( trimInPlace ( arg ) ); string ret; cout << "arg is " << arg << "\n"; std::string theString = "319 Enter event data, end with <CrLf>.<CrLf>" + XHCPCRLF; cout << theString; strm << theString; strm.flush(); string line = ""; string evttxt = ""; while ( line != "." ) { evttxt += line + "\n"; getline ( strm,line ); trimInPlace ( line ); } cout << "evt: " << evttxt << "::\n"; XHCPEvent evt = XHCPEvent(evttxt); cout << "evt:" + evt.getDescription() + "\n"; theString = "219 Event added successfully" + XHCPCRLF; return theString; }
[ "zeroping@gmail.com" ]
zeroping@gmail.com