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
f45402b176d3f70794149ce23b3424862f526dba
1501f50acc22b9e915d04df435210d68e2a907ee
/include/UnityEngine/AddressableAssets/AddressablesPlatform.hpp
909a52b8bb6b6902e68982b7294815dca8c82807
[ "Unlicense" ]
permissive
sc2ad/BeatSaber-Quest-Codegen
cd944128d6c7b61f2014f13313d2d6cf424df811
4bfd0c0f705e7a302afe6ec1ef996b5b2e3f4600
refs/heads/master
2023-03-11T11:07:22.074423
2023-02-28T22:15:16
2023-02-28T22:15:16
285,669,750
31
25
Unlicense
2023-02-28T22:15:18
2020-08-06T20:56:01
C++
UTF-8
C++
false
false
8,071
hpp
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Type namespace: UnityEngine.AddressableAssets namespace UnityEngine::AddressableAssets { // Forward declaring type: AddressablesPlatform struct AddressablesPlatform; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::AddressableAssets::AddressablesPlatform, "UnityEngine.AddressableAssets", "AddressablesPlatform"); // Type namespace: UnityEngine.AddressableAssets namespace UnityEngine::AddressableAssets { // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: UnityEngine.AddressableAssets.AddressablesPlatform // [TokenAttribute] Offset: FFFFFFFF struct AddressablesPlatform/*, public ::System::Enum*/ { public: public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating value type constructor for type: AddressablesPlatform constexpr AddressablesPlatform(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator ::System::Enum operator ::System::Enum() noexcept { return *reinterpret_cast<::System::Enum*>(this); } // Creating interface conversion operator: i_Enum inline ::System::Enum* i_Enum() noexcept { return reinterpret_cast<::System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public UnityEngine.AddressableAssets.AddressablesPlatform Unknown static constexpr const int Unknown = 0; // Get static field: static public UnityEngine.AddressableAssets.AddressablesPlatform Unknown static ::UnityEngine::AddressableAssets::AddressablesPlatform _get_Unknown(); // Set static field: static public UnityEngine.AddressableAssets.AddressablesPlatform Unknown static void _set_Unknown(::UnityEngine::AddressableAssets::AddressablesPlatform value); // static field const value: static public UnityEngine.AddressableAssets.AddressablesPlatform Windows static constexpr const int Windows = 1; // Get static field: static public UnityEngine.AddressableAssets.AddressablesPlatform Windows static ::UnityEngine::AddressableAssets::AddressablesPlatform _get_Windows(); // Set static field: static public UnityEngine.AddressableAssets.AddressablesPlatform Windows static void _set_Windows(::UnityEngine::AddressableAssets::AddressablesPlatform value); // static field const value: static public UnityEngine.AddressableAssets.AddressablesPlatform OSX static constexpr const int OSX = 2; // Get static field: static public UnityEngine.AddressableAssets.AddressablesPlatform OSX static ::UnityEngine::AddressableAssets::AddressablesPlatform _get_OSX(); // Set static field: static public UnityEngine.AddressableAssets.AddressablesPlatform OSX static void _set_OSX(::UnityEngine::AddressableAssets::AddressablesPlatform value); // static field const value: static public UnityEngine.AddressableAssets.AddressablesPlatform Linux static constexpr const int Linux = 3; // Get static field: static public UnityEngine.AddressableAssets.AddressablesPlatform Linux static ::UnityEngine::AddressableAssets::AddressablesPlatform _get_Linux(); // Set static field: static public UnityEngine.AddressableAssets.AddressablesPlatform Linux static void _set_Linux(::UnityEngine::AddressableAssets::AddressablesPlatform value); // static field const value: static public UnityEngine.AddressableAssets.AddressablesPlatform PS4 static constexpr const int PS4 = 4; // Get static field: static public UnityEngine.AddressableAssets.AddressablesPlatform PS4 static ::UnityEngine::AddressableAssets::AddressablesPlatform _get_PS4(); // Set static field: static public UnityEngine.AddressableAssets.AddressablesPlatform PS4 static void _set_PS4(::UnityEngine::AddressableAssets::AddressablesPlatform value); // static field const value: static public UnityEngine.AddressableAssets.AddressablesPlatform Switch static constexpr const int Switch = 5; // Get static field: static public UnityEngine.AddressableAssets.AddressablesPlatform Switch static ::UnityEngine::AddressableAssets::AddressablesPlatform _get_Switch(); // Set static field: static public UnityEngine.AddressableAssets.AddressablesPlatform Switch static void _set_Switch(::UnityEngine::AddressableAssets::AddressablesPlatform value); // static field const value: static public UnityEngine.AddressableAssets.AddressablesPlatform XboxOne static constexpr const int XboxOne = 6; // Get static field: static public UnityEngine.AddressableAssets.AddressablesPlatform XboxOne static ::UnityEngine::AddressableAssets::AddressablesPlatform _get_XboxOne(); // Set static field: static public UnityEngine.AddressableAssets.AddressablesPlatform XboxOne static void _set_XboxOne(::UnityEngine::AddressableAssets::AddressablesPlatform value); // static field const value: static public UnityEngine.AddressableAssets.AddressablesPlatform WebGL static constexpr const int WebGL = 7; // Get static field: static public UnityEngine.AddressableAssets.AddressablesPlatform WebGL static ::UnityEngine::AddressableAssets::AddressablesPlatform _get_WebGL(); // Set static field: static public UnityEngine.AddressableAssets.AddressablesPlatform WebGL static void _set_WebGL(::UnityEngine::AddressableAssets::AddressablesPlatform value); // static field const value: static public UnityEngine.AddressableAssets.AddressablesPlatform iOS static constexpr const int iOS = 8; // Get static field: static public UnityEngine.AddressableAssets.AddressablesPlatform iOS static ::UnityEngine::AddressableAssets::AddressablesPlatform _get_iOS(); // Set static field: static public UnityEngine.AddressableAssets.AddressablesPlatform iOS static void _set_iOS(::UnityEngine::AddressableAssets::AddressablesPlatform value); // static field const value: static public UnityEngine.AddressableAssets.AddressablesPlatform Android static constexpr const int Android = 9; // Get static field: static public UnityEngine.AddressableAssets.AddressablesPlatform Android static ::UnityEngine::AddressableAssets::AddressablesPlatform _get_Android(); // Set static field: static public UnityEngine.AddressableAssets.AddressablesPlatform Android static void _set_Android(::UnityEngine::AddressableAssets::AddressablesPlatform value); // static field const value: static public UnityEngine.AddressableAssets.AddressablesPlatform WindowsUniversal static constexpr const int WindowsUniversal = 10; // Get static field: static public UnityEngine.AddressableAssets.AddressablesPlatform WindowsUniversal static ::UnityEngine::AddressableAssets::AddressablesPlatform _get_WindowsUniversal(); // Set static field: static public UnityEngine.AddressableAssets.AddressablesPlatform WindowsUniversal static void _set_WindowsUniversal(::UnityEngine::AddressableAssets::AddressablesPlatform value); // Get instance field reference: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& dyn_value__(); }; // UnityEngine.AddressableAssets.AddressablesPlatform #pragma pack(pop) static check_size<sizeof(AddressablesPlatform), 0 + sizeof(int)> __UnityEngine_AddressableAssets_AddressablesPlatformSizeCheck; static_assert(sizeof(AddressablesPlatform) == 0x4); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
[ "redbrumbler.official+github@gmail.com" ]
redbrumbler.official+github@gmail.com
b626a140cb2c33ead08a0940d121b50a955059af
fed7f032be10355d8bd3892248fbf853a218aebc
/Task120/ofTask120_FrontLine/src/ofWarArea.h
e26cf8ee75a750ee1806d0daa9f5c7d63ad87d78
[]
no_license
lpestl/SimpleTasks
7ec413cac1161176da77d4b549a75a0a011496b6
c87f595bbd024af457ed82a0d4cc6d417fe0859c
refs/heads/master
2021-05-06T11:07:26.223246
2018-12-02T12:56:52
2018-12-02T12:56:52
114,215,965
0
0
null
2018-12-02T12:56:53
2017-12-14T07:15:46
C#
UTF-8
C++
false
false
609
h
#pragma once #include "ofPoint.h" #include "ofRectangle.h" #include "MilitaryIntelligence.h" struct cell { char value; std::vector<neighbor_status> borders; }; class ofWarArea { public: void setup(std::vector<std::vector<char>> real_area); void update(); void draw(); void windowResized(int w, int h); void next_step(); private: std::vector<std::vector<char>> real_area_; ofPoint logicSizeArea_; ofRectangle rectArea_; ofPoint cellSize_; std::vector<std::vector<cell>> area_; float betweenInterval_; military_intelligence * mi_; operation_status op_status_; intelligence_report report_; };
[ "mikhail.kataev@rubius.com" ]
mikhail.kataev@rubius.com
1eeedf3917373fa2c10a44b40af50b09dc0cd672
91da10320e3276a8858468a6b9828e2720ac7a2a
/common/file_handle/file_handle_imp.cpp
1b4ae9e8cd883754dce9fe90d8c0beb65a9f9b93
[]
no_license
neko940709/CLAIMS
8cfab4ea6cf201adbb10ef8c40732b885d0f0016
03623e53f30f53d69e222606bca82e306cb88ebd
refs/heads/master
2021-01-15T12:09:56.972404
2016-09-23T13:09:51
2016-09-23T13:09:51
68,585,873
1
0
null
2016-09-19T08:36:57
2016-09-19T08:36:57
null
UTF-8
C++
false
false
1,121
cpp
/* * Copyright [2012-2015] DaSE@ECNU * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * 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. * * /Claims/common/file_handle/file_handle_imp.cpp * * Created on: Oct 20, 2015 * Author: yukai * Email: yukai2014@gmail.com * * Description: * */ #include "./file_handle_imp.h" namespace claims { namespace common {} // namespace common } /* namespace claims */
[ "yukai2014@gmail.com" ]
yukai2014@gmail.com
4da62030322a253b595eb99b038f94dbfd21619c
3292ba9bd2a70eea8b6def75bb43e18796b48044
/cpp_CS225/lab/06-lab_trees/TreeTraversals/main.cpp
e7d224026ee21e001b80261ab45aceaa235d4989
[ "MIT" ]
permissive
Yutong-Dai/codes-for-courses
91125bd7156eb8756160b21d2bf71276bf31ab9a
a2dfea516ebc7cabef31a5169533b6da352e7ccb
refs/heads/master
2022-04-11T02:41:11.439127
2020-03-19T14:59:55
2020-03-19T14:59:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
855
cpp
#include <algorithm> #include <iostream> #include "InorderTraversal.h" #include "PreorderTraversal.h" using namespace std; int main() { // For deterministic behavior, use a fixed seed instead of a random device std::random_device r; std::mt19937 rng(r()); BinaryTree<int> myTree; for (int i = 1; i <= 10; i++) myTree.insertRandom(i, rng); myTree.print(); PreorderTraversal<int> pot(myTree.getRoot()); cout << "Preorder Traversal: "; for (TreeTraversal<int>::Iterator it = pot.begin(); it != pot.end(); ++it) { cout << (*it)->elem << " "; } cout << endl; InorderTraversal<int> iot(myTree.getRoot()); cout << "Inorder Traversal: "; for (TreeTraversal<int>::Iterator it = iot.begin(); it != iot.end(); ++it) { cout << (*it)->elem << " "; } cout << endl; }
[ "rothdyt@gmail.com" ]
rothdyt@gmail.com
fb84ae19afc11ac35b95d7085e3e4f308a489392
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/RWStepRepr_RWIntegerRepresentationItem.hxx
cbfdfce30b9256cbe73728d63688248e903c3fa7
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
1,805
hxx
// Created on: 2015-09-03 // Created by: Irina KRYLOVA // Copyright (c) 2015 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _RWStepRepr_RWIntegerRepresentationItem_HeaderFile #define _RWStepRepr_RWIntegerRepresentationItem_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Integer.hxx> #include <StepData_StepReaderData.hxx> #include <Interface_Check.hxx> #include <StepRepr_IntegerRepresentationItem.hxx> #include <StepData_StepWriter.hxx> class StepData_StepReaderData; class Interface_Check; class StepRepr_IntegerRepresentationItem; class StepData_StepWriter; //! Read & Write Module for IntegerRepresentationItem class RWStepRepr_RWIntegerRepresentationItem { public: DEFINE_STANDARD_ALLOC Standard_EXPORT RWStepRepr_RWIntegerRepresentationItem(); Standard_EXPORT void ReadStep (const Handle(StepData_StepReaderData)& data, const Standard_Integer num, Handle(Interface_Check)& ach, const Handle(StepRepr_IntegerRepresentationItem)& ent) const; Standard_EXPORT void WriteStep (StepData_StepWriter& SW, const Handle(StepRepr_IntegerRepresentationItem)& ent) const; }; #endif // _RWStepRepr_RWIntegerRepresentationItem_HeaderFile
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
0236236154947300e90f422e1b20033dcdd2e3bb
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/v8/test/cctest/test-assembler-s390.cc
f6b79d499499065e4cc164b739a883ca76d85f0c
[ "BSD-3-Clause", "Apache-2.0", "SunPro", "bzip2-1.0.6" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
13,735
cc
// Copyright 2014 the V8 project authors. 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. #include "src/v8.h" #include "src/disassembler.h" #include "src/factory.h" #include "src/macro-assembler.h" #include "src/s390/assembler-s390-inl.h" #include "src/s390/simulator-s390.h" #include "test/cctest/cctest.h" using namespace v8::internal; // Define these function prototypes to match JSEntryFunction in execution.cc. typedef Object* (*F1)(int x, int p1, int p2, int p3, int p4); typedef Object* (*F2)(int x, int y, int p2, int p3, int p4); typedef Object* (*F3)(void* p0, int p1, int p2, int p3, int p4); typedef Object* (*F4)(void* p0, void* p1, int p2, int p3, int p4); #define __ assm. // Simple add parameter 1 to parameter 2 and return TEST(0) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); __ lhi(r1, Operand(3)); // test 4-byte instr __ llilf(r2, Operand(4)); // test 6-byte instr __ lgr(r2, r2); // test 2-byte opcode __ ar(r2, r1); // test 2-byte instr __ b(r14); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG code->Print(); #endif F2 f = FUNCTION_CAST<F2>(code->entry()); intptr_t res = reinterpret_cast<intptr_t>( CALL_GENERATED_CODE(isolate, f, 3, 4, 0, 0, 0)); ::printf("f() = %" V8PRIxPTR "\n", res); CHECK_EQ(7, static_cast<int>(res)); } // Loop 100 times, adding loop counter to result TEST(1) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); Label L, C; #if defined(_AIX) __ function_descriptor(); #endif __ lr(r3, r2); __ lhi(r2, Operand(0, kRelocInfo_NONEPTR)); __ b(&C); __ bind(&L); __ ar(r2, r3); __ ahi(r3, Operand(-1 & 0xFFFF)); __ bind(&C); __ cfi(r3, Operand(0, kRelocInfo_NONEPTR)); __ bne(&L); __ b(r14); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG code->Print(); #endif F1 f = FUNCTION_CAST<F1>(code->entry()); intptr_t res = reinterpret_cast<intptr_t>( CALL_GENERATED_CODE(isolate, f, 100, 0, 0, 0, 0)); ::printf("f() = %" V8PRIxPTR "\n", res); CHECK_EQ(5050, static_cast<int>(res)); } TEST(2) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); // Create a function that accepts &t, and loads, manipulates, and stores // the doubles and floats. Assembler assm(CcTest::i_isolate(), NULL, 0); Label L, C; #if defined(_AIX) __ function_descriptor(); #endif __ lgr(r3, r2); __ lhi(r2, Operand(1)); __ b(&C); __ bind(&L); __ lr(r5, r2); // Set up muliplicant in R4:R5 __ mr_z(r4, r3); // this is actually R4:R5 = R5 * R2 __ lr(r2, r5); __ ahi(r3, Operand(-1 & 0xFFFF)); __ bind(&C); __ cfi(r3, Operand(0, kRelocInfo_NONEPTR)); __ bne(&L); __ b(r14); // some relocated stuff here, not executed __ RecordComment("dead code, just testing relocations"); __ iilf(r0, Operand(isolate->factory()->true_value())); __ RecordComment("dead code, just testing immediate operands"); __ iilf(r0, Operand(-1)); __ iilf(r0, Operand(0xFF000000)); __ iilf(r0, Operand(0xF0F0F0F0)); __ iilf(r0, Operand(0xFFF0FFFF)); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG code->Print(); #endif F1 f = FUNCTION_CAST<F1>(code->entry()); intptr_t res = reinterpret_cast<intptr_t>( CALL_GENERATED_CODE(isolate, f, 10, 0, 0, 0, 0)); ::printf("f() = %" V8PRIxPTR "\n", res); CHECK_EQ(3628800, static_cast<int>(res)); } TEST(3) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); __ ar(r14, r13); __ sr(r14, r13); __ mr_z(r14, r13); __ dr(r14, r13); __ or_z(r14, r13); __ nr(r14, r13); __ xr(r14, r13); __ agr(r14, r13); __ sgr(r14, r13); __ ogr(r14, r13); __ ngr(r14, r13); __ xgr(r14, r13); __ ahi(r13, Operand(123)); __ aghi(r13, Operand(123)); __ stm(r1, r2, MemOperand(r3, r0, 123)); __ slag(r1, r2, Operand(123)); __ lay(r1, MemOperand(r2, r3, -123)); __ a(r13, MemOperand(r1, r2, 123)); __ ay(r13, MemOperand(r1, r2, 123)); __ brc(Condition(14), Operand(123)); __ brc(Condition(14), Operand(-123)); __ brcl(Condition(14), Operand(123)); __ brcl(Condition(14), Operand(-123)); __ iilf(r13, Operand(123456789)); __ iihf(r13, Operand(-123456789)); __ mvc(MemOperand(r0, 123), MemOperand(r4, 567), 89); __ sll(r13, Operand(10)); v8::internal::byte* bufPos = assm.buffer_pos(); ::printf("buffer position = %p", static_cast<void*>(bufPos)); ::fflush(stdout); // OS::DebugBreak(); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG code->Print(); #endif USE(code); ::exit(0); } #if 0 TEST(4) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); Label L2, L3, L4; __ chi(r2, Operand(10)); __ ble(&L2); __ lr(r2, r4); __ ar(r2, r3); __ b(&L3); __ bind(&L2); __ chi(r2, Operand(5)); __ bgt(&L4); __ lhi(r2, Operand::Zero()); __ b(&L3); __ bind(&L4); __ lr(r2, r3); __ sr(r2, r4); __ bind(&L3); __ lgfr(r2, r3); __ b(r14); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG code->Print(); #endif F2 f = FUNCTION_CAST<F2>(code->entry()); intptr_t res = reinterpret_cast<intptr_t>( CALL_GENERATED_CODE(isolate, f, 3, 4, 3, 0, 0)); ::printf("f() = %" V8PRIdPTR "\n", res); CHECK_EQ(4, static_cast<int>(res)); } // Test ExtractBitRange TEST(5) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); MacroAssembler assm(isolate, NULL, 0); __ mov(r2, Operand(0x12345678)); __ ExtractBitRange(r3, r2, 3, 2); __ lgfr(r2, r3); __ b(r14); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG code->Print(); #endif F2 f = FUNCTION_CAST<F2>(code->entry()); intptr_t res = reinterpret_cast<intptr_t>(CALL_GENERATED_CODE(isolate, f, 3, 4, 3, 0, 0)); ::printf("f() = %" V8PRIdPTR "\n", res); CHECK_EQ(2, static_cast<int>(res)); } // Test JumpIfSmi TEST(6) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); MacroAssembler assm(isolate, NULL, 0); Label yes; __ mov(r2, Operand(0x12345678)); __ JumpIfSmi(r2, &yes); __ beq(&yes); __ Load(r2, Operand::Zero()); __ b(r14); __ bind(&yes); __ Load(r2, Operand(1)); __ b(r14); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG code->Print(); #endif F2 f = FUNCTION_CAST<F2>(code->entry()); intptr_t res = reinterpret_cast<intptr_t>(CALL_GENERATED_CODE(isolate, f, 3, 4, 3, 0, 0)); ::printf("f() = %" V8PRIdPTR "\n", res); CHECK_EQ(1, static_cast<int>(res)); } // Test fix<->floating point conversion. TEST(7) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); MacroAssembler assm(isolate, NULL, 0); Label yes; __ mov(r3, Operand(0x1234)); __ cdfbr(d1, r3); __ ldr(d2, d1); __ adbr(d1, d2); __ cfdbr(Condition(0), r2, d1); __ b(r14); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG code->Print(); #endif F2 f = FUNCTION_CAST<F2>(code->entry()); intptr_t res = reinterpret_cast<intptr_t>(CALL_GENERATED_CODE(isolate, f, 3, 4, 3, 0, 0)); ::printf("f() = %" V8PRIdPTR "\n", res); CHECK_EQ(0x2468, static_cast<int>(res)); } // Test DSGR TEST(8) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); MacroAssembler assm(isolate, NULL, 0); // Zero upper bits of r3/r4 __ llihf(r3, Operand::Zero()); __ llihf(r4, Operand::Zero()); __ mov(r3, Operand(0x0002)); __ mov(r4, Operand(0x0002)); __ dsgr(r2, r4); __ b(r14); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG code->Print(); #endif F1 f = FUNCTION_CAST<F1>(code->entry()); intptr_t res = reinterpret_cast<intptr_t>(CALL_GENERATED_CODE(isolate, f, 100, 0, 0, 0, 0)); ::printf("f() = %" V8PRIdPTR "\n", res); CHECK_EQ(0, static_cast<int>(res)); } // Test LZDR TEST(9) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); MacroAssembler assm(isolate, NULL, 0); __ lzdr(d4); __ b(r14); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG code->Print(); #endif F1 f = FUNCTION_CAST<F1>(code->entry()); intptr_t res = reinterpret_cast<intptr_t>(CALL_GENERATED_CODE(isolate, f, 0, 0, 0, 0, 0)); ::printf("f() = %" V8PRIdPTR "\n", res); } #endif // Test msrkc and msgrkc TEST(10) { if (!CpuFeatures::IsSupported(MISC_INSTR_EXT2)) { return; } ::printf("MISC_INSTR_EXT2 is enabled.\n"); CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); Label ok, failed; { // test 1: msrkc __ lgfi(r2, Operand(3)); __ lgfi(r3, Operand(4)); __ msrkc(r1, r2, r3); // 3 * 4 __ b(static_cast<Condition>(le | overflow), &failed); // test failed. __ chi(r1, Operand(12)); __ bne(&failed); // test failed. __ lgfi(r2, Operand(-3)); __ lgfi(r3, Operand(4)); __ msrkc(r1, r2, r3); // -3 * 4 __ b(static_cast<Condition>(ge | overflow), &failed); // test failed. __ chi(r1, Operand(-12)); __ bne(&failed); // test failed. __ iilf(r2, Operand(0x80000000)); __ lgfi(r3, Operand(-1)); __ msrkc(r1, r2, r3); // INT_MIN * -1 __ b(nooverflow, &failed); // test failed. __ cfi(r1, Operand(0x80000000)); __ bne(&failed); // test failed. } { // test 1: msgrkc __ lgfi(r2, Operand(3)); __ lgfi(r3, Operand(4)); __ msgrkc(r1, r2, r3); // 3 * 4 __ b(static_cast<Condition>(le | overflow), &failed); // test failed. __ chi(r1, Operand(12)); __ bne(&failed); // test failed. __ lgfi(r2, Operand(-3)); __ lgfi(r3, Operand(4)); __ msgrkc(r1, r2, r3); // -3 * 4 __ b(static_cast<Condition>(ge | overflow), &failed); // test failed. __ chi(r1, Operand(-12)); __ bne(&failed); // test failed. __ lgfi(r2, Operand::Zero()); __ iihf(r2, Operand(0x80000000)); __ lgfi(r3, Operand(-1)); __ msgrkc(r1, r2, r3); // INT_MIN * -1 __ b(nooverflow, &failed); // test failed. __ cgr(r1, r2); __ bne(&failed); // test failed. } __ bind(&ok); __ lgfi(r2, Operand::Zero()); __ b(r14); // test done. __ bind(&failed); __ lgfi(r2, Operand(1)); __ b(r14); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG code->Print(); #endif F2 f = FUNCTION_CAST<F2>(code->entry()); intptr_t res = reinterpret_cast<intptr_t>( CALL_GENERATED_CODE(isolate, f, 3, 4, 0, 0, 0)); ::printf("f() = %" V8PRIxPTR "\n", res); CHECK_EQ(0, static_cast<int>(res)); } #undef __
[ "changhyeok.bae@lge.com" ]
changhyeok.bae@lge.com
e99b0d70403c86df853d584a8f46e218926d0ce5
607829232b9ec8d6733fb67be85e8555d19e1ee0
/libs/core/include/fcppt/record/label_fwd.hpp
7b9df0626b3f0c741887abd9e95867efed049b68
[ "BSL-1.0" ]
permissive
cnsuhao/fcppt
3b917196d5faf477d769b8f04e0001361a857776
104c035118a04011c5fd9574cc78b2889550ea65
refs/heads/master
2021-01-13T06:30:29.527419
2016-11-05T13:33:41
2016-11-05T13:33:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
403
hpp
// Copyright Carl Philipp Reh 2009 - 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_RECORD_LABEL_FWD_HPP_INCLUDED #define FCPPT_RECORD_LABEL_FWD_HPP_INCLUDED namespace fcppt { namespace record { template< typename Tag > struct label; } } #endif
[ "carlphilippreh@gmail.com" ]
carlphilippreh@gmail.com
9bd59c559067f33adc7005fcd956a21e69762dad
378d404d4b8ec12dd9548470fa3b33d3dec087ff
/atcoder/yorukatu/dp100/dp100_5.cpp
97f88afc865ce8fe358ac4bd4e5d8d1650f6b9ad
[]
no_license
kk-katayama/com_pro
d0e8871aff88e7939d439c37f9cafd2d11a870fc
a3a6a3bcb846e2eded42d1fed5d9495e53a73e41
refs/heads/master
2021-06-25T18:49:35.320092
2021-02-05T06:50:38
2021-02-05T06:50:38
200,748,000
0
0
null
null
null
null
UTF-8
C++
false
false
1,154
cpp
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <utility> #include <set> #include <map> #include <cmath> #include <queue> #include <cstdio> #define rep(i,n) for(int i = 0; i < n; ++i) #define rep1(i,n) for(int i = 1; i <= n; ++i) #define rep2(i,s,t) for(int i = s; i <= t; ++i) #define rev(i,n) for(int i = n-1; i >= 0; --i) #define rev1(i,n) for(int i = n; i > 0; --i) #define rev2(i,s,t) for(int i = s; i >= t; --i) #define F first #define S second using namespace std; template<class T>bool chmax(T &a, const T &b) { if(a < b){ a = b; return 1; } return 0; } template<class T>bool chmin(T &a, const T &b) { if(a > b){ a = b; return 1; } return 0; } using ll = long long; using pi = pair<int,int>; using vi = vector<ll>; using vii = vector<vi>; int main() { int n; cin >> n; vi a(n); rep(i,n) cin >> a[i]; vii dp1(n+1, vi(200, 0)); vi dp2(n+1, 0); dp2[0] = 1000; rep(i,n) { rep(j,200) { chmax(dp1[i+1][j], dp1[i][j]); chmax(dp2[i+1], j + dp1[i][j] * a[i]); } chmax(dp1[i+1][dp2[i]%a[i]], dp2[i]/a[i]); chmax(dp2[i+1], dp2[i]); } cout << dp2[n] << "\n"; return 0; }
[ "galapagos4444@gmail.com" ]
galapagos4444@gmail.com
d91b9bb5e97823444c0a9d8e22da0b97e96435e5
da8ae98080ff729586bfeb4c11c52bd48327d06f
/SymOptim/tests/mainTests.cpp
879c8b592ac9a21051018e52553355071c5eaed1
[]
no_license
RhobanProject/SimLagrange
24670ffbb99cfca0c0f365ab1476f68e0e9aa3cc
db62b31cbbe7ddb2da821e927531a3b1fc80d927
refs/heads/master
2021-01-10T15:27:39.338821
2018-07-01T19:36:56
2018-07-01T19:36:56
44,232,478
0
0
null
null
null
null
UTF-8
C++
false
false
2,524
cpp
#include <iostream> #include <stdexcept> #include <cassert> #include "SymOptim/src/GradientDescent.hpp" #include "SymOptim/src/PenaltyMethod.hpp" #include "Symbolic/src/Constant.hpp" using namespace std; using namespace Leph::SymOptim; int main() { //Gradient Descent GradientDescent<double>::VariableContainer variables; variables.push("x", GradientDescent<double>::Symbol::create("x")); variables.push("y", GradientDescent<double>::Symbol::create("y")); GradientDescent<double>::TermPtr targetConvex = Leph::Symbolic::Add<double>::create( Leph::Symbolic::Mult<double,double,double>:: create(variables[0], variables[0]), Leph::Symbolic::Mult<double,double,double>:: create(variables[1], variables[1])); GradientDescent<double>::TermPtr targetSaddle = Leph::Symbolic::Sub<double>::create( Leph::Symbolic::Mult<double,double,double>:: create(variables[0], variables[0]), Leph::Symbolic::Mult<double,double,double>:: create(variables[1], variables[1])); GradientDescent<double> descentConvex(targetConvex, variables); descentConvex.state("x") = 10.0; descentConvex.state("y") = 5.0; descentConvex.runOptimization(false); assert(descentConvex.state("x") > -0.0001 && descentConvex.state("x") < 0.0001); assert(descentConvex.state("y") > -0.0001 && descentConvex.state("y") < 0.0001); GradientDescent<double> descentSaddle(targetSaddle, variables); descentSaddle.state("x") = 10.0; descentSaddle.state("y") = 5.0; try { descentSaddle.runOptimization(); assert(false); } catch (const std::runtime_error& error) { assert(true); } //Penalty Method PenaltyMethod<double> penalty(targetConvex, variables); PenaltyMethod<double>::TermPtr constraint = Leph::Symbolic::Sub<double>::create( variables["x"], Leph::Symbolic::Constant<double>::create(2.0)); penalty.addEqualityConstraint(constraint); penalty.state("x") = 1.0; penalty.state("y") = 1.0; penalty.runOptimization(); //cout << "Gradient Iteration: " << penalty.getDescentCount() << endl; //cout << "Penalty Iteration: " << penalty.getPenaltyCount() << endl; assert(penalty.state("x") > 1.99 && penalty.state("x") < 2.01); assert(penalty.state("y") > -0.0001 && penalty.state("y") < 0.0001); return 0; }
[ "leph.quentinrouxel@gmail.com" ]
leph.quentinrouxel@gmail.com
ea37dce899391b5347d2843bb97e3b04241929f8
9ec67e83200f643f9f55ed90e0b2cae4581ebcb6
/SupportLib/ImageRecolourInvertBlackAndWhite.h
ae66a27e5d7a1b180e2b96520c1ebf72c724ddc2
[]
no_license
andrewpaterson/Codaphela.Library
465770eaf2839589fc305660725abb38033f8aa2
2a4722ba0a4b98a304a297a9d74c9b6811fa4ac5
refs/heads/master
2023-05-25T13:01:45.587888
2023-05-14T11:46:36
2023-05-14T11:46:36
3,248,841
1
1
null
null
null
null
UTF-8
C++
false
false
1,548
h
/** ---------------- COPYRIGHT NOTICE, DISCLAIMER, and LICENSE ------------- ** Copyright (c) 2012 Andrew Paterson This file is part of The Codaphela Project: Codaphela SupportLib Codaphela SupportLib 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. Codaphela SupportLib 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 Codaphela SupportLib. If not, see <http://www.gnu.org/licenses/>. libpng is Copyright Glenn Randers-Pehrson zlib is Copyright Jean-loup Gailly and Mark Adler ** ------------------------------------------------------------------------ **/ #ifndef __IMAGE_RECOLOUR_INVERT_BLACK_AND_WHITE_H__ #define __IMAGE_RECOLOUR_INVERT_BLACK_AND_WHITE_H__ #include "ImageRecolour.h" class CImageRecolourInvertBlackAndWhite : public CImageRecolour { CONSTRUCTABLE(CImageRecolourInvertBlackAndWhite); public: CImageColourARGB cARGB0000; CImageColourARGB cARGB1111; CImageColourARGB cARGB0111; void Init(CRectangle* pcRectangle = NULL); void Kill(void); CImageColourARGB* GetBlack(void); }; #endif // !__IMAGE_RECOLOUR_INVERT_BLACK_AND_WHITE_H__
[ "andrew.ian.paterson@gmail.com" ]
andrew.ian.paterson@gmail.com
61642813ad8601ef9dd648f96040793c06825dcb
8ce93fe7930212f47c85e0750ac93927a4e765b3
/http_conn.cpp
ca4ab0c78289cb52b2ea98a76e68fa5ada924034
[]
no_license
angelaliuya/webserver
7fa5aeb629e41f460eef939f9d8a2f6e9b0a15bd
d09353439d8e62f0401a7991369fb36984a9249c
refs/heads/main
2023-07-01T06:48:49.884526
2021-07-23T14:36:53
2021-07-23T14:52:33
386,348,585
0
0
null
null
null
null
UTF-8
C++
false
false
22,266
cpp
#include "http_conn.h" // 定义HTTP响应的一些状态信息 const char* ok_200_title = "OK"; const char* error_400_title = "Bad Request"; const char* error_400_form = "Your request has bad syntax or is inherently impossible to satisfy.\n"; const char* error_403_title = "Forbidden"; const char* error_403_form = "You do not have permission to get file from this server.\n"; const char* error_404_title = "Not Found"; const char* error_404_form = "The requested file was not found on this server.\n"; const char* error_500_title = "Internal Error"; const char* error_500_form = "There was an unusual problem serving the requested file.\n"; // 网站的根目录 const char* doc_root = "/lywebserver/resources"; //设置非阻塞 int setnonblocking( int fd ) { int old_option = fcntl( fd, F_GETFL ); int new_option = old_option | O_NONBLOCK; fcntl( fd, F_SETFL, new_option ); return old_option; } // 向epoll中添加需要监听的文件描述符 //addfd( epollfd, listenfd, false ); //监听套接字 //addfd( m_epollfd, sockfd, true ); //连接套接字 void addfd( int epollfd, int fd, bool one_shot ) { epoll_event event; event.data.fd = fd; event.events = EPOLLIN | EPOLLRDHUP; //EPOLLRDHUP:通过事件判断对端是否断开 if(one_shot) { // 防止同一个通信被不同的线程处理 event.events |= EPOLLONESHOT; //只监听一次事件,当监听完这次事件之后,如果还需要继续监听这个socket的话,需要再次把这个socket加入到EPOLL队列里。 } /* epoll的事件注册函数: epoll的句柄; 动作类型:注册新的fd到epollfd 需要监听的fd; 告诉内核需要监听什么事; */ epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event); // 设置文件描述符非阻塞 setnonblocking(fd); } // 从epoll中移除监听的文件描述符 void removefd( int epollfd, int fd ) { epoll_ctl( epollfd, EPOLL_CTL_DEL, fd, 0 ); close(fd); } /* 当响应结束时:modfd( m_epollfd, m_sockfd, EPOLLIN );再次触发读 */ // 修改文件描述符,重置socket上的EPOLLONESHOT事件,以确保下一次可读时,EPOLLIN事件能被触发 void modfd(int epollfd, int fd, int ev) { epoll_event event; event.data.fd = fd; //修改已经注册的fd的监听事件 event.events = ev | EPOLLET | EPOLLONESHOT | EPOLLRDHUP; //设置为边沿触发, //将EPOLL设为边缘触发; /* 当被监控的文件描述符上有可读写事件发生时,epoll_wait会通知处理程序 去读写,如果这次没有把数据全部读写完,下次调用epoll_wait时,它不会通知你,直到 该文件描述符上出席那第二次读写事件事才会通知你。 */ epoll_ctl( epollfd, EPOLL_CTL_MOD, fd, &event ); } // 所有的客户数 int http_conn::m_user_count = 0; // 所有socket上的事件都被注册到同一个epoll内核事件中,所以设置成静态的 int http_conn::m_epollfd = -1; //是都用一个epollfd吗 // 关闭连接 void http_conn::close_conn() { if(m_sockfd != -1) { removefd(m_epollfd, m_sockfd); m_sockfd = -1; m_user_count--; // 关闭一个连接,将客户总数量-1 } } /* users[connfd].init( connfd, client_address); */ // 初始化连接,外部调用初始化套接字地址 void http_conn::init(int sockfd, const sockaddr_in& addr){ m_sockfd = sockfd; //客户端的sockfd m_address = addr; //客户端的ip地址 // 端口复用 int reuse = 1; /* 获取或设置与某个套接字关联的选项: 将要被设置或者获取选项的套接字; 选项所在的协议层;//控制套接字的层次:SOL_SOCKET(通用套接字选项);IPPROTO_IP:IP选项.)IPPROTO_TCP:TCP选项.  选项的名称; 指向包含新选项值的缓冲; 选项值的长度; SO_REUSEADDR:允许重用本地地址和端口   */ setsockopt( m_sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof( reuse ) ); addfd( m_epollfd, sockfd, true ); m_user_count++; init(); } void http_conn::init() { bytes_to_send = 0; bytes_have_send = 0; m_check_state = CHECK_STATE_REQUESTLINE; // 初始状态为检查请求行 m_linger = false; // 默认不保持链接 Connection : keep-alive保持连接 m_method = GET; // 默认请求方式为GET m_url = 0; // 获取一个目标URL m_version = 0; m_content_length = 0; m_host = 0; m_start_line = 0; m_checked_idx = 0; m_read_idx = 0; m_write_idx = 0; bzero(m_read_buf, READ_BUFFER_SIZE); bzero(m_write_buf, READ_BUFFER_SIZE); bzero(m_real_file, FILENAME_LEN); } // 循环读取客户数据,直到无数据可读或者对方关闭连接 bool http_conn::read() { if( m_read_idx >= READ_BUFFER_SIZE ) { return false; } int bytes_read = 0; /* 协议接收的数据可能大于buf的长度,所以在这种情况下要调用几次recv函数才能把套接字接收缓冲区中的数据copy完 如果是阻塞套接字,套接字缓冲区中没有任何数据时,recv就会等待,直到数据>=1, 如果是非阻塞套接字,网卡缓冲区中没有数据时,recv也会立即返回。 非阻塞必须循环读取,确保读尽 */ /*使用while循环的原因 边缘触发的情况下,如果不一次性读取一个事件上的数据,会干扰下一个事件 所以必须在读取数据的外部套一层循环,这样才能完整的读取数据 */ while(true) { //非阻塞套接字,recv是非阻塞的 如果应用层的数组满了怎么办 ??? // 从m_read_buf + m_read_idx索引出开始保存数据,大小是READ_BUFFER_SIZE - m_read_idx bytes_read = recv(m_sockfd, m_read_buf + m_read_idx, READ_BUFFER_SIZE - m_read_idx, 0 ); /*如果是阻塞IO,处理完数据后,程序会一直卡在recv上,因为是阻塞IO,如果没数据可读,它会一直等在那, 直到有数据可读。但是这个时候,如果有另外一个客户端取连接服务器,服务器就不能受理这个新的客户端了。 */ /* 所以把socket设置为非阻塞,没有数据可读时,会立即返回,并设置errno. 在边沿模式下,必须是非阻塞的 */ if (bytes_read == -1) { /* //EAGIN,又叫EWOULDBLOCK ,提示应用程序现在没有数据可读,请稍后再试 */ if( errno == EAGAIN || errno == EWOULDBLOCK ) { // 没有数据 break;//退出循环 } return false; //出错 } else if (bytes_read == 0) { // 对方关闭连接 return false; } m_read_idx += bytes_read; } return true; } // 解析一行,判断依据\r\n,每一行都是以回车换行符结束 http_conn::LINE_STATUS http_conn::parse_line() { char temp; for ( ; m_checked_idx < m_read_idx; ++m_checked_idx ) { temp = m_read_buf[ m_checked_idx ]; if ( temp == '\r' ) { if ( ( m_checked_idx + 1 ) == m_read_idx ) { return LINE_OPEN; //(以\r结尾,没有换行符)行数据尚且不完整 } else if ( m_read_buf[ m_checked_idx + 1 ] == '\n' ) { //\r\n m_read_buf[ m_checked_idx++ ] = '\0'; //把\r->\0 //标志着这是一行 m_read_buf[ m_checked_idx++ ] = '\0'; //把\n->\0 //m_checked_idx此时指向\n的下一个字符 return LINE_OK; //读取到一个完整的行 } return LINE_BAD; //行出错 } else if( temp == '\n' ) { if( ( m_checked_idx > 1) && ( m_read_buf[ m_checked_idx - 1 ] == '\r' ) ) { m_read_buf[ m_checked_idx-1 ] = '\0'; m_read_buf[ m_checked_idx++ ] = '\0'; return LINE_OK; } return LINE_BAD; } } return LINE_OPEN; } // 解析HTTP请求行,获得请求方法,目标URL,以及HTTP版本号 http_conn::HTTP_CODE http_conn::parse_request_line(char* text) { // GET /index.html HTTP/1.1 m_url = strpbrk(text, " \t"); // 判断第二个参数中的字符哪个在text中最先出现 if (! m_url) { return BAD_REQUEST; } // GET\0/index.html HTTP/1.1 *m_url++ = '\0'; // 置位空字符,字符串结束符 char* method = text; if ( strcasecmp(method, "GET") == 0 ) { // 忽略大小写比较 m_method = GET; } else { return BAD_REQUEST; } // /index.html HTTP/1.1 // 检索字符串 str1 中第一个不在字符串 str2 中出现的字符下标。 m_version = strpbrk( m_url, " \t" ); if (!m_version) {//若返回空 return BAD_REQUEST; } *m_version++ = '\0'; //把\t->\0,向前走一步 if (strcasecmp( m_version, "HTTP/1.1") != 0 ) { return BAD_REQUEST; //忽略大小写比较字符串,相同返回0 } /** * http://192.168.110.129:10000/index.html */ if (strncasecmp(m_url, "http://", 7) == 0 ) { m_url += 7; // 在参数 str 所指向的字符串中搜索第一次出现字符 c(一个无符号字符)的位置。 m_url = strchr( m_url, '/' ); } if ( !m_url || m_url[0] != '/' ) { return BAD_REQUEST; } m_check_state = CHECK_STATE_HEADER; // 检查状态变成检查头 return NO_REQUEST;// 请求不完整,需要继续读取客户数据,需要继续读取头 } // 解析HTTP请求的一个头部信息(字符串匹配,记录下一些一些字段的值) http_conn::HTTP_CODE http_conn::parse_headers(char* text) { // 遇到空行,表示头部字段解析完毕 if( text[0] == '\0' ) { //那一行为\0 // 如果HTTP请求有消息体,则还需要读取m_content_length字节的消息体, // 状态机转移到CHECK_STATE_CONTENT状态 if ( m_content_length != 0 ) { m_check_state = CHECK_STATE_CONTENT; return NO_REQUEST; } // 否则说明我们已经得到了一个完整的HTTP请求 return GET_REQUEST; } else if ( strncasecmp( text, "Connection:", 11 ) == 0 ) { // 处理Connection 头部字段 Connection: keep-alive text += 11; text += strspn( text, " \t" ); if ( strcasecmp( text, "keep-alive" ) == 0 ) { m_linger = true; } } else if ( strncasecmp( text, "Content-Length:", 15 ) == 0 ) { // 处理Content-Length头部字段 text += 15; text += strspn( text, " \t" ); m_content_length = atol(text); } else if ( strncasecmp( text, "Host:", 5 ) == 0 ) { // 处理Host头部字段 text += 5; text += strspn( text, " \t" ); m_host = text; } else { printf( "oop! unknow header %s\n", text );//其他的一切看作未知的 } return NO_REQUEST; //没有换状态 } // 我们没有真正解析HTTP请求的消息体,只是判断它是否被完整的读入了 http_conn::HTTP_CODE http_conn::parse_content( char* text ) { if ( m_read_idx >= ( m_content_length + m_checked_idx ) ) { text[ m_content_length ] = '\0'; return GET_REQUEST; } return NO_REQUEST; } // 主状态机,解析请求 http_conn::HTTP_CODE http_conn::process_read() { //初始化,行 LINE_STATUS line_status = LINE_OK; HTTP_CODE ret = NO_REQUEST; char* text = 0; /* parse_line:从数组中读取一行,返回读取一行的三种状态 */ while (((m_check_state == CHECK_STATE_CONTENT) && (line_status == LINE_OK)) || ((line_status = parse_line()) == LINE_OK)) { //根据\r\n获取一行数据,置为'\0',并得到读完该行的状态 // 获取一行数据 text = get_line(); //获取当前行的开始索引 m_start_line = m_checked_idx;//下一行的开始索引 printf( "got 1 http line: %s\n", text ); /* m_check_state = CHECK_STATE_REQUESTLINE; // 初始状态为检查请求行 */ //先读取一行文本,根据主状态机的状态去分别进行不同的处理 switch ( m_check_state ) { case CHECK_STATE_REQUESTLINE: { //检查请求行 ret = parse_request_line( text ); //检查状态变成检查头,return NO_REQUEST. if ( ret == BAD_REQUEST ) { return BAD_REQUEST; } break; } case CHECK_STATE_HEADER: { //检查请求头部字段 ret = parse_headers( text ); if ( ret == BAD_REQUEST ) { return BAD_REQUEST; } else if ( ret == GET_REQUEST ) { return do_request(); //请求解析完了,去回复 } break; } case CHECK_STATE_CONTENT: {//当前正在解析请求体 ret = parse_content( text ); if ( ret == GET_REQUEST ) { return do_request(); //没有真正解析消息体,去回复 } line_status = LINE_OPEN; break; } default: { return INTERNAL_ERROR; } } } return NO_REQUEST; } // 当得到一个完整、正确的HTTP请求时,我们就分析目标文件的属性, // 如果目标文件存在、对所有用户可读,且不是目录,则使用mmap将其 // 映射到内存地址m_file_address处,并告诉调用者获取文件成功 http_conn::HTTP_CODE http_conn::do_request() { // "/home/nowcoder/webserver/resources" strcpy( m_real_file, doc_root ); // 字符串复制 b->a int len = strlen( doc_root ); strncpy( m_real_file + len, m_url, FILENAME_LEN - len - 1 ); // 获取m_real_file文件的相关的状态信息,-1失败,0成功 //通过文件名filename获取文件信息,并保存在buf所指的结构体stat中 if ( stat( m_real_file, &m_file_stat ) < 0 ) { return NO_RESOURCE; } // 判断访问权限 if ( ! ( m_file_stat.st_mode & S_IROTH ) ) { return FORBIDDEN_REQUEST;//表示客户对资源没有足够的访问权限 } // 判断是否是目录 if ( S_ISDIR( m_file_stat.st_mode ) ) { return BAD_REQUEST; } // 以只读方式打开文件 int fd = open( m_real_file, O_RDONLY ); // 创建内存映射 文件被映射到内存的起始位置,将一个文件或者其他对象映射进内存 m_file_address = ( char* )mmap( 0, m_file_stat.st_size, PROT_READ, MAP_PRIVATE, fd, 0 ); close( fd ); return FILE_REQUEST; //获取文件成功 } // 对内存映射区执行munmap操作 void http_conn::unmap() { if( m_file_address ) { munmap( m_file_address, m_file_stat.st_size ); m_file_address = 0; } } // 写HTTP响应 bool http_conn::write() { int temp = 0; //int bytes_have_send = 0; // 已经发送的字节 //int bytes_to_send = m_write_idx;// 将要发送的字节 (m_write_idx)写缓冲区中待发送的字节数 //已经准备好的数据初始化 bytes_to_send = m_write_idx + m_file_stat.st_size; //增加一些判断 //1. 判断响应头是否发送完毕,如果发送完毕了,要做如下处理 if(bytes_have_send >= m_iv[0].iov_len){ //头已经发送完毕 m_iv[0].iov_len = 0; m_iv[1].iov_base = m_file_address+(bytes_have_send-m_write_idx); m_iv[1].iov_len = bytes_to_send; } //如果没有发送完毕,还要修改下次写数据的位置 else{ m_iv[0].iov_base = m_write_buf + bytes_have_send; m_iv[0].iov_len = m_iv[0].iov_len -bytes_have_send; } if ( bytes_to_send <= 0 ) { // 将要发送的字节为0,这一次响应结束。 /* event.events = ev | EPOLLET | EPOLLONESHOT | EPOLLRDHUP; //边沿触发,ONESHOT事件,对端连接断开会触发EPOLLRDHUP */ modfd( m_epollfd, m_sockfd, EPOLLIN ); //手动触发读 init(); return true; } while(1) { // 分散写 temp = writev(m_sockfd, m_iv, m_iv_count);//和write相同,除了数据取自IOVEC,而不是连续缓冲区 if ( temp <= -1 ) { // 如果TCP socket写缓冲没有空间,则等待下一轮EPOLLOUT事件,虽然在此期间, // 服务器无法立即接收到同一客户的下一个请求,但可以保证连接的完整性。 if( errno == EAGAIN ) { modfd( m_epollfd, m_sockfd, EPOLLOUT ); //再次触发写 return true; } //出错 unmap(); return false; } bytes_to_send -= temp; bytes_have_send += temp; if ( bytes_to_send <= bytes_have_send ) { // 发送HTTP响应成功,根据HTTP请求中的Connection字段决定是否立即关闭连接 unmap(); // if(m_linger) { //HTTP请求是否要求保持连接 init(); modfd( m_epollfd, m_sockfd, EPOLLIN ); //继续监测读事件 return true; } else { modfd( m_epollfd, m_sockfd, EPOLLIN ); return false; } } } } // 往写缓冲中写入待发送的数据 //add_response( "%s %d %s\r\n", "HTTP/1.1", status, title ); bool http_conn::add_response( const char* format, ... ) { if( m_write_idx >= WRITE_BUFFER_SIZE ) { return false; } va_list arg_list; //定义临时变量 va_start( arg_list, format ); //指定位置,把这个“空指针”指定到我们需要的位置上 //将输出格式化输出到一个字符数组中 int len = vsnprintf( m_write_buf + m_write_idx, WRITE_BUFFER_SIZE - 1 - m_write_idx, format, arg_list ); if( len >= ( WRITE_BUFFER_SIZE - 1 - m_write_idx ) ) { return false; } m_write_idx += len; va_end( arg_list ); //指针置空 return true; } //add_status_line( 500, error_500_title ); //add_status_line(200, ok_200_title ); bool http_conn::add_status_line( int status, const char* title ) { return add_response( "%s %d %s\r\n", "HTTP/1.1", status, title ); } bool http_conn::add_headers(int content_len) { add_content_length(content_len); add_content_type(); add_linger(); add_blank_line(); return true; } bool http_conn::add_content_length(int content_len) { return add_response( "Content-Length: %d\r\n", content_len ); } bool http_conn::add_linger() { return add_response( "Connection: %s\r\n", ( m_linger == true ) ? "keep-alive" : "close" ); } bool http_conn::add_blank_line() { return add_response( "%s", "\r\n" ); } bool http_conn::add_content( const char* content ) { return add_response( "%s", content ); } bool http_conn::add_content_type() { return add_response("Content-Type:%s\r\n", "text/html"); } // 根据服务器处理HTTP请求的结果,决定返回给客户端的内容 /* HTTP响应报文格式: 状态行: 协议版本\space状态码\space状态码描述\r\n 响应头部 响应正文 */ bool http_conn::process_write(HTTP_CODE ret) { switch (ret) { case INTERNAL_ERROR: //表示服务器内部错误 add_status_line( 500, error_500_title ); //写到写缓冲区 add_headers( strlen( error_500_form ) ); if ( ! add_content( error_500_form ) ) { return false; } break; case BAD_REQUEST: add_status_line( 400, error_400_title ); add_headers( strlen( error_400_form ) ); if ( ! add_content( error_400_form ) ) { return false; } break; case NO_RESOURCE: add_status_line( 404, error_404_title ); add_headers( strlen( error_404_form ) ); if ( ! add_content( error_404_form ) ) { return false; } break; case FORBIDDEN_REQUEST: add_status_line( 403, error_403_title ); add_headers(strlen( error_403_form)); if ( ! add_content( error_403_form ) ) { return false; } break; case FILE_REQUEST: //表示文件获取成功 add_status_line(200, ok_200_title ); add_headers(m_file_stat.st_size); //两个地址,一个是写缓冲区的地址;一个是请求文件映射到内存的地址 m_iv[ 0 ].iov_base = m_write_buf;//写缓冲区地址 m_iv[ 0 ].iov_len = m_write_idx;//偏移量 m_iv[ 1 ].iov_base = m_file_address;// 客户请求的目标文件被mmap到内存中的起始位置 m_iv[ 1 ].iov_len = m_file_stat.st_size;//大小 m_iv_count = 2; //响应头的大小+文件的大小,也就是总的要发送的数据 bytes_to_send = m_write_idx + m_file_stat.st_size; return true; default: return false; } m_iv[ 0 ].iov_base = m_write_buf; m_iv[ 0 ].iov_len = m_write_idx; m_iv_count = 1; return true; } // 由线程池中的工作线程调用,这是处理HTTP请求的入口函数 void http_conn::process() { // 解析HTTP请求 HTTP_CODE read_ret = process_read(); if ( read_ret == NO_REQUEST ) {//请求不完整,需要继续读取客户数据 modfd( m_epollfd, m_sockfd, EPOLLIN ); //重新检测读,手动再次触发读 return; } // 生成响应 //两个地址,一个是写缓冲区的地址,一个是文件被映射到内存中的地址 //将数据先到缓冲区中 bool write_ret = process_write( read_ret ); if ( !write_ret ) { close_conn(); } modfd( m_epollfd, m_sockfd, EPOLLOUT); //触发写事件,需要触发写时,再把写加入进去 }
[ "18738980993@163.com" ]
18738980993@163.com
505c03de334e29292f19d8a49faab5ced9018be2
380520b9b0a39618f216f70453f73e849798b554
/LiveStreamingPlatform/beautify/filter.cpp
b3d33471f8b36f4eedca084a1bb48639ce78d858
[]
no_license
tayduivn/LiveStreamingPlatform
e151a239c60353908e0fd5cc19d2fa7a488ae80f
604edf7f8b5453afb094c9fada9dcfa09e5b102e
refs/heads/main
2023-02-05T15:30:07.133970
2020-12-26T14:11:45
2020-12-26T14:11:45
344,164,330
3
0
null
2021-03-03T15:00:14
2021-03-03T15:00:13
null
UTF-8
C++
false
false
598
cpp
#include "filter.h" #include "bilateralfilter.h" #include <iostream> using namespace std; Filter *Filter::Get(FilterType type) { static BilateralFilter bilateralFilter; switch (type) { case BILATERAL: return &bilateralFilter; break; default: break; } return nullptr; } bool Filter::Set(string key, double value) { if (params.find(key) == params.end()) { cout << "para " << key << " is not support!" << endl; return false; } params[key] = value; return true; } Filter::~Filter() { } Filter::Filter() { }
[ "andywang0607@gmail.com" ]
andywang0607@gmail.com
d100f347c7773a8c1abbe25724ffccd60daf4268
38de77c2686edbf71ef3318fce6ba845f3447399
/staircase.cpp
267c9738cfc08fdb22053bc782bce6dfdfa6f090
[]
no_license
AnikaLimaa/Problem-Solving
946475f82587c85ec2a814b89a307ae0e96e5801
2f91e8b563c15daaca82870a1294c3cafc4732df
refs/heads/master
2022-12-29T23:08:39.956346
2020-09-30T02:49:50
2020-09-30T02:49:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
761
cpp
#include<iostream> #include <bits/stdc++.h> #define MOD 10000000007 using namespace std; int dp[100001], n; int count_paths(int i) { if(i == 0) return 1; if(i < 0) return 0; if(dp[i] != -1) return dp[i]; cout<<"b "<<dp[i]<<endl; dp[i] = count_paths(i - 1) % MOD; cout<<"A "<<dp[i]<<endl; //dp[i] = (dp[i] + count_paths(i - 2)) % MOD; //cout<<dp[i]<<endl; //dp[i] = (dp[i] + count_paths(i - 3)) % MOD; //cout<<dp[i]<<endl; return dp[i]; } int main() { int t; cin >> t; // assert(t >=1 and t<= 5); for(int i = 0; i < t; i++) { cin >> n; // assert(n >= 1 and n <= 100000); memset(dp, -1, sizeof dp); int ans = count_paths(n); cout <<"Ans"<< ans << endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
edf223e5e8b6029f72591c568436eda8f371464d
d551b222f1678e68b703a59b0641663bfa0559c6
/particle.h
6ae303599d0551358cd17556e5b5c7036a545720
[ "MIT" ]
permissive
314arhaam/FPSE
22b4312ff225c57035abc1dd656227a645cc72f4
808af7816b8b598988d7733d0099287032f4fd5b
refs/heads/master
2021-09-10T01:18:53.260521
2018-03-20T13:54:29
2018-03-20T13:54:29
126,024,954
4
0
null
null
null
null
UTF-8
C++
false
false
1,940
h
// // particle.hpp // DPM // // Created by Parham Abbasi on 3/15/18. // Copyright © 2018 Parham Abbasi. All rights reserved. // #ifndef particle_h #define particle_h #include <stdio.h> #include <cmath> #include "geometry.h" #include "collision.h" struct list{ double T; int a; char* s; }; struct Geom{ double length = 2; double width = 2; } geom; class particle{ public: //geometry *gPtr; double x, y, radius, u, v, omega, density, volume, momentOfInertia, Mass, eps_w = 0.8, eps_p = 0.8, velocityVector[2], *vPtr; /*Constructor of particle*/ particle(){ } particle( double X, double Y, //geometry *A, double Radius = 0.01, double U = 0, double V = 0, double Omega = 0, double Density = 2600 ) { x = X; y = Y; u = U; v = V; radius = Radius; density = Density; omega = Omega; velocityVector[0] = u; velocityVector[1] = v; vPtr = velocityVector; this->physicalProps(); } void move(double dt){ this->x += this->u*dt; this->y += this->v*dt; //std::cout<<"\nv = "<<y; } list nearestWall(){ list L; double wallTime[4]; double U[4] = { -this->u, this->u, -this->v, this->v }; double D[4] = { this->x - this->radius, -this->x + 3 - this->radius, this->y - this->radius, -this->y + 8 - this->radius}; for (int i = 0; i < 4; i++){ wallTime[i] = utility::utd(D[i], U[i]); } L.a = utility::argMin(wallTime, 4); L.T = wallTime[L.a]; return L; } private: void physicalProps(){ volume = (4/3)*M_PI*pow(radius, 3); Mass = density*volume; momentOfInertia = 0.4*Mass*pow(radius, 2); } }; #endif /* particle_h */
[ "noreply@github.com" ]
noreply@github.com
70393bd4020d7a645525038c74580ecd3061de6e
b5d067cb8d376b3f51c9764bc7e96992bbaea324
/hw_lab/10/main_my.cpp
d474eb71340b184c401fa91944343c56478500af
[]
no_license
daidianlizi/AdvProgramProbSov_CS253
5b40d14ddd73fefeea0ae2f1172c04aa19b4f699
e2c098a1aeed5af6db4f555c407c81304ce0fdf2
refs/heads/master
2020-05-23T18:10:08.025024
2019-05-15T19:19:29
2019-05-15T19:19:29
186,882,846
0
0
null
null
null
null
UTF-8
C++
false
false
416
cpp
#include <iostream> #include <vector> #include <cmath> #include <string> #include <unordered_map> using namespace std; int main() { int MyMax = 4000000; int num1 = 1; int num2 = 2; int sum = 0; int tmp; while (num1 < MyMax){ if (num1%2 == 0){ sum += num1; } tmp = num2 + num1; num1 = num2; num2 = tmp; } cout<<sum; return 0; }
[ "wmhdyd@163.com" ]
wmhdyd@163.com
33d0b5ff64955596a8dd02aaf258a5a67154ee71
29021572353d0591f332e946009befe8fb826c11
/include/map3.h
2955e74934bb18fa817c0bdaaeeef5a70d58aa4d
[]
no_license
qiwen98/Sokoban-Game-Solver-
d0717008a48a266d30875cc4a256a42ff888cb5c
bc64fac4a219a20a64c4bea92d4d3087cdf6a4e2
refs/heads/master
2020-04-29T10:37:30.005276
2019-03-17T07:12:02
2019-03-17T07:12:02
176,067,809
1
0
null
null
null
null
UTF-8
C++
false
false
448
h
#ifndef MAP3_H #define MAP3_H #define map_x_Size 25 #define map_y_Size 25 #define person_init_position_x 13 #define person_init_position_y 6 #define box_init_position_x {22,9,20} #define box_init_position_y {21,19,2} #define final_point_x {4,9,2} #define final_point_y {10,12,3} #define boxnumbersetting 3 #include<iostream> using namespace std; void mapcalling(int m, int n ,int map[][map_x_Size]); #endif // MAP3_H
[ "noreply@github.com" ]
noreply@github.com
005165811771f009af87d891bf283b5f47c243f1
4fdc7e69abfc3b22ae4afb3be7cc8fcccf3d6ba7
/main.cpp
1b49c898cecc8b55e457a74127765ce94e704e3e
[]
no_license
20chupin/Morse_Devoir
a5ce9d24a06d8f8d7903716fe89358d31e23311b
62243819ebcb98fc22ed01b8a4b0aab050baa7b0
refs/heads/main
2023-02-20T01:20:06.982940
2021-01-23T13:00:32
2021-01-23T13:00:32
330,133,753
0
0
null
null
null
null
UTF-8
C++
false
false
3,726
cpp
#include <iostream> #include "texte.h" #include "audio.h" using namespace std; void encodeur_decodeur(int argc, char **argv) { if (argc == 1) { throw string("Pour un encodage (français vers morse): \nLe premier argument doit être E \nLe deuxième argument doit être une phrase composée de lettre majuscules, et/ou des caractères '.', ',', '?' \n\nPour un décodage (morse vers français): \nLe premier argument doit être D \nLe deuxième argument doit être le nom du fichier wave à analyser" ); } else if (argv[1][0] != 'E' and argv[1][0] != 'D') { throw string("Pour un encodage (français vers morse): \nLe premier argument doit être E \nLe deuxième argument doit être une phrase composée de lettre majuscules, et/ou des caractères '.', ',', '?' \n\nPour un décodage (morse vers français): \nLe premier argument doit être D \nLe deuxième argument doit être le nom du fichier wave à analyser" ); } // Encodage else if (argv[1][0] == 'E') { // On récupère la phrase à traduire string a_traduire = ""; for (int i = 2; i < argc; i++) { a_traduire += (string)argv[i]; a_traduire += " "; } // Encodage en morse écrit texte txt('F', a_traduire); txt.encode(); //Encodage en morse audio dans traduction.wav audio aud; aud.m_to_s(txt.morse_getter()); cout<<"La traduction en morse se trouve dans le fichier audio traduction.wav"<<endl; } //Décodage else if (argv[1][0] == 'D') { //Décodage en morse écrit (ne marche qu'avec exemple prof) audio aud; aud.s_to_m(argv[2]); string mrs = aud.morse_texte_getter(); //Décodage en français écrit texte txt('M', aud.morse_texte_getter()); txt.decode(); cout<<txt.francais_getter()<<endl; } } void e_d_gestion_d_erreur(int argc, char **argv) { try { encodeur_decodeur(argc, argv); } catch(string const& chaine) { cerr << chaine << endl; } } void tests() { // Test de la partie traduction écrite cout << "Test de la partie traduction écrite :" << endl; string ascii_string_ori = "HELLO WORLD"; string ascii_string = ascii_string_ori; string morse_string; // Affichage valeur de départ cout << "ascii : " << ascii_string << endl; // Encodage texte F('F', ascii_string); F.encode(); morse_string = F.morse_getter(); cout << "encodage morse : " << morse_string << endl; // Décodage texte M('M', morse_string); M.decode(); ascii_string = M.francais_getter(); cout << "decodage morse : " << ascii_string << endl; // Test if (ascii_string == ascii_string_ori) { cout << "Peut-être ok..." << endl << endl; } else { cout << "nok" << endl << endl; } // Test décodage complet cout << "Test du décodage complet de 'exemple_prof.wav' :" << endl; char* exe = "exe"; char* E_or_D = "D"; char* a_traduire = "exemple_prof.wav"; char* argv[3] = {exe, E_or_D, a_traduire}; cout << "'e_d_gestion_d_erreur' devrait afficher 'SOS SOS' et il affiche : " << endl; e_d_gestion_d_erreur(3, argv); cout << endl; // Test encodage complet cout << "Test de l'encodage complet de 'HELLO WORLD.' :" << endl; E_or_D = "E"; a_traduire = "HELLO WORLD."; argv[1] = E_or_D; argv[2] = a_traduire; e_d_gestion_d_erreur(3, argv); cout << endl; } int main(int argc, char **argv) { // Commenter une des deux lignes suivantes //tests(); e_d_gestion_d_erreur(argc, argv); return 0; }
[ "amandine.chupin@mines-paritech.fr" ]
amandine.chupin@mines-paritech.fr
d6e6cd21621353d0517750b2a6fbe4c1eb95baaf
22212b6400346c5ec3f5927703ad912566d3474f
/src/Kernel/DecoderInterfacePointer.h
90a8e252b511a7b113287f75527a853c8e776323
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
irov/Mengine
673a9f35ab10ac93d42301bc34514a852c0f150d
8118e4a4a066ffba82bda1f668c1e7a528b6b717
refs/heads/master
2023-09-04T03:19:23.686213
2023-09-03T16:05:24
2023-09-03T16:05:24
41,422,567
46
17
MIT
2022-09-26T18:41:33
2015-08-26T11:44:35
C++
UTF-8
C++
false
false
172
h
#pragma once #include "Interface/DecoderInterface.h" #include "Kernel/Pointer.h" namespace Mengine { typedef PointerT<DecoderInterfacePtr> DecoderInterfacePointer; }
[ "irov13@mail.ru" ]
irov13@mail.ru
5ca195ec67822a753c9d94a69a7bc60ac579d17c
ba7c8de14263ec4aaa4e8a1f591e8996f1629000
/Fig8-Geodesic/CompareDistance.cpp
420c0370041b06f4173418cdf3586b644b7e187a
[ "BSD-3-Clause" ]
permissive
PeterZs/AADR
42495616a6a84eadf58936414e4a99362bb99b66
ed19730fc56f5d019089dbfd7544eeb35ba9c9a2
refs/heads/master
2022-11-05T17:09:42.841523
2020-06-25T20:46:49
2020-06-25T20:46:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,041
cpp
// BSD 3-Clause License // // Copyright (c) 2019, Jiong Tao, Bailin Deng, Yue Peng // 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 copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "Parameters.h" #include "DistanceFile.h" #include <iostream> void shift_and_normalize_distance(const std::vector<int> &source_vtx, DenseVector &dist_values) { double mean_source_dist = 0; for(int i = 0; i < static_cast<int>(source_vtx.size()); ++ i){ mean_source_dist += dist_values(source_vtx[i]); } mean_source_dist /= double(source_vtx.size()); DenseVector source_dist; source_dist.setConstant(dist_values.size(), mean_source_dist); dist_values -= source_dist; dist_values /= dist_values.maxCoeff(); } int main(int argc, char* argv[]) { if(argc != 4){ std::cerr << "Usage: CompareDistance PARAMETERS_FILE DISTANCE_FILE REFERENCE_DISTANCE_FILE" << std::endl; return 1; } Parameters param; if(!param.load(argv[1])){ std::cerr << "Error: unable to load parameter file" << std::endl; return 1; } DenseVector distance, ref_distance; if(!DistanceFile::load(argv[2], distance)){ std::cerr << "Error: unable to read distance values from file " << argv[2] << std::endl; return 1; } if(!DistanceFile::load(argv[3], ref_distance)){ std::cerr << "Error: unable to read distance values from file " << argv[3] << std::endl; return 1; } if(distance.size() != ref_distance.size()){ std::cerr << "Error: different length of input distance arrays" << std::endl; } int n_vtx = distance.size(); for(int i = 0; i < static_cast<int>(param.source_vertices.size()); ++ i){ if(param.source_vertices[i] >= n_vtx){ std::cerr << "Error: source vertex index " << param.source_vertices[i] << " is out of bound" << std::endl; return 1; } } // Shift distance array such that the value at sources become zero shift_and_normalize_distance(param.source_vertices, distance); shift_and_normalize_distance(param.source_vertices, ref_distance); // Compute mean error double err = 0; double eps = 1e-14; std::vector<bool> source_flag(n_vtx, false); for(int i = 0; i < static_cast<int>(param.source_vertices.size()); ++ i){ source_flag[param.source_vertices[i]] = true; } for(int i = 0; i < n_vtx; ++ i){ if((!source_flag[i]) && (std::fabs(ref_distance(i)) > eps)){ err += std::fabs(distance(i) - ref_distance(i))/std::fabs(ref_distance(i)); } } err /= double(n_vtx - param.source_vertices.size()); std::cout << "Mean relative error: " << (err*100) << "%" << std::endl; return 0; }
[ "echoyue@mail.ustc.edu.cn" ]
echoyue@mail.ustc.edu.cn
5231f1495c5776b86e4133fa7013aa7bb68ef876
129ef5a7d2f7d307f906d295f54d94616511492d
/ReqTheoryList.cpp
923c374a668c5123eb71b262bd90ee8a008d33bc
[]
no_license
induvellanki/Degree_Progression
4bafc5d5e13ec13fec29a03e5c7c7f0d76ebfbb8
c0901081ba6450fb76f35ca19c68e871fa71d402
refs/heads/main
2023-04-11T23:14:38.894700
2021-04-25T23:17:23
2021-04-25T23:17:23
361,559,397
1
0
null
null
null
null
UTF-8
C++
false
false
980
cpp
#include "ReqTheoryList.h" #include <fstream> #include <sstream> #include <vector> #include <iostream> using namespace std; // When object created --> vector built from courses in corr. file ReqTheoryList::ReqTheoryList () { ifstream input_file; input_file.open("theory_inventory.txt"); string short_name, long_name; int course_credits; string temp, temp_credits; while (getline(input_file, temp)) { stringstream ss(temp); getline(ss, short_name, ','); getline(ss, long_name, ','); getline(ss, temp_credits); course_credits = stoi(temp_credits); ReqTheory theory_req(short_name, long_name, course_credits); theory_list.push_back(theory_req); } input_file.close(); } vector<ReqTheory> ReqTheoryList::get_theory_list() { return theory_list; } int ReqTheoryList::get_size() { return theory_list.size(); } ReqTheory& ReqTheoryList::operator[] (int num) { return theory_list[num]; }
[ "induvellanki@Indus-MacBook-Pro.local" ]
induvellanki@Indus-MacBook-Pro.local
39d2cc4f5407a9803787c97a1d1944727fa013fb
05dd6c56b0c3e36c3230a620ce63b9b62e93ba8e
/Task/10/Homework10-8.cpp
d5fda19b3041e00d762f1c8d97263b2178cb301c
[]
no_license
jckling/Learn-C
3b37d819ff9c40c79991a07dfcbe809e380a47c2
56d8c8a47ccb371d627cc6ff39ca5fda66496316
refs/heads/master
2021-01-01T04:03:50.851823
2019-07-07T06:07:05
2019-07-07T06:07:05
97,115,103
3
1
null
null
null
null
UTF-8
C++
false
false
522
cpp
#include<stdio.h> #include<stdlib.h> #include<math.h> int Prime(int x); void Pri(int x); int main() { int a; scanf("%d", &a); if (a <= 4) Pri(4); else Pri(a); return 0; } int Prime(int x) { int i; int flag; double n; flag = 1; n = sqrt(x); for (i = 2; i <= n; i++) { if (x % i == 0) { flag = 0; break; } } return flag; } void Pri(int x) { int i, j; j = 0; for (i = 2; i <= x; i++) { if (Prime(i)) { printf("%8lu", i); j++; if (j % 5 == 0) printf("\n"); } } }
[ "jckling@163.com" ]
jckling@163.com
b7c5e4bc4461fd09251fbfcd35c1f30d56c1ab3e
ff339f20057c5293f3f0968fe9bbf5e494160cba
/src/windows/grayscaledialog.h
5792eaa48ba6452574822ae1c4b89c7ae36c6886
[]
no_license
czlowiekimadlo/PTO-2011
344fa570a87503591bb57bd2c17a00fecbba1035
a80589643c1aa2cbd1e226e43ea765e391c75d1d
refs/heads/master
2021-03-12T19:25:26.266898
2012-05-21T17:40:05
2012-05-21T17:40:05
2,607,747
0
1
null
null
null
null
UTF-8
C++
false
false
506
h
#ifndef GRAYSCALEDIALOG_H #define GRAYSCALEDIALOG_H #include <QDialog> #include "../mainwindow.h" #include "../commands/grayscalecommand.h" class MainWindow; namespace Ui { class GrayscaleDialog; } class GrayscaleDialog : public QDialog { Q_OBJECT public: explicit GrayscaleDialog(MainWindow *parent = 0); ~GrayscaleDialog(); MainWindow * mainWindow; private slots: void on_buttonBox_accepted(); private: Ui::GrayscaleDialog *ui; }; #endif // GRAYSCALEDIALOG_H
[ "quak@tlen.pl" ]
quak@tlen.pl
08c79ed3d7df32b9e0c46d674523a007559ee55f
09ae08381c4aa0d6faf1117f9a80121250f6620b
/SCCC/1일차/10814.cpp
df3892836145fab7b58a9ffa64850abe6fde2f6a
[]
no_license
tony9402/SCCC_Study
cdfe1dc26bc67c50dc187687a5e176db77f70cc6
fd31bb9d7fe0021878ecd8f1d8ea1f07d78c7172
refs/heads/master
2020-04-15T06:38:57.073288
2019-08-30T12:02:32
2019-08-30T12:02:32
164,467,703
0
0
null
null
null
null
UHC
C++
false
false
495
cpp
//stable sort로도 풀어보기 #include<string> #include<iostream> #include<vector> #include<tuple> #include<algorithm> using namespace std; vector<tuple<int, int, string>> vc; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; for (int i = 0; i < n; i++) { int n; string name; cin >> n >> name; vc.push_back(make_tuple(n, i, name)); } sort(vc.begin(), vc.end()); for (auto i : vc) { cout << get<0>(i) << ' ' << get<2>(i) << '\n'; } return 0; }
[ "tony9402@naver.com" ]
tony9402@naver.com
b4378d7eba0f7b8299d168713e6159d3dd701176
fbafa7ea0c999471cf9fc42efc4388b2b2fac7d3
/Lab 10_2/Player.h
1c35e319bb3c0344c123ca609dd64807b4223c54
[]
no_license
ofthedove/cecs130
e914629eee287abd7cc22b992a4c4cf5595e4303
384f4eebd74d3878108cc9534e62ec344903b93d
refs/heads/master
2020-05-09T12:21:07.727021
2019-04-13T02:21:36
2019-04-13T02:21:36
181,109,212
0
0
null
null
null
null
UTF-8
C++
false
false
149
h
#ifndef PLAYER_H #define PLAYER_H #include "Board.h" class Player { bool isXPlayer; public: virtual void playTurn(Board) = 0; }; #endif
[ "andrewcombs13@gmail.com" ]
andrewcombs13@gmail.com
bc84820bdbcc4340a76e13271dda93ed522a661f
557fee5f3ed1730f0a46505ea41553c194192575
/AnimNotify/object/BaseDmgColActor.h
47978e2db8504ce87a88ddb143aee7ece09837d2
[]
no_license
DasomKong/UE4_SourceArchive
e39f16a7897d02a2434f5e1b336400568f5d3bff
38c6df0e4bb3d2b69bb1f524302ea4d7f5275da2
refs/heads/master
2022-12-17T17:33:19.129011
2020-09-22T03:08:10
2020-09-22T03:08:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,320
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "../../JHPTypes.h" #include "BaseDmgColActor.generated.h" UCLASS() class PROJECTA_API ABaseDmgColActor : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ABaseDmgColActor(); virtual void BeginPlay() override; void whenOverlapped(AActor* otherActor, UPrimitiveComponent* otherComp); virtual void doWhenSpawn() { SetLifeSpan(remainTime); } UFUNCTION() void OnOverlapBegin(class UPrimitiveComponent* OverlappedComponent, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult); protected: const bool giveDmg(const AActor* target, const float dmg); virtual void lastProcess(){} public: UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = DmgCol) float remainTime; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = DmgCol) FBattleData battleData; }; UCLASS() class PROJECTA_API ASimpleCol: public ABaseDmgColActor { GENERATED_BODY() public: ASimpleCol(); virtual void BeginPlay() override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason); virtual void doWhenSpawn() override; public: UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = SimpleCol) class USphereComponent* sphereCol; UPROPERTY(BlueprintReadOnly, Category = SimpleCol) float flickeringTime; UPROPERTY(BlueprintReadOnly, Category = SimpleCol) bool isAttachedToOwner; UPROPERTY(BlueprintReadOnly, Category = SimpleCol) FName attachName; private: FTimerHandle flickeringTimer; }; UCLASS() class PROJECTA_API ALineTraceCol : public ABaseDmgColActor { GENERATED_BODY() public: ALineTraceCol(); virtual void doWhenSpawn() override; public: UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = LineTraceCol) float Range; }; UCLASS() class PROJECTA_API AProjCol : public ABaseDmgColActor { GENERATED_BODY() public: AProjCol(); virtual void BeginPlay() override; virtual void Tick(float DeltaTime) override; virtual void lastProcess() override; void setProjectileProp(const bool _isHoming, const float _initSpd, const float _maxSpd, const float _hommingAccel, const float _gravityScale, const AActor* target); private: void emptyPathsExcludeTarget(void) { if (pathArray.Num() > 0) { for (int32 i = 0; i < pathArray.Num() - 1; ++i) { pathArray[i]->DestroyComponent(); } pathArray.Empty(); } } public: UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = ProjCol) class USphereComponent* sphereCol; UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = ProjCol) class UStaticMeshComponent* SM; UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = ProjCol) class UProjectileMovementComponent* movement; UPROPERTY() TArray<class USceneComponent*> pathArray; int32 cachedNum; int32 idx; }; UCLASS() class PROJECTA_API ATrailActor : public AActor { GENERATED_BODY() public: ATrailActor(); void setTrailActor(class UParticleSystem* PSC_templete); UFUNCTION() void whenOwnerDestroyed(AActor* destroyedActor); public: UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = TrailActor) class UParticleSystemComponent* trail; };
[ "jeongu1270@gmail.com" ]
jeongu1270@gmail.com
93f410303a8a1c84c8a6056c9e48c9440e4efab8
e0845c555b1902abc3871fe5f0224a1becc3c75a
/bitwise_OR_of_subarrays.cpp
b0b6318382eff6b0cfa38ad6948c486b2d1d4443
[]
no_license
PSukhalani-96/Programming-Practice
d2982350b366d26f42e73db288e071eb682917db
9b09012d1afdd8fea2c1cf745a8b576aed1504af
refs/heads/master
2020-05-27T00:15:09.726340
2019-07-08T12:49:18
2019-07-08T12:49:18
188,420,529
0
0
null
null
null
null
UTF-8
C++
false
false
1,250
cpp
/* We have an array A of non-negative integers. For every (contiguous) subarray B = [A[i], A[i+1], ..., A[j]] (with i <= j), we take the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j]. Return the number of possible results. (Results that occur more than once are only counted once in the final answer.) Example 1: Input: [0] Output: 1 Explanation: There is only one possible result: 0. Example 2: Input: [1,1,2] Output: 3 Explanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2]. These yield the results 1, 1, 2, 1, 3, 3. There are 3 unique values, so the answer is 3. Example 3: Input: [1,2,4] Output: 6 Explanation: The possible results are 1, 2, 3, 4, 6, and 7. */ class Solution { public: int subarrayBitwiseORs(vector<int>& A) { unordered_set<int> s1; unordered_set<int> res; s1.insert(0); for ( int num: A) { unordered_set<int> temp; for(auto itr: s1) { temp.insert(itr | num); } temp.insert(num); s1 = temp; res.insert(s1.begin(), s1.end()); } return res.size(); } };
[ "noreply@github.com" ]
noreply@github.com
db6042189add174bb0e00b215e5fffe628bab936
992b3deffde391784fd76c626c78cd0a1f51272a
/lib/UI/cpp/checkbox.cpp
e402d48ec6192067116a9b9e61db64c580f7d5f3
[]
no_license
Siluk98/Paint
4676d7da85b5d235b8fe3999753887fdb72cd2f4
9d409032c96d0ce028a642f3d3b89ad25953ce27
refs/heads/master
2020-03-26T16:49:18.397916
2019-09-16T14:53:28
2019-09-16T14:53:28
145,125,203
2
0
null
2019-01-02T04:20:50
2018-08-17T13:41:02
C++
UTF-8
C++
false
false
4,785
cpp
#include <iostream> #include "../../Engine/hpp/state.hpp" #include "../../Engine/hpp/game.hpp" #include "../../Engine/hpp/event.hpp" #include "../hpp/checkbox.hpp" UI::Checkbox::Checkbox(std::string id, cssHandler& css) { std::cout << "chkbox" << std::endl; /* bind("click", [](void* arg, Component* pthis){ UI::Checkbox* ptr = dynamic_cast<Checkbox*>(pthis); ptr->flipValue(); }); */ Functor *func = new Functor(nullptr,[](void* arg, Object* pthis){ UI::Checkbox* ptr = dynamic_cast<Checkbox*>(pthis); ptr->flipValue(); }); bind("Flip", func); //implement css outerWidth = 16; outerHeight = 16; innerWidth = outerWidth-8; innerHeight = outerHeight-8; outer = new sf::RectangleShape(sf::Vector2f(outerWidth,outerHeight)); inner = new sf::RectangleShape(sf::Vector2f(innerWidth,innerHeight)); hitbox = new sf::IntRect(0,0,outerWidth,outerHeight); innerColor = sf::Color(0,0,0,0); outerColor = sf::Color::White; moveTo(100,100); applyStyle(css); outer->setFillColor(innerColor); outer->setOutlineColor(outerColor); outer->setOutlineThickness(-2); inner->setFillColor(outerColor); std::cout << "hitbox: " << hitbox->left << " " << hitbox->top << std::endl; isPressed = false; this->id = id; addType("checkbox"); addEvent("MouseDown", Action{[](Object* a, Object* b, std::string arg1, std::string arg2){ UI::Checkbox *c = dynamic_cast<Checkbox*>(a); c->isPressed = true; //std::cout << "check" << std::endl; }}); addEvent("MouseUp", Action{[](Object* a, Object* b, std::string arg1, std::string arg2){ UI::Checkbox *c = dynamic_cast<Checkbox*>(a); if(c->isPressed) { std::cout << "click " << c->id << std::endl; c->isPressed = false; c->execute("Flip"); c->execute("onInput"); } }}); } UI::Checkbox::Checkbox(std::string id, cssHandler* css) : UI::Checkbox(id,*css){} UI::Checkbox::~Checkbox() { delete outer; delete inner; } void UI::Checkbox::draw(sf::RenderTarget &target, sf::RenderStates states) const { target.draw(*outer); if(value) target.draw(*inner); } void UI::Checkbox::update() { for(unsigned int i=0;i<events.size();i++) { events[i]->handle(this,nullptr,"",""); } } std::string UI::Checkbox::create(std::string obj, std::string params) { return "What's that?"; } void UI::Checkbox::changeStyle(std::string atr, std::string val) { try { if(val == "") return; std::cout << id << ": " << atr << ": " << val << std::endl; if(atr == "width") { int i = std::stoi(val); outerWidth = i; innerWidth = i-8; hitbox->height = outerWidth; outer->setSize(sf::Vector2f(outerWidth,outerHeight)); inner->setSize(sf::Vector2f(innerWidth,innerHeight)); } if(atr == "height") { int i = std::stoi(val); outerHeight = i; innerHeight = i-8; hitbox->height = outerHeight; outer->setSize(sf::Vector2f(outerWidth,outerHeight)); inner->setSize(sf::Vector2f(innerWidth,innerHeight)); } if(atr == "top") { int i = std::stoi(val); moveTo(hitbox->left,i); } if(atr == "left") { int i = std::stoi(val); moveTo(i,hitbox->top); } if(atr == "innerColor") { if(val == "red") innerColor = sf::Color::Red; else if(val == "blue") innerColor = sf::Color::Blue; else if(val == "green") innerColor = sf::Color::Green; else innerColor = sf::Color::White; } if(atr == "outerColor") { if(val == "red") outerColor = sf::Color::Red; else if(val == "blue") outerColor = sf::Color::Blue; else if(val == "green") outerColor = sf::Color::Green; else outerColor = sf::Color::White; } } catch(...) { std::cout << "Broken css" << std::endl; } } bool UI::Checkbox::getValue() { return value; } bool UI::Checkbox::setValue(bool v) { value = v; return value; } bool UI::Checkbox::flipValue() { value = !value; return value; } sf::Vector2f UI::Checkbox::moveTo(int x,int y) { int dw = (outerWidth-innerWidth)/2; int dh = (outerHeight-innerHeight)/2; inner->setPosition(x,y); outer->setPosition(x-dw,y-dh); return Object::moveTo(x,y); }
[ "siluk98@tlen.pl" ]
siluk98@tlen.pl
df6dafca81cae6da8691863f38f30f5e18f1a9e0
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/ClassifierService/UNIX_ClassifierService.cpp
bda4189efe719888d7523ee2f91742045bfb5965
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
3,397
cpp
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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 "UNIX_ClassifierService.h" #if defined(PEGASUS_OS_HPUX) # include "UNIX_ClassifierService_HPUX.hxx" # include "UNIX_ClassifierService_HPUX.hpp" #elif defined(PEGASUS_OS_LINUX) # include "UNIX_ClassifierService_LINUX.hxx" # include "UNIX_ClassifierService_LINUX.hpp" #elif defined(PEGASUS_OS_DARWIN) # include "UNIX_ClassifierService_DARWIN.hxx" # include "UNIX_ClassifierService_DARWIN.hpp" #elif defined(PEGASUS_OS_AIX) # include "UNIX_ClassifierService_AIX.hxx" # include "UNIX_ClassifierService_AIX.hpp" #elif defined(PEGASUS_OS_FREEBSD) # include "UNIX_ClassifierService_FREEBSD.hxx" # include "UNIX_ClassifierService_FREEBSD.hpp" #elif defined(PEGASUS_OS_SOLARIS) # include "UNIX_ClassifierService_SOLARIS.hxx" # include "UNIX_ClassifierService_SOLARIS.hpp" #elif defined(PEGASUS_OS_ZOS) # include "UNIX_ClassifierService_ZOS.hxx" # include "UNIX_ClassifierService_ZOS.hpp" #elif defined(PEGASUS_OS_VMS) # include "UNIX_ClassifierService_VMS.hxx" # include "UNIX_ClassifierService_VMS.hpp" #elif defined(PEGASUS_OS_TRU64) # include "UNIX_ClassifierService_TRU64.hxx" # include "UNIX_ClassifierService_TRU64.hpp" #else # include "UNIX_ClassifierService_STUB.hxx" # include "UNIX_ClassifierService_STUB.hpp" #endif Boolean UNIX_ClassifierService::validateKey(CIMKeyBinding &kb) const { /* Keys */ //SystemCreationClassName //SystemName //CreationClassName //Name CIMName name = kb.getName(); if (name.equal(PROPERTY_SYSTEM_CREATION_CLASS_NAME) || name.equal(PROPERTY_SYSTEM_NAME) || name.equal(PROPERTY_CREATION_CLASS_NAME) || name.equal(PROPERTY_NAME) ) return true; return false; } void UNIX_ClassifierService::setScope(CIMName scope) { currentScope = scope; }
[ "brunolauze@msn.com" ]
brunolauze@msn.com
cf89404da14a9bd834367f5d1c8539b9e7eb76ab
794f253c1a58b90d76b8fec4dd85a6aabf275d3b
/p3/hash_function.cpp
08b1ea47c050d35c5207f80c1ba5230e6bd43461
[]
no_license
kkrusk/CSCI-311
cdfe98afef3f159b55792c18101e0436cccbfed0
1242af7c584a5ec79c0819158f967f402fab97bc
refs/heads/master
2020-04-25T07:31:41.709840
2019-02-26T02:49:38
2019-02-26T02:49:38
172,616,902
0
0
null
null
null
null
UTF-8
C++
false
false
966
cpp
/* This assignment originated at UC Riverside.*/ //AUTHOR: KYLE KRUSKAMP //HASH FUNCTION //APR 1 2016 #include <string> #include "hash.h" using std::string; // This is only a sample hash function (and a bad one at that). You will // need to replace the contents of this hash function with your own // hash function /* * A common hash function that multiplies by 33, which is a prime number * I attempted using 37, 131, etc but found 33 most effective * The if statement may be redundant because I can't think of when the number would be negative * Resources/credit on understanding different functions * https://www.daniweb.com/programming/software-development/threads/231987/string-hash-function */ int Hash :: hf (string key) { int sum = 0; for(unsigned int i = 0; i < key.length(); i++) { sum = 33 * sum + ((int)key[i]); sum %= HASH_TABLE_SIZE; } if(sum < 0) { sum += HASH_TABLE_SIZE; } return sum; }
[ "kylekrusk@gmail.com" ]
kylekrusk@gmail.com
14763512e525259619a3a0cc671d50cada0ebf14
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/collectd/gumtree/collectd_repos_function_419_last_repos.cpp
7c2bbe559f15491fadd38dd6e47032bd93d6ff95
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
602
cpp
static void nut_submit(nut_ups_t *ups, const char *type, const char *type_instance, gauge_t value) { value_list_t vl = VALUE_LIST_INIT; vl.values = &(value_t){.gauge = value}; vl.values_len = 1; if (strcasecmp(ups->hostname, "localhost") != 0) sstrncpy(vl.host, ups->hostname, sizeof(vl.host)); sstrncpy(vl.plugin, "nut", sizeof(vl.plugin)); sstrncpy(vl.plugin_instance, ups->upsname, sizeof(vl.plugin_instance)); sstrncpy(vl.type, type, sizeof(vl.type)); sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance)); plugin_dispatch_values(&vl); }
[ "993273596@qq.com" ]
993273596@qq.com
c6bebc2bb33f8aff8afad1ba862aa81c4c7b3e5a
f08bb2a493665c32f573dc8c64840b11d9ae0d0f
/src/CRSpline.h
4f5447a6cb9a9e47172f66eedf2210ffa97fcb05
[]
no_license
vanish87/Jungle-of
015e4990c3fed7f28eb07eaabfdec57afe81a9e9
230136eea9a8137f949e7fe8c113fc0ccc3aa824
refs/heads/master
2021-01-10T02:11:11.340230
2013-05-17T00:27:09
2013-05-17T00:27:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
431
h
#ifndef CRSPLINES_H_ #define CRSPLINES_H_ #pragma once #include "ofMatrix4x4.h" namespace Jungle { class CRSpline { public: CRSpline(void); ~CRSpline(void); //get pos between P2 and P3 with t=[0,1] ofVec3f GetPos(ofVec3f p0, ofVec3f p1, ofVec3f p2, ofVec3f p3, float t); float CubicFun(float u, ofVec4f c); public: float tau_; ofMatrix4x4 geo_matrix_; }; } #endif
[ "vanish8.7@gmail.com" ]
vanish8.7@gmail.com
38448ca32f4c6c23f522b0309c182e9d4280b219
2720b9cb2cb05b86f5cfdf1799baea0cf706d159
/3RVX/D3DDevice.cpp
e2719eb355aa0b842e0bd3bbefd31efbb0715563
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
malensek/3RVX
baa076679437facab4d00315c3f5030be67fc9bd
556a0fe742922cd732645b2d1e03065d87e39747
refs/heads/master
2023-08-23T16:10:29.905393
2022-01-20T23:43:07
2022-01-20T23:43:07
12,887,841
368
99
BSD-2-Clause
2023-03-10T11:29:31
2013-09-17T06:22:24
C++
UTF-8
C++
false
false
947
cpp
// Copyright (c) 2016, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "D3DDevice.h" #include <d3d9.h> #pragma comment(lib, "d3d9.lib") #include "Logger.h" D3DDevice::D3DDevice(HWND hWnd) { DWORD behaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING; D3DPRESENT_PARAMETERS d3dpp = { 0 }; d3dpp.Windowed = TRUE; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; Direct3DCreate9Ex(D3D_SDK_VERSION, &_pDirect3DEx); HRESULT hr = _pDirect3DEx->CreateDeviceEx( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, behaviorFlags, &d3dpp, NULL, &_pDeviceEx); } D3DDevice::~D3DDevice() { if (_pDeviceEx) { _pDeviceEx->Release(); } if (_pDirect3DEx) { _pDirect3DEx->Release(); } } bool D3DDevice::Occluded() { HRESULT hr = _pDeviceEx->CheckDeviceState(NULL); return (hr == S_PRESENT_OCCLUDED); }
[ "matt@malensek.net" ]
matt@malensek.net
3a292e8c4eab2e43a00ddb0455fb3bf04730090e
4b81a99df02e2dd5685334522251d7787dfec3d4
/v3.0alpha0/Classes/ByeWorldScene.h
c136b3b2b1e85eff03b98e5ed933978242df72c7
[]
no_license
czhiraga/Cocos2d-xTestApps
18148af480b05350fba2f1eea189a8cf3a919eb5
7b10e6aa3d41c0e822b4eebcd4500c0de1ba18b8
refs/heads/master
2020-05-30T08:12:15.851075
2014-10-27T11:02:49
2014-10-27T11:02:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,107
h
#ifndef __BYEWORLD_SCENE_H__ #define __BYEWORLD_SCENE_H__ #include "cocos2d.h" class ByeWorld : public cocos2d::CCLayer { public: // Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer) virtual bool init(); // there's no 'id' in cpp, so we recommend to return the class instance pointer static cocos2d::Scene* scene(); // a selector callback void menuCloseCallback(cocos2d::Object* pSender); void clickAd(cocos2d::Object* pSender); void sendConversion(cocos2d::Object* pSender); // アクセス解析 // void sendEvent(CCObject* pSender); // void sendEventPurchase(CCObject* pSender); // void sendUserInfo(CCObject* pSender); // void startSession(CCObject* pSender); // void endSession(CCObject* pSender); // LTV計測 void addParam(cocos2d::Object* pSender); void addParam2(cocos2d::Object* pSender); void sendLtv(cocos2d::Object* pSender); // preprocessor macro for "static create()" constructor ( node() deprecated ) CREATE_FUNC(ByeWorld); }; #endif // __HELLOWORLD_SCENE_H__
[ "hiraga_tsuyoshi@cyberx.co.jp" ]
hiraga_tsuyoshi@cyberx.co.jp
3c8417c08116686811c6bf7adcadee78edee467b
8c89782663a343f7c3d362573620f79d275a6142
/src/2000/2920.cpp14.cpp
96befe28312c7e46e4376f633a5bad0f3b2e1828
[ "MIT" ]
permissive
upple/BOJ
14a8c8e372131b9a50ba7c1e7428ba7e57b4702d
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
refs/heads/master
2021-06-21T07:17:57.974279
2019-06-28T17:56:30
2019-06-28T17:56:30
128,779,781
13
0
null
null
null
null
UTF-8
C++
false
false
403
cpp
#include<cstdio> #include<vector> #include<algorithm> using namespace std; int main() { vector<int> arr(8),st, rv; for(int i=0; i<8; i++) scanf("%d", &arr[i]); st=arr; sort(st.begin(), st.end()); rv=st; reverse(rv.begin(), rv.end()); if(arr==st) printf("ascending"); else if(arr==rv) printf("descending"); else printf("mixed"); }
[ "upple_@naver.com" ]
upple_@naver.com
1107a91fbdeaf7829e808036726015e30dd3228b
7df7098cac8dcba022797e1ad97318dd97097b2c
/Account/Detail/MainFrame.cpp
f765cba73118e2505c8fade68674efccc8402738
[]
no_license
lovejiushuai/HappyXiu_V0.2
57d20cf9a9b0fd133ead598d19c7846c3cea2408
ef80c91047fcca2e17c8a1be0e7efe0e71e5d5cc
refs/heads/master
2020-03-30T00:32:26.236209
2015-06-17T10:09:00
2015-06-17T10:09:00
37,587,177
0
0
null
null
null
null
UTF-8
C++
false
false
1,372
cpp
// MainFrame.cpp : implementation file // #include "stdafx.h" #include "Detail.h" #include "MainFrame.h" // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) CMainFrame::CMainFrame() { EnableAutomation(); } CMainFrame::~CMainFrame() { } void CMainFrame::OnFinalRelease() { // When the last reference for an automation object is released // OnFinalRelease is called. The base class will automatically // deletes the object. Add additional cleanup required for your // object before calling the base class. CFrameWnd::OnFinalRelease(); } BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() END_MESSAGE_MAP() BEGIN_DISPATCH_MAP(CMainFrame, CFrameWnd) END_DISPATCH_MAP() // Note: we add support for IID_IMainFrame to support typesafe binding // from VBA. This IID must match the GUID that is attached to the // dispinterface in the .IDL file. // {BF9D1EE8-C74B-432F-A1EF-D02FBE6D60CE} static const IID IID_IMainFrame = { 0xBF9D1EE8, 0xC74B, 0x432F, { 0xA1, 0xEF, 0xD0, 0x2F, 0xBE, 0x6D, 0x60, 0xCE } }; BEGIN_INTERFACE_MAP(CMainFrame, CFrameWnd) INTERFACE_PART(CMainFrame, IID_IMainFrame, Dispatch) END_INTERFACE_MAP() // CMainFrame message handlers int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; // TODO: Add your specialized creation code here return 0; }
[ "lovejiushuai@gmail.com" ]
lovejiushuai@gmail.com
7d8eeac8922618ca84aecc9ad074e042cc93c1db
554e6b73ed500172abe5fdef08fbc7caf4089f78
/Cpp/codeforces/678D.cpp
2523df7ec0969a89794b8285dd793bdbb9c339c9
[]
no_license
Shandilier/Competitive-Programming-1
e65388adff421398d803b746635597b2fa5a53c2
c9d66f472aee2fd1fbd3e934e3efb2230dbeebd6
refs/heads/main
2023-06-25T09:33:46.317893
2021-07-28T03:06:16
2021-07-28T03:06:16
385,301,682
0
0
null
null
null
null
UTF-8
C++
false
false
1,442
cpp
#include<bits/stdc++.h> #define ll long long int #define loop(i,a,b) for(int (i)=(a);(i)<(b);(i)++) #define rep(i,n) for(int (i)=0;(i)<n;(i)++) #define bp 1000000007 #define sz(a) int((a).size()) #define pb push_back #define mp make_pair #define all(c) (c).begin(),(c).end() #define F first #define S second using namespace std; typedef pair<ll,ll> ii; ll maxm=0; void dfs(ll v,vector<ll>adj[],ll val[],ll leafCount[]) { if(adj[v].size()==0) leafCount[v]++; for(ll i=0;i<adj[v].size();i++) { dfs(adj[v][i],adj,val,leafCount); leafCount[v]+=leafCount[adj[v][i]]; val[v]+=val[adj[v][i]]; } if((val[v]+leafCount[v])%leafCount[v]==0) maxm=max(maxm,val[v]/leafCount[v]); else maxm=max(maxm,val[v]/leafCount[v]+1); } void solve() { ll n; cin>>n; vector<ll>adj[n+1]; ll x; for(ll i=2;i<=n;i++) { cin>>x; adj[x].push_back(i); } ll val[n+1]; for(ll i=1;i<=n;i++) cin>>val[i]; ll leafCount[n+1]; memset(leafCount,0,sizeof(leafCount)); dfs(1,adj,val,leafCount); // for(ll i=1;i<=n;i++) // cout<<val[i]<<" "; cout<<maxm<<endl; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); // ll test; int test=1; // cin>>test; while(test--) { solve(); } return 0; }
[ "sachin.shandilya@ge.com" ]
sachin.shandilya@ge.com
159957730ed6fd9b202ae76bcc616108b2e7eb62
7e46bb84906a762fe5c27cb1a0268f0250a4e88b
/main.cpp
91065045e58e72c1dbcdc2566e19fd38b626d9c0
[]
no_license
AdrianKlessa/PL-Dziedziczenie-punktikolo
839d9381d922bfd27d4395da036316022f4e42ea
afcfa10449d2ce0fb9d4f15cc3e1b6882ea37bbc
refs/heads/master
2020-05-26T13:28:19.468679
2019-05-23T14:25:33
2019-05-23T14:25:33
188,246,890
0
0
null
null
null
null
UTF-8
C++
false
false
1,382
cpp
#include <iostream> #include <math.h> using namespace std; class Punkt { float x,y; string nazwa; public: void wyswietl() { cout<< nazwa << " (" <<x << "," << y << ")" << endl; } Punkt(string n="S", float a=0, float b=0) { nazwa=n; x=a; y=b; } }; class Kolo : public Punkt { protected: float r; string nazwa; public: void wyswietl() { cout << "Kolo o nazwie " << nazwa << endl; cout << "Srodek kola: " << endl; Punkt::wyswietl(); cout << "Promien: "<<r << endl; cout << "Pole kola: " << M_PI*r*r<<endl; } Kolo(string nk="Kolko",string np="S", float a=0, float b=0, float pr=1) :Punkt(np,a,b) { nazwa=nk; r=pr; }; }; class Kula : public Kolo { public: Kula(string n="Kulka", string ns="S",float a=0, float b=0, float pr=1) :Kolo(n,ns,a,b,pr) { } void wyswietl() { cout << "Kula o nazwie " << nazwa << endl; cout << "Srodek kuli: " << endl; Kolo::wyswietl(); cout << endl << "Objetosc kuli: " << endl << 4*M_PI*r*r*r/3; } }; int main() { Kolo k1; k1.wyswietl(); cout << endl << endl; Kula K1("Moja kula","Srodek",2,3,2.5); K1.wyswietl(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
3fc4da03e108438c94197f016717483d547ffb7a
3a7d140ec93581c61c9c5680cf6bbc319266f688
/Solved Practice problems/magnets.cpp
fd9e60b3b71d360dbef65616de200176fc7801ff
[]
no_license
Ovishake1607066/Solved-Codeforces-problems
dcc6e33d471e4e92d1cf76b7c5aab4b0278fbf55
fe038bb365bd666b2bbcad815e9ad3206d7e0988
refs/heads/master
2022-07-17T04:12:21.628142
2020-05-13T19:20:09
2020-05-13T19:20:09
263,710,650
0
0
null
null
null
null
UTF-8
C++
false
false
330
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long int main() { string s1,s2; ll n,a,c=0; cin>>n; for(ll i=0;i<n;i++) { cin>>s1; if(s1==s2) continue; else { c++; s2=s1; } } cout<<c<<endl; }
[ "noreply@github.com" ]
noreply@github.com
b62385e9d47687e3b42ba27864010c3797f2fdc5
210f6d3b0f73f76c77be76af30bf8ba9d4006cdf
/src/qt/qtipcserver.cpp
c1bf7e445d2232aa2605aa5dfef142ab13bf3969
[ "MIT" ]
permissive
DenisMalofeyev/taler
0a4afd971fa7b01d138c07795abc25d5a718216a
ecab96268ca6424aa2cd63563440188e090c71a0
refs/heads/master
2021-06-18T00:07:39.783780
2017-06-20T21:50:43
2017-06-20T21:50:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,370
cpp
// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include "qtipcserver.h" #include "guiconstants.h" #include "ui_interface.h" #include "util.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/interprocess/ipc/message_queue.hpp> #include <boost/version.hpp> #if defined(WIN32) && (!defined(BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME) || !defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) || BOOST_VERSION < 104900) #warning Compiling without BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME and BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME uncommented in boost/interprocess/detail/tmp_dir_helpers.hpp or using a boost version before 1.49 may have unintended results see svn.boost.org/trac/boost/ticket/5392 #endif using namespace boost; using namespace boost::interprocess; using namespace boost::posix_time; static void ipcThread2(void* pArg); #ifdef MAC_OSX // URI handling not implemented on OSX yet void ipcInit() { } #else static void ipcThread(void* pArg) { IMPLEMENT_RANDOMIZE_STACK(ipcThread(pArg)); // Make this thread recognisable as the GUI-IPC thread RenameThread("bitcoin-gui-ipc"); try { ipcThread2(pArg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ipcThread()"); } catch (...) { PrintExceptionContinue(NULL, "ipcThread()"); } printf("ipcThread exited\n"); } static void ipcThread2(void* pArg) { printf("ipcThread started\n"); message_queue* mq = (message_queue*)pArg; char buffer[MAX_URI_LENGTH + 1] = ""; size_t nSize = 0; unsigned int nPriority = 0; loop { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100); if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d)) { uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize)); Sleep(1000); } if (fShutdown) break; } // Remove message queue message_queue::remove(BITCOINURI_QUEUE_NAME); // Cleanup allocated memory delete mq; } void ipcInit() { message_queue* mq = NULL; char buffer[MAX_URI_LENGTH + 1] = ""; size_t nSize = 0; unsigned int nPriority = 0; try { mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH); // Make sure we don't lose any taler: URIs for (int i = 0; i < 2; i++) { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1); if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d)) { uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize)); } else break; } // Make sure only one instance is listening message_queue::remove(BITCOINURI_QUEUE_NAME); delete mq; mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH); } catch (interprocess_exception &ex) { printf("ipcInit() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what()); return; } if (!CreateThread(ipcThread, mq)) { delete mq; return; } } #endif
[ "gott.x@web.de" ]
gott.x@web.de
6855f617f4df3f553512c4fb60f177f1705d81d5
becacd46fa457d724c563afa5c171d7b23580ba7
/Algorithm/svgpp/SvgPath.h
02cd9157b60b879408cd9a3fb7b022d463b8dbd8
[ "MIT" ]
permissive
boyang-yu/ClothDesigner
a5e9ad7f77133a6d7c89703d6d3bd71e4706afe9
82b186d6db320b645ac67a4d32d7746cc9bdd391
refs/heads/master
2022-03-11T10:41:10.717069
2019-07-31T12:46:53
2019-07-31T12:46:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,433
h
#pragma once #include "GL\glew.h" #include "SvgAbstractObject.h" #include "PathStyle.hpp" namespace svg { class SvgPath : public SvgAbstractObject { public: SvgPath(); virtual ~SvgPath(); ObjectType objectType()const { return ObjectType::Path; } virtual void render(); virtual void renderId(); virtual std::shared_ptr<SvgAbstractObject> clone(bool selectedOnly = false)const; virtual std::shared_ptr<SvgAbstractObject> deepclone(bool selectedOnly = false)const; virtual TiXmlElement* toXML(TiXmlNode* parent)const; virtual void copyTo(SvgAbstractObject* obj)const; virtual ldp::Float2 getStartPoint()const; virtual ldp::Float2 getEndPoint()const; virtual int numId()const{ return 1; } // the path is closed or open bool isClosed()const; virtual void updateBoundFromGeometry(); void setPathWidth(float w); float getPathWidth()const { return m_pathStyle.stroke_width; } // split all segments to individual paths // if there is only one segment, we do not split and return an nullptr // else we return grouped splittings std::shared_ptr<SvgAbstractObject> splitToSegments(bool to_single_segs = true)const; // extract path from cmdsBegin(include) to cmdsEnd(exclude) // to_single_segment will convert 'M-L-L-L' to 'M-L M-L M-L' std::shared_ptr<SvgAbstractObject> subPath(int cmdsBegin, int cmdsEnd, bool to_single_segment = false)const; std::shared_ptr<SvgAbstractObject> subPath(const std::vector<int>& cmdsBegins, const std::vector<int>& cmdsEnds, bool to_single_segment = false)const; // check the intersection with other and insert a point if intersected bool insertPointByIntersection(const SvgPath* other, float thre); protected: void cacheNvPaths(); void renderSelection(); void configNvParams(); public: std::vector<GLubyte> m_cmds; std::vector<GLfloat> m_coords; GLenum m_gl_fill_rull; PathStyle m_pathStyle; // return number of coordinates associated with a cmd static int numCoords(GLubyte cmd); static char svgCmd(GLubyte cmd); static const char* strokeFillMap(int fill); static const char* strokeLineCapMap(int cap); static const char* strokeLineJoinMap(int join); static GLenum lineJoinConverter(const SvgPath *path); static GLenum lineCapConverter(const SvgPath *path); public: struct GLPathResource{ GLuint id; GLPathResource(); ~GLPathResource(); }; std::shared_ptr<GLPathResource> m_gl_path_res; }; }
[ "dong_pingli@hotmail.com" ]
dong_pingli@hotmail.com
5f90a73e4601e46b0212eaf2b2dcb2367144df54
db96f25810356dedb49271975725d394ce1fe0e7
/WebServer/FileHandler.cpp
979e54befa1fa82db1eb69f356194ff05ca90d3b
[]
no_license
harshalbhakta/MiniWebServer
e0fbf361764c9ff4a5de77e22a57b2ae2367cceb
2aa3cce698bd7c52ab9e3ed1044ddf5475bedbd1
refs/heads/master
2021-03-12T23:25:00.756717
2013-02-21T01:09:49
2013-02-21T01:09:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,262
cpp
/////////////////////////////////////////////////////////////////////////////////////////// // FileHandler.h - FileHandler Implementation File // // // // Version 1.0 // // Language : C++ , Microsoft Visual Studio 2008. // // Author : Harshal Bhakta,Shazia Bee CIS_554_WEB_SERVER, Syracuse University // // // /////////////////////////////////////////////////////////////////////////////////////////// /* FileHandler Class Description * ============================================================================================ * * FileHandler class is implemented to be used for handling File IO tasks for our webserver. * In our webserver we need to fetch the requested page from server directory. Reading the * content of the HTML file is handled by FileHandler. // Interface : // FileHandler fh("test.html"); // cout<<fh.getHtmlFileContent(); */ #include <iostream> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <exception> #include "FileHandler.h" #include "Logger.h" #include "ErrorLogger.h" using namespace std; FileHandler::FileHandler(string file) { try { fileName = file; } catch (exception &e) { cout << endl << "File Handler Exception: " << e.what() << endl; ErrorLogger::LogError( e.what()); } } void FileHandler::setFileName(string fname) { try { fileName = fname; } catch (exception &e) { cout << endl << "File Handler Exception: " << e.what() << endl; ErrorLogger::LogError( e.what()); } } int FileHandler::getFileLength() { try { return fileContent.length(); } catch (exception &e) { cout << endl << "File Handler Exception: " << e.what() << endl; ErrorLogger::LogError( e.what()); return 0; } } string FileHandler::getFileContent() { try { return fileContent; } catch (exception &e) { cout << endl << "File Handler Exception: " << e.what() << endl; ErrorLogger::LogError( e.what()); return 0; } } void FileHandler::getHtmlFileContent() { try { fileContent = ""; string line = ""; // Fetch the contents of the file. ifstream myfile (fileName.c_str()); if (myfile.is_open()) { Logger::LogMessage("Reading file for HTML content"); while ( myfile.good() ) { getline (myfile,line); fileContent = fileContent + line; cout << line << endl; } myfile.close(); } } catch (exception &e) { cout << endl << "File Handler Exception: " << e.what() << endl; ErrorLogger::LogError( e.what()); } } bool FileHandler::ifFileExists() { try { Logger::LogMessage("Checking if requested file exists or not"); bool returnFileExists = true; ifstream ifile(fileName.c_str()); if ( ifile == 0 ) { Logger::LogMessage("File does not exists"); returnFileExists = false; } Logger::LogMessage("File exists"); return returnFileExists; } catch (exception &e) { cout << endl << "File Handler Exception: " << e.what() << endl; ErrorLogger::LogError( e.what()); return false; } }
[ "harshal.c.bhakta@gmail.com" ]
harshal.c.bhakta@gmail.com
ffc66dff97380a9e4a13cc53eff826b58163cf8b
d691b4d23482de4e6605be15bbf27dd046b48812
/provider/DeleteEvent.cpp
524b481219d07a31e7936e4fd4f2bdf18bbbc9d8
[]
no_license
Wiggly-xd/widerFrontend
c2871a719117d30b0e171a2f288e918ac6409b62
256db310276786d8a9e445e1e624a1a86110609d
refs/heads/master
2023-02-19T20:39:39.963100
2021-01-25T08:22:32
2021-01-25T08:22:32
317,494,011
0
0
null
null
null
null
UTF-8
C++
false
false
28
cpp
#include "DeleteEvent.h"
[ "noreply@github.com" ]
noreply@github.com
2121a53197eafa2afb6da39f320bc0143245914e
b869deb7ebb1d14bc3bf320ab6b065b717c0421b
/uri1001.cpp
a786f48bb5d2c3c1a7e6b01558563025b91c81f3
[]
no_license
Shamim-38/Programming-Problem-Solving---uva-uri-timus
1346d4e19a8ca347fddbcfe623d2878240b72ecb
394042ab7169d2d7d63144b4a9970298d836f387
refs/heads/master
2020-08-01T16:39:21.225571
2019-09-26T09:18:43
2019-09-26T09:18:43
211,049,465
0
0
null
null
null
null
UTF-8
C++
false
false
138
cpp
#include<stdio.h> int main() { int A,B,X; scanf("%d %d",&A,&B); X=A+B; printf("X = %d\n",X); return 0; }
[ "shamimul435@gmail.com" ]
shamimul435@gmail.com
9698011bf0b93c6506f657e6c18ae439aea68ab2
31ee2fc5e739d90a5649dde0954f6767dcb397cc
/src/primitives/transaction.h
5594581ad8760397026aa5b6b7dc0b1e9bb0908b
[ "MIT" ]
permissive
Eclipsim/Eclipsim
00e5fcdbb5c3965843fa593aacdb7e3558c5ecfd
6214238a9d7da0ce552ceb3e182506f554f1e716
refs/heads/master
2020-05-30T22:02:10.943542
2019-06-03T10:51:45
2019-06-03T10:51:45
189,836,626
0
0
null
null
null
null
UTF-8
C++
false
false
11,757
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-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. #ifndef BITCOIN_PRIMITIVES_TRANSACTION_H #define BITCOIN_PRIMITIVES_TRANSACTION_H #include "amount.h" #include "script/script.h" #include "serialize.h" #include "uint256.h" /** An outpoint - a combination of a transaction hash and an index n into its vout */ class COutPoint { public: uint256 hash; uint32_t n; COutPoint() { SetNull(); } COutPoint(uint256 hashIn, uint32_t nIn) { hash = hashIn; n = nIn; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(hash); READWRITE(n); } void SetNull() { hash.SetNull(); n = (uint32_t) -1; } bool IsNull() const { return (hash.IsNull() && n == (uint32_t) -1); } friend bool operator<(const COutPoint& a, const COutPoint& b) { int cmp = a.hash.Compare(b.hash); return cmp < 0 || (cmp == 0 && a.n < b.n); } friend bool operator==(const COutPoint& a, const COutPoint& b) { return (a.hash == b.hash && a.n == b.n); } friend bool operator!=(const COutPoint& a, const COutPoint& b) { return !(a == b); } std::string ToString() const; std::string ToStringShort() const; }; /** An input of a transaction. It contains the location of the previous * transaction's output that it claims and a signature that matches the * output's public key. */ class CTxIn { public: COutPoint prevout; CScript scriptSig; uint32_t nSequence; /* Setting nSequence to this value for every input in a transaction * disables nLockTime. */ static const uint32_t SEQUENCE_FINAL = 0xffffffff; /* Below flags apply in the context of BIP 68*/ /* If this flag set, CTxIn::nSequence is NOT interpreted as a * relative lock-time. */ static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31); /* If CTxIn::nSequence encodes a relative lock-time and this flag * is set, the relative lock-time has units of 512 seconds, * otherwise it specifies blocks with a granularity of 1. */ static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22); /* If CTxIn::nSequence encodes a relative lock-time, this mask is * applied to extract that lock-time from the sequence field. */ static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff; /* In order to use the same number of bits to encode roughly the * same wall-clock duration, and because blocks are naturally * limited to occur every 600s on average, the minimum granularity * for time-based relative lock-time is fixed at 512 seconds. * Converting from CTxIn::nSequence to seconds is performed by * multiplying by 512 = 2^9, or equivalently shifting up by * 9 bits. */ static const int SEQUENCE_LOCKTIME_GRANULARITY = 9; CTxIn() { nSequence = SEQUENCE_FINAL; } explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL); CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(prevout); READWRITE(*(CScriptBase*)(&scriptSig)); READWRITE(nSequence); } friend bool operator==(const CTxIn& a, const CTxIn& b) { return (a.prevout == b.prevout && a.scriptSig == b.scriptSig && a.nSequence == b.nSequence); } friend bool operator!=(const CTxIn& a, const CTxIn& b) { return !(a == b); } friend bool operator<(const CTxIn& a, const CTxIn& b) { return a.prevout<b.prevout; } std::string ToString() const; }; /** An output of a transaction. It contains the public key that the next input * must be able to sign with to claim it. */ class CTxOut { public: CAmount nValue; CScript scriptPubKey; int nRounds; CTxOut() { SetNull(); } CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(nValue); READWRITE(*(CScriptBase*)(&scriptPubKey)); } void SetNull() { nValue = -1; scriptPubKey.clear(); nRounds = -10; // an initial value, should be no way to get this by calculations } bool IsNull() const { return (nValue == -1); } CAmount GetDustThreshold(const CFeeRate &minRelayTxFee) const { // "Dust" is defined in terms of CTransaction::minRelayTxFee, which has units Eclips-per-kilobyte. // If you'd pay more than 1/3 in fees to spend something, then we consider it dust. // A typical spendable txout is 34 bytes big, and will need a CTxIn of at least 148 bytes to spend // i.e. total is 148 + 32 = 182 bytes. Default -minrelaytxfee is 1000 Eclips per kB // and that means that fee per spendable txout is 182 * 1000 / 1000 = 182 Eclips. // So dust is a spendable txout less than 546 * minRelayTxFee / 1000 (in Eclips) // i.e. 182 * 3 = 546 Eclips with default -minrelaytxfee = minRelayTxFee = 1000 Eclips per kB. if (scriptPubKey.IsUnspendable()) return 0; size_t nSize = GetSerializeSize(*this, SER_DISK, 0)+148u; return 3*minRelayTxFee.GetFee(nSize); } bool IsDust(const CFeeRate &minRelayTxFee) const { return (nValue < GetDustThreshold(minRelayTxFee)); } friend bool operator==(const CTxOut& a, const CTxOut& b) { return (a.nValue == b.nValue && a.scriptPubKey == b.scriptPubKey && a.nRounds == b.nRounds); } friend bool operator!=(const CTxOut& a, const CTxOut& b) { return !(a == b); } std::string ToString() const; }; struct CMutableTransaction; /** The basic transaction that is broadcasted on the network and contained in * blocks. A transaction can contain multiple inputs and outputs. */ class CTransaction { public: // Default transaction version. static const int32_t CURRENT_VERSION=2; // Changing the default transaction version requires a two step process: first // adapting relay policy by bumping MAX_STANDARD_VERSION, and then later date // bumping the default CURRENT_VERSION at which point both CURRENT_VERSION and // MAX_STANDARD_VERSION will be equal. static const int32_t MAX_STANDARD_VERSION=2; // The local variables are made const to prevent unintended modification // without updating the cached hash value. However, CTransaction is not // actually immutable; deserialization and assignment are implemented, // and bypass the constness. This is safe, as they update the entire // structure, including the hash. const int32_t nVersion; const std::vector<CTxIn> vin; const std::vector<CTxOut> vout; const uint32_t nLockTime; private: /** Memory only. */ const uint256 hash; uint256 ComputeHash() const; public: /** Construct a CTransaction that qualifies as IsNull() */ CTransaction(); /** Convert a CMutableTransaction into a CTransaction. */ CTransaction(const CMutableTransaction &tx); CTransaction(CMutableTransaction &&tx); template <typename Stream> inline void Serialize(Stream& s) const { s << this->nVersion; s << vin; s << vout; s << nLockTime; } /** This deserializing constructor is provided instead of an Unserialize method. * Unserialize is not possible, since it would require overwriting const fields. */ template <typename Stream> CTransaction(deserialize_type, Stream& s) : CTransaction(CMutableTransaction(deserialize, s)) {} bool IsNull() const { return vin.empty() && vout.empty(); } const uint256& GetHash() const { return hash; } // Return sum of txouts. CAmount GetValueOut() const; // GetValueIn() is a method on CCoinsViewCache, because // inputs must be known to compute value in. // Compute priority, given priority of inputs and (optionally) tx size double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const; // Compute modified tx size for priority calculation (optionally given tx size) unsigned int CalculateModifiedSize(unsigned int nTxSize=0) const; /** * Get the total transaction size in bytes, including witness data. * "Total Size" defined in BIP141 and BIP144. * @return Total transaction size in bytes */ unsigned int GetTotalSize() const; bool IsCoinBase() const { return (vin.size() == 1 && vin[0].prevout.IsNull()); } friend bool operator==(const CTransaction& a, const CTransaction& b) { return a.hash == b.hash; } friend bool operator!=(const CTransaction& a, const CTransaction& b) { return a.hash != b.hash; } std::string ToString() const; }; /** A mutable version of CTransaction. */ struct CMutableTransaction { int32_t nVersion; std::vector<CTxIn> vin; std::vector<CTxOut> vout; uint32_t nLockTime; CMutableTransaction(); CMutableTransaction(const CTransaction& tx); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(this->nVersion); READWRITE(vin); READWRITE(vout); READWRITE(nLockTime); } template <typename Stream> CMutableTransaction(deserialize_type, Stream& s) { Unserialize(s); } /** Compute the hash of this CMutableTransaction. This is computed on the * fly, as opposed to GetHash() in CTransaction, which uses a cached result. */ uint256 GetHash() const; std::string ToString() const; friend bool operator==(const CMutableTransaction& a, const CMutableTransaction& b) { return a.GetHash() == b.GetHash(); } friend bool operator!=(const CMutableTransaction& a, const CMutableTransaction& b) { return !(a == b); } }; typedef std::shared_ptr<const CTransaction> CTransactionRef; static inline CTransactionRef MakeTransactionRef() { return std::make_shared<const CTransaction>(); } template <typename Tx> static inline CTransactionRef MakeTransactionRef(Tx&& txIn) { return std::make_shared<const CTransaction>(std::forward<Tx>(txIn)); } /** Implementation of BIP69 * https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki */ struct CompareInputBIP69 { inline bool operator()(const CTxIn& a, const CTxIn& b) const { if (a.prevout.hash == b.prevout.hash) return a.prevout.n < b.prevout.n; uint256 hasha = a.prevout.hash; uint256 hashb = b.prevout.hash; typedef std::reverse_iterator<const unsigned char*> rev_it; rev_it rita = rev_it(hasha.end()); rev_it ritb = rev_it(hashb.end()); return std::lexicographical_compare(rita, rita + hasha.size(), ritb, ritb + hashb.size()); } }; struct CompareOutputBIP69 { inline bool operator()(const CTxOut& a, const CTxOut& b) const { return a.nValue < b.nValue || (a.nValue == b.nValue && a.scriptPubKey < b.scriptPubKey); } }; #endif // BITCOIN_PRIMITIVES_TRANSACTION_H
[ "eclipsim777@protonmail.com" ]
eclipsim777@protonmail.com
7dce0b4b22e82313823b10e33cc05ca7dc6c066d
2eb3b66b421a1f4a18bcb72b69023a3166273ca1
/Project Euler/Triangular, pentagonal, and hexagonal/main.cc
8ffc8ddd5f114586702604f0565c7ee30fb4be64
[]
no_license
johnathan79717/competitive-programming
e1d62016e8b25d8bcb3d003bba6b1d4dc858a62f
3c8471b7ebb516147705bbbc4316a511f0fe4dc0
refs/heads/master
2022-05-07T20:34:21.959511
2022-03-31T15:20:28
2022-03-31T15:20:28
55,674,796
2
2
null
null
null
null
UTF-8
C++
false
false
1,049
cc
#include <iostream> #include <vector> using namespace std; int main() { // int T, P, H, dt, dp, dh; // T = P = H = 40755; // dt = 286; // dp = 496; // dh = 573; // do { // if(T <= P && T <= H) { // T += dt; // ++dt; // } // else if (P <= T && P <= H) { // P += dp; // dp += 3; // } // else { // H += dh; // dh += 4; // } // } while(T != P || P != H); // cout << T << endl; long long N, a, b; cin >> N >> a >> b; vector<long long> t; if(a == 3) { for(int i = 1; (long long)i*(i+1)/2 < N; i++) t.push_back((long long)i*(i+1)/2); } else { for(int i = 1; (long long)i*(2*i-1) < N; i++) { t.push_back((long long)i*(2*i-1)); } } vector<long long> p; for(int i = 1; (long long)i*(3*i-1)/2 < N; i++) { p.push_back((long long)i * (3*i-1) / 2); } int i = 0, j = 0; while(i < t.size() && j < p.size()) { if(t[i] < p[j]) i++; else if(t[i] > p[j]) j++; else { printf("%lld\n", t[i]); i++; j++; } } }
[ "johnathan79717@gmail.com" ]
johnathan79717@gmail.com
9ad781c8df2a10eebacd8fc829342b767e758703
627cd624fa23cdcb28b449b4c831cc1ff924da40
/Prims algo/Prims algo/stdafx.cpp
e0669ce15649465809610f698f019817318b6bfc
[]
no_license
Taha-Imtiaz/Data-Structures
5e7c09e0edae59f11610d45fbbbf71a35b695319
4b60f3f72df1dfc47b6518057820d46b883ee83f
refs/heads/master
2020-11-24T05:37:32.706901
2019-12-14T08:02:05
2019-12-14T08:02:05
227,987,081
0
0
null
null
null
null
UTF-8
C++
false
false
289
cpp
// stdafx.cpp : source file that includes just the standard includes // Prims algo.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "tahaimtiaz1996@gmail.com" ]
tahaimtiaz1996@gmail.com
201d6ff777cd9ada2657dbc853d88ce99eb63682
553847a2eb789346787d28c201f2d9936198c1a6
/test1/day0.cpp
3da12d0d3a39a2985cb554f6b84a5935ea147377
[]
no_license
chan4lk/image_processing_test1
91eabd2ba6fe6358a2ea45fa288fe7b7bddd7024
d05076b88185a7b10a7c51252b5ae3df8b0231d8
refs/heads/master
2016-08-04T11:45:58.417136
2015-05-07T06:19:18
2015-05-07T06:19:18
35,202,249
0
0
null
null
null
null
UTF-8
C++
false
false
4,038
cpp
#include "opencv\cv.h" #include "opencv\cvaux.h" #include "opencv\highgui.h" #include "opencv2\imgproc\imgproc.hpp"5y using namespace cv; int day0(){ Mat image = imread("grass.jpg"); Mat image2 = imread("day2.jpg"); if (!image.data){ printf("Could not open or find image!"); waitKey(0); return -1; } if (!image2.data){ printf("Could not open or find image!"); waitKey(0); return -1; } //print image details printf("image width: %d\n", image.cols); printf("image height: %d\n", image.rows); printf("image width step: %d\n", image.step); printf("image channels: %d\n", image.channels()); //access pixel Vec3b pixel = image.at<Vec3b>(10, 10); printf("blue: %d\n", pixel.val[0]); printf("green: %d\n", pixel.val[1]); printf("red: %d\n", pixel.val[2]); //make range white for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { Vec3b &intensity = image.at<Vec3b>(j, i); for (int k = 0; k < image.channels(); k++) { // change pixel value for all three channels intensity.val[k] = 255; } } } //replace image part for (int i = 100; i < 200; i++) { for (int j = 100; j < 200; j++) { Vec3b &intensity = image.at<Vec3b>(j, i); Vec3b &intensity2 = image2.at<Vec3b>(j, i); //pixel can be copied entirely without copying bgr values one by one intensity2 = intensity; /*for(int k = 0; k < image.channels(); k++) { intensity2.val[k] = intensity.val[k]; }*/ } } //convert to grayscale image Mat grayimage1(image.size(), CV_8U); //using inbuilt method cvtColor(image, grayimage1, CV_BGR2GRAY); //binaryimage1 > 128; //manual /*for (int i = 0; i < image.cols; i++) { for (int j = 0; j < image.rows; j++) { Vec3b pixel = image.at<Vec3b>(j, i); uchar &pixel2 = grayimage1.at<uchar>(j, i); pixel2 = uchar (0.299 * pixel.val[0] + 0.587 * pixel.val[1] + 0.115 * pixel.val[2]); } }*/ //negative image /*Mat negativeimage(image.size(), image.depth()); for (int i = 0; i < image.cols; i++) { for (int j = 0; j < image.rows; j++) { Vec3b pixel = image.at<Vec3b>(j, i); Vec3b &pixel2 = negativeimage.at<Vec3b>(j, i); /*pixel2.val[0] = pixel.val[0] - 255; pixel2.val[1] = pixel.val[1] - 255; pixel2.val[2] = pixel.val[2] - 255; } } //cvtColor(image, negativeimage, CV_inverse namedWindow("negativepenguins"); imshow("negativepenguins", negativeimage);*/ //histogram int grayvalues[256] = {}; for (int i = 0; i < grayimage1.cols; i++) { for (int j = 0; j < grayimage1.rows; j++) { int pixel = grayimage1.at<uchar>(j, i); grayvalues[pixel]++; } } printf("histogram\n"); for (int i = 0; i < 256; i++) { printf("%d: %d\n", i, grayvalues[i]); } //drawing graphical histogram double max = 10519; Mat histimage(500, 256, CV_8UC1, Scalar(255)); //normalizing int hist[256] = {}; for (int i = 0; i < 256; i++) { hist[i] = cvRound(grayvalues[i] / max * 500); line(histimage, Point(i, 500 - hist[i]), Point(i, 500), Scalar(0), 1, 8, 0); } //bin_w = cvRound (histogram_cols / 256); namedWindow("histogram"); imshow("histogram", histimage); //contrast stretching for (int i = 0; i < grayimage1.cols; i++) { for (int j = 0; j < grayimage1.rows; j++) { int px = grayimage1.at<uchar>(j, i); if (px < 150) { grayimage1.at<uchar>(j, i) = 0; } else { if (px >= 150 && px < 220) { grayimage1.at<uchar>(j, i) = uchar((px - 10) * 3.4 + 10); } else { grayimage1.at<uchar>(j, i) = uchar((px - 220) * 0.14 + 250); } } } } namedWindow("binarypenguins"); imshow("binarypenguins", grayimage1); namedWindow("penguins"); imshow("penguins", image); namedWindow("jellyfish"); imshow("jellyfish", image2); waitKey(0); destroyWindow("penguins"); destroyWindow("jellyfish"); destroyWindow("binarypenguins"); destroyWindow("negativepenguins"); destroyWindow("histogram"); return 0; }
[ "chan4lk@gmail.com" ]
chan4lk@gmail.com
f54e0c095cea41c8dec414d9275cc5f7a5c4ea5c
ae0ba9edf4616db289204163963eb951d4f7f109
/src/xsec/transformers/TXFMSB.cpp
32d5a35a9ada46a8ed8ad87c5853af27c73d5be6
[ "Apache-2.0", "OpenSSL" ]
permissive
odant/conan-xmlsec
deac7c7b50c09eca7371cb284d8e84c316d0e9ee
4a3af78f8186102b1278fbd2c0cdf42da7a2dd1b
refs/heads/master
2022-12-08T14:11:45.094661
2020-10-22T12:21:13
2020-10-22T12:21:13
199,825,387
2
0
null
null
null
null
UTF-8
C++
false
false
2,658
cpp
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. 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. */ /* * XSEC * * TXFMSB := Class that takes an input safeBuffer to start a transform pipe * * $Id: TXFMSB.cpp 1817117 2017-12-04 19:03:16Z scantor $ * */ #include <xsec/transformers/TXFMSB.hpp> XERCES_CPP_NAMESPACE_USE // General includes #include <memory.h> TXFMSB::TXFMSB(DOMDocument *doc) : TXFMBase(doc) { toOutput = 0; } TXFMSB::~TXFMSB() { } // Methods to set the inputs void TXFMSB::setInput(TXFMBase *newInput) { // We're the start of the actual data pipe, but we need to track // the pointer for chain disposal. input = newInput; return; } void TXFMSB::setInput(const safeBuffer& sbIn) { // Assume this is a string sb = sbIn; toOutput = sb.sbStrlen(); sbs = toOutput; } void TXFMSB::setInput(const safeBuffer& sbIn, unsigned int sbSize) { // Assume this is a string sb = sbIn; if (sbSize > sb.sbRawBufferSize()) toOutput = sb.sbRawBufferSize(); else toOutput = sbSize; sbs = toOutput; } // Methods to get tranform output type and input requirement TXFMBase::ioType TXFMSB::getInputType(void) const { return TXFMBase::BYTE_STREAM; } TXFMBase::ioType TXFMSB::getOutputType(void) const { return TXFMBase::BYTE_STREAM; } TXFMBase::nodeType TXFMSB::getNodeType(void) const { return TXFMBase::DOM_NODE_NONE; } // Methods to get output data unsigned int TXFMSB::readBytes(XMLByte * const toFill, unsigned int maxToFill) { // Return from the buffer unsigned int ret; if (toOutput == 0) return 0; // Check if we can just output everything left if (toOutput <= maxToFill) { memcpy((char *) toFill, &(sb.rawBuffer()[sbs - toOutput]), toOutput); ret = (unsigned int) toOutput; toOutput = 0; return ret; } // Output just some memcpy((char *) toFill, &(sb.rawBuffer()[sbs - toOutput]), maxToFill); ret = maxToFill; toOutput -= maxToFill; return ret; }
[ "" ]
f6f6d6bcd8134c24d122ff8b224d331790479210
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/ipc/ipc_mojo_perftest.cc
87c5ccc4c7a1e63b2755b5ae25ab6418a2e45804
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
3,407
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <memory> #include "base/memory/ptr_util.h" #include "base/process/process_metrics.h" #include "base/run_loop.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "ipc/ipc_channel_mojo.h" #include "ipc/ipc_perftest_support.h" #include "mojo/edk/embedder/embedder.h" #include "mojo/edk/embedder/platform_channel_pair.h" #include "mojo/edk/test/multiprocess_test_helper.h" #include "mojo/edk/test/scoped_ipc_support.h" namespace IPC { namespace { class MojoChannelPerfTest : public test::IPCChannelPerfTestBase { public: void TearDown() override { ipc_support_.reset(); test::IPCChannelPerfTestBase::TearDown(); } std::unique_ptr<ChannelFactory> CreateChannelFactory( const ChannelHandle& handle, base::SingleThreadTaskRunner* runner) override { ipc_support_.reset(new mojo::edk::test::ScopedIPCSupport(io_task_runner())); return ChannelMojo::CreateServerFactory( helper_.StartChild("MojoPerfTestClient"), runner); } bool StartClient() override { return true; } bool WaitForClientShutdown() override { return helper_.WaitForChildTestShutdown(); } mojo::edk::test::MultiprocessTestHelper helper_; std::unique_ptr<mojo::edk::test::ScopedIPCSupport> ipc_support_; }; TEST_F(MojoChannelPerfTest, ChannelPingPong) { RunTestChannelPingPong(GetDefaultTestParams()); base::RunLoop run_loop; run_loop.RunUntilIdle(); } TEST_F(MojoChannelPerfTest, ChannelProxyPingPong) { RunTestChannelProxyPingPong(GetDefaultTestParams()); base::RunLoop run_loop; run_loop.RunUntilIdle(); } // Test to see how many channels we can create. TEST_F(MojoChannelPerfTest, DISABLED_MaxChannelCount) { #if defined(OS_POSIX) LOG(INFO) << "base::GetMaxFds " << base::GetMaxFds(); base::SetFdLimit(20000); #endif std::vector<mojo::edk::PlatformChannelPair*> channels; for (size_t i = 0; i < 10000; ++i) { LOG(INFO) << "channels size: " << channels.size(); channels.push_back(new mojo::edk::PlatformChannelPair()); } } class MojoPerfTestClient : public test::PingPongTestClient { public: typedef test::PingPongTestClient SuperType; MojoPerfTestClient(); std::unique_ptr<Channel> CreateChannel(Listener* listener) override; int Run(MojoHandle handle); private: mojo::edk::test::ScopedIPCSupport ipc_support_; mojo::ScopedMessagePipeHandle handle_; }; MojoPerfTestClient::MojoPerfTestClient() : ipc_support_(base::ThreadTaskRunnerHandle::Get()) { mojo::edk::test::MultiprocessTestHelper::ChildSetup(); } std::unique_ptr<Channel> MojoPerfTestClient::CreateChannel(Listener* listener) { return ChannelMojo::Create(std::move(handle_), Channel::MODE_CLIENT, listener); } int MojoPerfTestClient::Run(MojoHandle handle) { handle_ = mojo::MakeScopedHandle(mojo::MessagePipeHandle(handle)); return RunMain(); } MULTIPROCESS_TEST_MAIN(MojoPerfTestClientTestChildMain) { MojoPerfTestClient client; int rv = mojo::edk::test::MultiprocessTestHelper::RunClientMain( base::Bind(&MojoPerfTestClient::Run, base::Unretained(&client))); base::RunLoop run_loop; run_loop.RunUntilIdle(); return rv; } } // namespace } // namespace IPC
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
035899549ad578d3f03134984fb4eac96d415f9e
46889ce97d827d287db87a85d543758096b1f814
/src/materialsystem/shaderapidx11/TextureDx11.cpp
8337c6ee1aa0280209ba85bcc365205413578714
[]
no_license
lachbr/SourceEngine
8dbaf562fe0e8c3ca33b2f077420f15823177808
e1bab45d8e9774fe2fe473448009dbd59becd0e8
refs/heads/master
2022-04-10T19:33:46.206407
2020-02-29T22:18:32
2020-02-29T22:18:32
240,649,072
0
0
null
2020-02-16T00:15:05
2020-02-15T05:15:58
C++
UTF-8
C++
false
false
21,538
cpp
#include "TextureDx11.h" #include "shaderapi/ishaderapi.h" #include "shaderdevicedx11.h" #include "shaderapidx11_global.h" #include "shaderapi/ishaderutil.h" #include "filesystem.h" #include "bitmap/tgawriter.h" // NOTE: This has to be the last file included! #include "tier0/memdbgon.h" // We will have to convert srcFormat into what this function // returns for use in D3D11. ImageFormat GetClosestSupportedImageFormatForD3D11( ImageFormat srcFormat ) { switch ( srcFormat ) { case IMAGE_FORMAT_BGR888: return IMAGE_FORMAT_BGRA8888; case IMAGE_FORMAT_RGB888: return IMAGE_FORMAT_RGBA8888; default: return srcFormat; } } DXGI_FORMAT GetD3DFormat( ImageFormat format ) { switch ( format ) { // These are not exact but have the same number // of channels and bits-per-channel. case IMAGE_FORMAT_I8: return DXGI_FORMAT_R8_UNORM; case IMAGE_FORMAT_IA88: return DXGI_FORMAT_R8G8_UNORM; case IMAGE_FORMAT_UV88: return DXGI_FORMAT_R8G8_UNORM; case IMAGE_FORMAT_UVWQ8888: case IMAGE_FORMAT_UVLX8888: return DXGI_FORMAT_R8G8B8A8_UNORM; case IMAGE_FORMAT_NV_DST24: return DXGI_FORMAT_D24_UNORM_S8_UINT; // These ones match D3D. case IMAGE_FORMAT_A8: return DXGI_FORMAT_A8_UNORM; case IMAGE_FORMAT_DXT1: case IMAGE_FORMAT_DXT1_ONEBITALPHA: return DXGI_FORMAT_BC1_UNORM; case IMAGE_FORMAT_DXT3: return DXGI_FORMAT_BC2_UNORM; case IMAGE_FORMAT_DXT5: return DXGI_FORMAT_BC3_UNORM; case IMAGE_FORMAT_BGRA4444: return DXGI_FORMAT_B4G4R4A4_UNORM; case IMAGE_FORMAT_BGRX5551: return DXGI_FORMAT_B5G5R5A1_UNORM; case IMAGE_FORMAT_BGR565: return DXGI_FORMAT_B5G6R5_UNORM; case IMAGE_FORMAT_BGRX8888: return DXGI_FORMAT_B8G8R8X8_UNORM; case IMAGE_FORMAT_BGRA8888: return DXGI_FORMAT_B8G8R8A8_UNORM; case IMAGE_FORMAT_RGBA16161616F: return DXGI_FORMAT_R16G16B16A16_FLOAT; case IMAGE_FORMAT_RGBA16161616: return DXGI_FORMAT_R16G16B16A16_UNORM; case IMAGE_FORMAT_R32F: return DXGI_FORMAT_R32_FLOAT; case IMAGE_FORMAT_RGBA32323232F: return DXGI_FORMAT_R32G32B32A32_FLOAT; case IMAGE_FORMAT_RGBA8888: return DXGI_FORMAT_R8G8B8A8_UNORM; default: return DXGI_FORMAT_UNKNOWN; } } ImageFormat GetImageFormat( DXGI_FORMAT d3dFormat ) { switch ( d3dFormat ) { case DXGI_FORMAT_UNKNOWN: return IMAGE_FORMAT_UNKNOWN; // These are not exact but have the same number // of channels and bits-per-channel. case DXGI_FORMAT_R8_UNORM: return IMAGE_FORMAT_I8; case DXGI_FORMAT_R8G8_UNORM: return IMAGE_FORMAT_IA88; //case DXGI_FORMAT_R8G8_UNORM: // return IMAGE_FORMAT_UV88; case DXGI_FORMAT_R8G8B8A8_UNORM: return IMAGE_FORMAT_UVWQ8888; case DXGI_FORMAT_A8_UNORM: return IMAGE_FORMAT_A8; case DXGI_FORMAT_BC1_UNORM: return IMAGE_FORMAT_DXT1_ONEBITALPHA; case DXGI_FORMAT_BC2_UNORM: return IMAGE_FORMAT_DXT3; case DXGI_FORMAT_BC3_UNORM: return IMAGE_FORMAT_DXT5; case DXGI_FORMAT_B4G4R4A4_UNORM: return IMAGE_FORMAT_BGRA4444; case DXGI_FORMAT_B5G6R5_UNORM: return IMAGE_FORMAT_BGR565; case DXGI_FORMAT_B8G8R8X8_UNORM: return IMAGE_FORMAT_BGRX8888; case DXGI_FORMAT_B8G8R8A8_UNORM: return IMAGE_FORMAT_BGRA8888; case DXGI_FORMAT_R16G16B16A16_FLOAT: return IMAGE_FORMAT_RGBA16161616F; case DXGI_FORMAT_R16G16B16A16_UNORM: return IMAGE_FORMAT_RGBA16161616; case DXGI_FORMAT_R32_FLOAT: return IMAGE_FORMAT_R32F; case DXGI_FORMAT_R32G32B32A32_FLOAT: return IMAGE_FORMAT_RGBA32323232F; } } // Texture2D is used for regular 2D textures, cubemaps, and 2D texture arrays // TODO: Support 1D and 3D textures? ID3D11Resource *CreateD3DTexture( int width, int height, int nDepth, ImageFormat dstFormat, int numLevels, int nCreationFlags ) { if ( nDepth <= 0 ) nDepth = 1; bool isCubeMap = ( nCreationFlags & TEXTURE_CREATE_CUBEMAP ) != 0; if ( isCubeMap ) nDepth = 6; bool bIsRenderTarget = ( nCreationFlags & TEXTURE_CREATE_RENDERTARGET ) != 0; bool bManaged = ( nCreationFlags & TEXTURE_CREATE_MANAGED ) != 0; bool bIsDepthBuffer = ( nCreationFlags & TEXTURE_CREATE_DEPTHBUFFER ) != 0; bool isDynamic = ( nCreationFlags & TEXTURE_CREATE_DYNAMIC ) != 0; bool bAutoMipMap = ( nCreationFlags & TEXTURE_CREATE_AUTOMIPMAP ) != 0; bool bVertexTexture = ( nCreationFlags & TEXTURE_CREATE_VERTEXTEXTURE ) != 0; bool bAllowNonFilterable = ( nCreationFlags & TEXTURE_CREATE_UNFILTERABLE_OK ) != 0; bool bVolumeTexture = ( nDepth > 1 ); bool bIsFallback = ( nCreationFlags & TEXTURE_CREATE_FALLBACK ) != 0; bool bNoD3DBits = ( nCreationFlags & TEXTURE_CREATE_NOD3DMEMORY ) != 0; // NOTE: This function shouldn't be used for creating depth buffers! //Assert( !bIsDepthBuffer ); dstFormat = GetClosestSupportedImageFormatForD3D11( dstFormat ); DXGI_FORMAT d3dFormat = DXGI_FORMAT_UNKNOWN; d3dFormat = GetD3DFormat( dstFormat ); if ( d3dFormat == DXGI_FORMAT_UNKNOWN ) { Warning( "ShaderAPIDX11::CreateD3DTexture: Invalid image format %i!\n", (int)dstFormat ); Assert( 0 ); return 0; } D3D11_USAGE usage = D3D11_USAGE_DEFAULT; if ( isDynamic ) { usage = D3D11_USAGE_DYNAMIC; } UINT miscFlags = 0; if ( bAutoMipMap ) { miscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS; } if ( isCubeMap ) { miscFlags |= D3D11_RESOURCE_MISC_TEXTURECUBE; } UINT bindFlags = D3D11_BIND_SHADER_RESOURCE; if ( bIsRenderTarget ) { bindFlags = D3D11_BIND_RENDER_TARGET; } if ( bIsDepthBuffer ) { bindFlags = D3D11_BIND_DEPTH_STENCIL; } UINT cpuAccessFlags = 0; if ( !bIsDepthBuffer && !bIsRenderTarget ) { cpuAccessFlags = D3D11_CPU_ACCESS_WRITE; } ID3D11Resource *pBaseTexture = NULL; HRESULT hr = S_OK; // TODO: Support 1D and 3D textures // (2D textures are good for regular textures, cubemaps, and texture arrays) D3D11_TEXTURE2D_DESC desc; ZeroMemory( &desc, sizeof( D3D11_TEXTURE3D_DESC ) ); desc.ArraySize = nDepth; desc.Format = d3dFormat; desc.Width = width; desc.Height = height; desc.MipLevels = numLevels; desc.MiscFlags = miscFlags; desc.BindFlags = bindFlags; desc.CPUAccessFlags = cpuAccessFlags; desc.Usage = usage; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; ID3D11Texture2D *pTex2D = NULL; hr = D3D11Device()->CreateTexture2D( &desc, NULL, &pTex2D ); pBaseTexture = pTex2D; if ( FAILED( hr ) ) { switch ( hr ) { case E_OUTOFMEMORY: Warning( "TextureDx11::CreateD3DTexture: E_OUTOFMEMORY\n" ); break; default: break; } return 0; } //s_TextureCount++; return pBaseTexture; } void DestroyD3DTexture( ID3D11Resource *pD3DTex ) { if ( pD3DTex ) { int ref = pD3DTex->Release(); Assert( ref == 0 ); //s_TextureCount--; } } //----------------------------------- // Dx11 implementation of a texture //----------------------------------- CTextureDx11::CTextureDx11() { m_nFlags = 0; m_Count = 0; m_CountIndex = 0; m_nTimesBoundMax = 0; m_nTimesBoundThisFrame = 0; m_Anisotropy = 0; m_Format = IMAGE_FORMAT_RGBA8888; m_MinFilter = SHADER_TEXFILTERMODE_LINEAR; m_MagFilter = SHADER_TEXFILTERMODE_LINEAR; m_UTexWrap = D3D11_TEXTURE_ADDRESS_CLAMP; m_VTexWrap = D3D11_TEXTURE_ADDRESS_CLAMP; m_WTexWrap = D3D11_TEXTURE_ADDRESS_CLAMP; m_Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; m_pTexture = NULL; m_ppTexture = NULL; m_pSamplerState = NULL; m_pView = NULL; m_ppView = NULL; m_pDepthStencilView = NULL; m_pRenderTargetView = NULL; } inline int CalcMipLevels( int w, int h ) { return ceil( log2( max( w, h ) ) ) + 1; } void CTextureDx11::SetupTexture2D( int width, int height, int depth, int count, int i, int flags, int numCopies, int numMipLevels, ImageFormat dstImageFormat ) { Log( "Making texture2D\n" ); bool bIsRenderTarget = ( flags & TEXTURE_CREATE_RENDERTARGET ) != 0; bool bIsDepthBuffer = ( flags & TEXTURE_CREATE_DEPTHBUFFER ) != 0; if ( bIsDepthBuffer ) { Log( "Making depth buffer\n" ); SetupDepthTexture( dstImageFormat, width, height, "depth", true ); return; } else if ( bIsRenderTarget ) { Log( "Making render target\n" ); SetupBackBuffer( width, height, "rendertarget", NULL, dstImageFormat ); return; } dstImageFormat = IMAGE_FORMAT_RGBA8888; //--------------------------------------------------------------------------------- if ( depth == 0 ) depth == 1; bool bIsCubeMap = ( flags & TEXTURE_CREATE_CUBEMAP ) != 0; if ( bIsCubeMap ) depth = 6; bool bIsDynamic = ( flags & TEXTURE_CREATE_DYNAMIC ) != 0; bool bAutoMipMap = ( flags & TEXTURE_CREATE_AUTOMIPMAP ) != 0; bool bIsManaged = ( flags & TEXTURE_CREATE_MANAGED ) != 0; // Can't be both managed + dynamic. Dynamic is an optimization, but // if it's not managed, then we gotta do special client-specific stuff // So, managed wins out! if ( bIsManaged ) bIsDynamic = false; if ( bAutoMipMap && numMipLevels == 0 ) { numMipLevels = CalcMipLevels( width, height ); } m_iTextureType = TEXTURE_STANDARD; m_iTextureDimensions = TEXTURE_2D; unsigned short usSetFlags = 0; usSetFlags |= ( flags & TEXTURE_CREATE_VERTEXTEXTURE ) ? CTextureDx11::IS_VERTEX_TEXTURE : 0; m_nFlags = CTextureDx11::IS_ALLOCATED; m_nWidth = width; m_nHeight = height; m_Depth = depth; m_Count = count; m_CountIndex = i; m_CreationFlags = flags; m_nFlags |= usSetFlags; ID3D11Resource *pD3DTex; // Set the initial texture state if ( numCopies <= 1 ) { m_NumCopies = 1; pD3DTex = CreateD3DTexture( width, height, depth, dstImageFormat, numMipLevels, flags ); SetTexture( pD3DTex ); } else { m_NumCopies = numCopies; m_ppTexture = new ID3D11Resource * [numCopies]; for ( int k = 0; k < numCopies; k++ ) { pD3DTex = CreateD3DTexture( width, height, depth, dstImageFormat, numMipLevels, flags ); SetTexture( k, pD3DTex ); } } m_CurrentCopy = 0; if ( m_NumCopies == 1 ) pD3DTex = m_pTexture; else pD3DTex = m_ppTexture[m_CurrentCopy]; m_Format = dstImageFormat; m_UTexWrap = D3D11_TEXTURE_ADDRESS_CLAMP; m_VTexWrap = D3D11_TEXTURE_ADDRESS_CLAMP; m_WTexWrap = D3D11_TEXTURE_ADDRESS_CLAMP; m_NumLevels = numMipLevels; m_Filter = ( numMipLevels != 1 ) ? D3D11_FILTER_MIN_MAG_MIP_LINEAR : D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; m_SwitchNeeded = false; AdjustSamplerState(); MakeView(); } void CTextureDx11::SetupDepthTexture( ImageFormat renderFormat, int width, int height, const char *pDebugName, bool bTexture ) { m_nFlags = CTextureDx11::IS_ALLOCATED; if ( bTexture ) m_nFlags |= CTextureDx11::IS_DEPTH_STENCIL_TEXTURE; else m_nFlags |= CTextureDx11::IS_DEPTH_STENCIL; m_iTextureType = TEXTURE_DEPTHSTENCIL; m_iTextureDimensions = TEXTURE_3D; m_nWidth = width; m_nHeight = height; m_Depth = 1; m_Count = 1; m_CountIndex = 0; m_CreationFlags = TEXTURE_CREATE_DEPTHBUFFER; m_Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; m_NumLevels = 1; m_NumCopies = 1; m_CurrentCopy = 0; m_pTexture = CreateD3DTexture( width, height, m_Depth, renderFormat, m_NumLevels, m_CreationFlags ); AdjustSamplerState(); MakeDepthStencilView(); if ( bTexture ) { MakeView(); } } void CTextureDx11::SetupBackBuffer( int width, int height, const char *pDebugName, ID3D11Texture2D *pBackBuffer, ImageFormat format ) { m_nFlags = CTextureDx11::IS_ALLOCATED; m_iTextureType = TEXTURE_RENDERTARGET; m_iTextureDimensions = TEXTURE_2D; m_nWidth = width; m_nHeight = height; m_Depth = 1; m_Count = 1; m_CountIndex = 0; m_CreationFlags = TEXTURE_CREATE_RENDERTARGET; m_Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; m_NumLevels = 1; m_NumCopies = 1; m_CurrentCopy = 0; if ( pBackBuffer ) m_pTexture = pBackBuffer; else m_pTexture = CreateD3DTexture( width, height, m_Depth, format, m_NumLevels, m_CreationFlags ); AdjustSamplerState(); MakeRenderTargetView(); MakeView(); } void CTextureDx11::SetMinFilter( ShaderTexFilterMode_t texFilterMode ) { m_MinFilter = texFilterMode; AdjustD3DFilter(); } void CTextureDx11::SetMagFilter( ShaderTexFilterMode_t texFilterMode ) { m_MagFilter = texFilterMode; AdjustD3DFilter(); } void CTextureDx11::SetWrap( ShaderTexCoordComponent_t coord, ShaderTexWrapMode_t wrapMode ) { D3D11_TEXTURE_ADDRESS_MODE address; switch ( wrapMode ) { case SHADER_TEXWRAPMODE_CLAMP: address = D3D11_TEXTURE_ADDRESS_CLAMP; break; case SHADER_TEXWRAPMODE_REPEAT: address = D3D11_TEXTURE_ADDRESS_WRAP; break; case SHADER_TEXWRAPMODE_BORDER: address = D3D11_TEXTURE_ADDRESS_BORDER; break; default: address = D3D11_TEXTURE_ADDRESS_CLAMP; Warning( "CTextureDx11::SetWrap: unknown wrapMode %i\n", wrapMode ); break; } switch ( coord ) { case SHADER_TEXCOORD_S: m_UTexWrap = address; break; case SHADER_TEXCOORD_T: m_VTexWrap = address; break; case SHADER_TEXCOORD_U: m_WTexWrap = address; break; default: Warning( "CTextureDx11::SetWrap: unknown coord %i\n", coord ); break; } AdjustSamplerState(); } void CTextureDx11::AdjustD3DFilter() { // Determines the D3D11 filter from the specified combination // of min and mag filter on the texture. // Non-mip combinations if ( m_MinFilter == SHADER_TEXFILTERMODE_NEAREST && m_MagFilter == SHADER_TEXFILTERMODE_NEAREST ) { m_Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; } else if ( m_MinFilter == SHADER_TEXFILTERMODE_LINEAR && m_MagFilter == SHADER_TEXFILTERMODE_LINEAR ) { m_Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; } else if ( m_MinFilter == SHADER_TEXFILTERMODE_NEAREST && m_MagFilter == SHADER_TEXFILTERMODE_LINEAR ) { m_Filter = D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT; } else if ( m_MinFilter == SHADER_TEXFILTERMODE_LINEAR && m_MagFilter == SHADER_TEXFILTERMODE_NEAREST ) { m_Filter = D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT; } // Linear_Mipmap combinations else if ( m_MinFilter == SHADER_TEXFILTERMODE_LINEAR_MIPMAP_LINEAR && m_MagFilter == SHADER_TEXFILTERMODE_LINEAR ) { m_Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; } else if ( m_MinFilter == SHADER_TEXFILTERMODE_LINEAR_MIPMAP_LINEAR && m_MagFilter == SHADER_TEXFILTERMODE_NEAREST ) { m_Filter = D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR; } else if ( m_MinFilter == SHADER_TEXFILTERMODE_LINEAR_MIPMAP_NEAREST && m_MagFilter == SHADER_TEXFILTERMODE_LINEAR ) { m_Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; } else if ( m_MinFilter == SHADER_TEXFILTERMODE_LINEAR_MIPMAP_NEAREST && m_MagFilter == SHADER_TEXFILTERMODE_NEAREST ) { m_Filter = D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT; } // Nearest_Mipmap combinations else if ( m_MinFilter == SHADER_TEXFILTERMODE_NEAREST_MIPMAP_NEAREST && m_MagFilter == SHADER_TEXFILTERMODE_LINEAR ) { m_Filter = D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR; } else if ( m_MinFilter == SHADER_TEXFILTERMODE_NEAREST_MIPMAP_NEAREST && m_MagFilter == SHADER_TEXFILTERMODE_NEAREST ) { m_Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; } else if ( m_MinFilter == SHADER_TEXFILTERMODE_NEAREST_MIPMAP_LINEAR && m_MagFilter == SHADER_TEXFILTERMODE_LINEAR ) { m_Filter = D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR; } else if ( m_MinFilter == SHADER_TEXFILTERMODE_NEAREST_MIPMAP_LINEAR && m_MagFilter == SHADER_TEXFILTERMODE_NEAREST ) { m_Filter = D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR; } else { Warning( "CTextureDx11::AdjustD3DFilter: Invalid combination of min and mag filter. Min: %i, Mag: %i\n", m_MinFilter, m_MagFilter ); } AdjustSamplerState(); } void CTextureDx11::SetAnisotropicLevel( int level ) { m_Anisotropy = level; AdjustSamplerState(); } void CTextureDx11::AdjustSamplerState() { if ( m_pSamplerState ) m_pSamplerState->Release(); m_pSamplerState = NULL; D3D11_SAMPLER_DESC desc; ZeroMemory( &desc, sizeof( D3D11_SAMPLER_DESC ) ); desc.AddressU = m_UTexWrap; desc.AddressV = m_VTexWrap; desc.AddressW = m_WTexWrap; desc.Filter = m_Filter; desc.MaxAnisotropy = m_Anisotropy; HRESULT hr = D3D11Device()->CreateSamplerState( &desc, &m_pSamplerState ); if ( FAILED( hr ) ) { Warning( "CTextureDx11: Couldn't create sampler state!\n" ); } } void CTextureDx11::MakeRenderTargetView() { if ( m_iTextureType != TEXTURE_RENDERTARGET ) { return; } if ( m_pRenderTargetView ) { int ref = m_pRenderTargetView->Release(); Assert( ref == 0 ); } HRESULT hr = D3D11Device()->CreateRenderTargetView( m_pTexture, NULL, &m_pRenderTargetView ); if ( FAILED( hr ) ) { Warning( "Failed to make D3D render target view!\n" ); } } void CTextureDx11::MakeDepthStencilView() { if ( m_iTextureType != TEXTURE_DEPTHSTENCIL ) { return; } if ( m_pDepthStencilView ) { int ref = m_pDepthStencilView->Release(); Assert( ref == 0 ); } HRESULT hr = D3D11Device()->CreateDepthStencilView( m_pTexture, NULL, &m_pDepthStencilView ); if ( FAILED( hr ) ) { Warning( "Failed to make D3D depth stencil view!\n" ); } } void CTextureDx11::MakeView() { bool bGenMipMap = ( m_CreationFlags & TEXTURE_CREATE_AUTOMIPMAP ) != 0; if ( m_NumCopies > 1 ) { if ( m_ppView ) { delete[] m_ppView; } m_ppView = new ID3D11ShaderResourceView * [m_NumCopies]; for ( int copy = 0; copy < m_NumCopies; copy++ ) { HRESULT hr = D3D11Device()->CreateShaderResourceView( m_ppTexture[copy], NULL, &m_ppView[copy] ); if ( FAILED( hr ) ) { Warning( "Unable to create shader resource view for texture copy %i!\n", copy ); } if ( bGenMipMap && m_ppView[copy] ) { D3D11DeviceContext()->GenerateMips( m_ppView[copy] ); } } } else { if ( m_pView ) { m_pView->Release(); } m_pView = NULL; HRESULT hr = D3D11Device()->CreateShaderResourceView( m_pTexture, NULL, &m_pView ); if ( FAILED( hr ) ) { Warning( "Unable to create D3D11 Texture view!\n" ); } if ( bGenMipMap && m_pView ) { D3D11DeviceContext()->GenerateMips( m_pView ); } } } static int s_NumBlits = 0; void CTextureDx11::BlitSurfaceBits( CTextureDx11::TextureLoadInfo_t &info, int xOffset, int yOffset, int srcStride ) { CD3D11_BOX box; box.left = xOffset; box.right = xOffset + info.m_nWidth; box.top = yOffset; box.bottom = yOffset + info.m_nHeight; box.front = 0; box.back = 1; int mem = ImageLoader::GetMemRequired( info.m_nWidth, info.m_nHeight, info.m_nZOffset, m_Format, false ); unsigned char *pNewImage = new unsigned char[mem]; int dstStride = ImageLoader::SizeInBytes( m_Format ); bool ret = ShaderUtil()->ConvertImageFormat( info.m_pSrcData, info.m_SrcFormat, pNewImage, m_Format, info.m_nWidth, info.m_nHeight, srcStride ); if ( !ret ) { Warning( "Couldn't convert texture for uploading to D3D!\n" ); return; } #if 0 { int debugMem = ImageLoader::GetMemRequired( info.m_nWidth, info.m_nHeight, info.m_nZOffset, IMAGE_FORMAT_BGRA8888, false ); unsigned char *pDebugImage = new unsigned char[debugMem]; int debugStride = ImageLoader::SizeInBytes( IMAGE_FORMAT_BGRA8888 ); ShaderUtil()->ConvertImageFormat( info.m_pSrcData, info.m_SrcFormat, pDebugImage, IMAGE_FORMAT_BGRA8888, info.m_nWidth, info.m_nHeight, srcStride, debugStride ); char filename[50]; memset( filename, 0, 50 ); sprintf( filename, "C:\\Users\\Brian\\Desktop\\SourceDX11Debug\\BlitSurfaceBitsDebug-%i.tga", s_NumBlits++ ); TGAWriter::WriteTGAFile( filename, info.m_nWidth, info.m_nHeight, IMAGE_FORMAT_BGRA8888, pDebugImage, debugStride ); delete[] pDebugImage; } #endif Log( "CalcSubresource: level %i, face %i, num levels %i\n", info.m_nLevel, info.m_CubeFaceID, m_NumLevels ); UINT subresource = D3D11CalcSubresource( info.m_nLevel, info.m_CubeFaceID, m_NumLevels ); D3D11DeviceContext()->UpdateSubresource( info.m_pTexture, subresource, &box, pNewImage, dstStride * info.m_nWidth, dstStride * info.m_nWidth * info.m_nHeight ); delete[] pNewImage; } void CTextureDx11::BlitTextureBits( CTextureDx11::TextureLoadInfo_t &info, int xOffset, int yOffset, int srcStride ) { // TODO: Volume texture? //Assert( info.m_nZOffset == 0 ); if ( info.m_nZOffset != 0 ) { return; } BlitSurfaceBits( info, xOffset, yOffset, srcStride ); } void CTextureDx11::LoadTexImage( CTextureDx11::TextureLoadInfo_t &info, int xOffset, int yOffset, int srcStride ) { MEM_ALLOC_CREDIT(); Assert( info.m_pSrcData ); Assert( info.m_pTexture ); // Copy in the bits... BlitTextureBits( info, xOffset, yOffset, srcStride ); } void CTextureDx11::Delete() { int nDeallocated = 0; if ( m_NumCopies == 1 ) { if ( m_pView ) { int refCount = m_pView->Release(); Assert( refCount == 0 ); m_pView = 0; nDeallocated++; } if ( m_pTexture ) { DestroyD3DTexture( m_pTexture ); m_pTexture = 0; nDeallocated = 1; } } else { if ( m_ppView ) { for ( int i = 0; i < m_NumCopies; i++ ) { if ( m_ppView[i] ) { int refCount = m_ppView[i]->Release(); Assert( refCount == 0 ); nDeallocated++; } } delete[] m_ppView; m_ppView = NULL; } if ( m_ppTexture ) { // Multiple copy texture for ( int j = 0; j < m_NumCopies; j++ ) { if ( m_ppTexture[j] ) { DestroyD3DTexture( m_ppTexture[j] ); m_ppTexture[j] = 0; ++nDeallocated; } } delete[] m_ppTexture; m_ppTexture = NULL; } } if ( m_iTextureType == TEXTURE_RENDERTARGET ) { if ( m_pRenderTargetView ) { int refCount = m_pRenderTargetView->Release(); Assert( refCount == 0 ); m_pRenderTargetView = 0; nDeallocated++; } } else if ( m_iTextureType == TEXTURE_DEPTHSTENCIL ) { if ( m_pDepthStencilView ) { int refCount = m_pDepthStencilView->Release(); Assert( refCount == 0 ); m_pDepthStencilView = 0; nDeallocated++; } } if ( m_pSamplerState ) { m_pSamplerState->Release(); m_pSamplerState = 0; nDeallocated++; } m_NumCopies = 0; m_nFlags = 0; }
[ "brianlach72@gmail.com" ]
brianlach72@gmail.com
f0e56dc4a35ee353e4a21727ac6b1a9ba5bbb7fd
aae1d55e0b47b38db0c84c2b87888499a59e1bcb
/eco314/lab4/4/CVetor.h
23f2d7fa878cd6f7b71a6d68aac36e4b7f2f39a3
[]
no_license
sauloantuness/unifei
a530f6536243d23a2f391e46880fd24d83e88f58
84fa6530a2130e6ee7c9283c792cd0ef77ddde35
refs/heads/master
2020-04-10T06:44:28.910809
2014-07-19T15:56:45
2014-07-19T15:56:45
10,576,290
0
0
null
null
null
null
UTF-8
C++
false
false
558
h
#ifndef CVETOR_H #define CVETOR_H #include <iostream> using namespace std; class CVetor{ protected: int n; int *p; public: CVetor(); CVetor(int); CVetor(CVetor &); ~CVetor(){}; int size(){return n;}; int& operator[](int); bool operator>(CVetor &); bool operator<(CVetor &); bool operator>=(CVetor &); bool operator<=(CVetor &); bool operator==(CVetor &); bool operator!=(CVetor &); friend ostream& operator<<(ostream &output, CVetor); friend istream& operator>>(istream &input, CVetor &); }; #endif
[ "saulo@saulo-note.(none)" ]
saulo@saulo-note.(none)
46e311188c43437ac7710041d79b15b7f9c1e40f
f0a6186fcdbf7d8427c84bac5f6b6c003bb4ca04
/Estudiantes/Antonio/compiladorV01.cpp
02354b46715534f88dc4ecd519b0b377fc9a61ac
[]
no_license
billywalker182/C-Plus-Plus
062a02fec43bb3d46c2610eff1b4b36e3a7fba1e
f6283929632a3cd36988951da2cfe56afc9e3b81
refs/heads/master
2023-03-21T05:23:09.906974
2021-03-16T02:37:59
2021-03-16T02:37:59
321,184,242
0
0
null
null
null
null
UTF-8
C++
false
false
1,061
cpp
/** * Main program - Adapted to C++ * @author Helmuth Trefftz * @author Jose Luis Montoya */ #include <string> #include "parser.h" using namespace std; int main(int argc, char* argv[]) { if (argc > 1) { string strNombreArchivo = argv[1];// toma de argumnetos or send parameters Parser parser1(strNombreArchivo); parser1.program(); } // Crea un objeto en el heap --- Se REQUIERE INVOCAR el destructor para evitar memory leaks // Parser* parser = new Parser(strNombreArchivo); // Call the method associated with the starting symbol of the grammar // Como el objeto se creo como puntero en el heap (el famoso *), se debe acceder a los atributos mediante la -> // parser->program(); // Hace lo mismo que la linea anterior // (*parser).program(); // delete parser; // Crear el objeto localmente (en el stack). Cuando se crea así, se auto destruye cuando se deja el alcance (scope) actual // Como el objeto se creó local en el stack, se accede a los métodos (y atributos, si hubiera acceso directo) mediante . return 0; }
[ "jho_c27@hotmail.com" ]
jho_c27@hotmail.com
5b0d6effcb02c37a9590b0493e346350c9269b95
e55cb03adcf031d4367c29151c86bee203c59d16
/mainwindow.cpp
d609ca63e37af5df604cad33853b8489c212fd29
[]
no_license
wind-flower435/MediaAnalysisTool
2dde46df5418fc9c3c8e4cf9ca29598aaef3a52b
8ece457703a94d09f794d3ded6ee3dfdb43c8e6f
refs/heads/master
2023-08-02T03:47:34.291281
2021-09-24T07:58:36
2021-09-24T07:58:36
409,864,626
1
0
null
null
null
null
UTF-8
C++
false
false
6,744
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "ui_dialog.h" #include <QFileDialog> #include <QPainter> #include <QMessageBox> #include <QMatrix> #include <QToolTip> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->statusbar->addPermanentWidget(ui->SelectButton); ui->statusbar->addPermanentWidget(ui->MediaButton); ui->statusbar->addPermanentWidget(ui->InfoButton); ui->statusbar->addPermanentWidget(ui->isNotPausedButton); ui->statusbar->addPermanentWidget(ui->deviceButton); //ui->statusbar->setStyleSheet("background-color:black;color:white"); ui->SelectButton->setToolTip(QString::fromStdWString(L"选择存放ffmpeg与sdl2动态库目录")); ui->MediaButton->setToolTip(QString::fromStdWString(L"选择要播放的媒体文件")); ui->InfoButton->setToolTip(QString::fromStdWString(L"显示文件信息")); ui->isNotPausedButton->setToolTip(QString::fromStdWString(L"静音/取消静音")); ui->deviceButton->setToolTip(QString::fromStdWString(L"关闭/开启所有音频设备")); m_control = new control(); ui->isNotPausedButton->setText(m_control->isNotPausedButtonText); _conn(); } void MainWindow::_conn() { connect(ui->SelectButton, &QPushButton::clicked, this, &MainWindow::on_Selected_Clicked); connect(ui->MediaButton, &QPushButton::clicked, this, &MainWindow::on_Media_Clicked); connect(ui->InfoButton, &QPushButton::clicked, this, &MainWindow::on_Info_Clicked); connect(ui->isNotPausedButton, &QPushButton::clicked, this, [this] { this->m_control->isPausedAudio(); }); connect(ui->deviceButton, &QPushButton::clicked, this, [this] { this->m_control->changeAudioDevice(); }); //错误提示 connect(m_control, &control::noSupported, this, [this] { QMessageBox::critical(this, "Error", "The file is not a media file format"); }); //视频音频任意一个 connect(m_control, &control::noSuitVideoCodec, this, [this] { QMessageBox::critical(this, "Error", "Can't get this video decoder"); }); connect(m_control, &control::noSuitAudioCodec, this, [this] { QMessageBox::critical(this, "Error", "Can't get this video decoder"); }); connect(m_control, &control::Custom_Signal, this, [this](QString Qstr) { QMessageBox::critical(this, "Error", Qstr); }); // connect(m_control, &control::s, this, &MainWindow::slotGetOneFrame); connect(m_control, &control::changeButtonText, this, [this] { ui->isNotPausedButton->setText(m_control->isNotPausedButtonText); }); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_Selected_Clicked() { srcDirPath = QFileDialog::getExistingDirectory(this, "choose src Directory", "./"); if (srcDirPath.isEmpty()) return; QDir dir(srcDirPath); dir.setFilter(QDir::Files); dir.setSorting(QDir::Name); dir.setNameFilters(QStringList("*.dll")); if (dir.isEmpty()) { QMessageBox::critical(this, "Error", QString::fromStdWString(L"未检测到dll文件")); return; } QStringList temp = dir.entryList(); for (int i = 0; i < temp.size(); i++) { m_control->getVideoHandle()->m_help->rec.append(temp[i]); m_control->getAudioHandle()->m_help->rec.append(temp[i]); } srcDirPath.replace('/', "\\\\"); m_control->getVideoHandle()->m_help->loadFfmpegDll(srcDirPath); m_control->getAudioHandle()->m_help->loadFfmpegDll(srcDirPath); m_control->getAudioHandle()->loadSDL(srcDirPath); QMessageBox::information(this, " ", QString::fromStdWString(L"动态库加载完成")); } void MainWindow::on_Media_Clicked() { if (m_control->getVideoHandle()->m_help->dllMap.empty() && m_control->getAudioHandle()->m_help->dllMap.empty()) { QMessageBox::critical(this, "Error", QString::fromStdWString(L"未加载所需dll !")); return; } m_control->forceFinishPlay(); QString MediaPath = QFileDialog::getOpenFileName(this, "choose a media file", "./", "All files(*.*)"); if (MediaPath.isEmpty()) return; MediaPath.replace('/', "\\\\"); m_control->getVideoHandle()->getFileName(MediaPath.toStdString()); m_control->getAudioHandle()->getFileName(MediaPath.toStdString()); m_control->begin(); m_control->getMediaInfo(); m_control->play(); } void MainWindow::on_Info_Clicked() { this->dial = new Dialog(this); #define INSERT(s, info) \ dial->ui->textEdit->append(QString::fromStdWString(L#s)); \ dial->ui->textEdit->insertPlainText(info) INSERT(容器:, m_control->m_format); INSERT(时长:, QString::number(m_control->m_duration, 10, 3) + "s"); INSERT(总帧数:, QString::number(m_control->m_frameNums)); if (m_control->getVideoHandle()->videoIndex >= 0 && m_control->getAudioHandle()->audioIndex < 0) { INSERT(视频编码:, m_control->m_videoDecode); INSERT(旋转角度:, QString::number(m_control->m_rotate)); INSERT(帧率:, QString::number(m_control->m_frameRate, 10, 3)); dial->show(); return; } if (m_control->getVideoHandle()->videoIndex < 0 && m_control->getAudioHandle()->audioIndex >= 0) { INSERT(音频编码:, m_control->m_audioDecode); dial->show(); return; } INSERT(视频编码:, m_control->m_videoDecode); INSERT(旋转角度:, QString::number(m_control->m_rotate)); INSERT(帧率:, QString::number(m_control->m_frameRate, 10, 3)); INSERT(音频编码:, m_control->m_audioDecode); dial->show(); #undef INSERT return; } void MainWindow::showFileError() { double num = (std::max)(m_control->getVideoHandle()->m_realVideoDuration, m_control->getAudioHandle()->m_realAudioDuration); QMessageBox::critical(this, "Error", "Media file have error,currently playing to:" + QString::number(num, 10, 3) + "s"); } void MainWindow::slotGetOneFrame(QImage &img) { mImage = img; update(); } void MainWindow::paintEvent(QPaintEvent *event) { QPainter painter(this); if (m_control->m_rotate > 0) { QMatrix matrix; matrix.rotate(m_control->m_rotate); mImage = mImage.transformed(matrix, Qt::FastTransformation); } painter.setBrush(Qt::white); painter.drawRect(0, 0, this->width(), this->height()); if (mImage.size().width() <= 0) return; const QImage &img = mImage.scaled(this->size(), Qt::KeepAspectRatio); int x = this->width() - img.width(); int y = this->height() - img.height(); x /= 2; y /= 2; painter.drawImage(QPoint(x, y), img); }
[ "19sliu@stu.edu.cn" ]
19sliu@stu.edu.cn
7677c647bb5f19879977e886135dd366225afd08
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
/released_plugins/v3d_plugins/bigneuron_AmosSironi_PrzemyslawGlowacki_SQBTree_plugin/libs/ITK_include/itkMultipleValuedVnlCostFunctionAdaptor.h
c53f8ba24fa95b9e3bec2a03111b87d8e84544c8
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
Vaa3D/vaa3d_tools
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
e6974d5223ae70474efaa85e1253f5df1814fae8
refs/heads/master
2023-08-03T06:12:01.013752
2023-08-02T07:26:01
2023-08-02T07:26:01
50,527,925
107
86
MIT
2023-05-22T23:43:48
2016-01-27T18:19:17
C++
UTF-8
C++
false
false
5,544
h
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkMultipleValuedVnlCostFunctionAdaptor_h #define __itkMultipleValuedVnlCostFunctionAdaptor_h #include "itkMultipleValuedCostFunction.h" #include "vnl/vnl_least_squares_function.h" namespace itk { /** \class MultipleValuedVnlCostFunctionAdaptor * \brief This class is an Adaptor that allows to pass * itk::MultipleValuedCostFunctions to vnl_optimizers expecting * a vnl_cost_function. * * This class returns a single valued. * * \ingroup Numerics Optimizers * \ingroup ITKOptimizers */ class MultipleValuedVnlCostFunctionAdaptor: public vnl_least_squares_function { public: /** InternalParametersType typedef. */ typedef vnl_vector< double > InternalParametersType; /** InternalMeasureType typedef. */ typedef vnl_vector< double > InternalMeasureType; /** InternalGradientType typedef. */ typedef vnl_matrix< double > InternalDerivativeType; /** MeasureType of the MultipleValuedCostFunction */ typedef MultipleValuedCostFunction::MeasureType MeasureType; /** Parameters of the MultipleValuedCostFunction */ typedef MultipleValuedCostFunction::ParametersType ParametersType; /** Derivatives of the MultipleValuedCostFunction */ typedef MultipleValuedCostFunction::DerivativeType DerivativeType; /** Scales typedef */ typedef Array< double > ScalesType; /** Constructor with size */ MultipleValuedVnlCostFunctionAdaptor(unsigned int spaceDimension, unsigned int numberOfValues); /** Set the CostFunction deriving from MultipleValuedCostFunction */ void SetCostFunction(MultipleValuedCostFunction *costFunction) { m_CostFunction = costFunction; } /** Get the CostFunction deriving from MultipleValuedCostFunction */ const MultipleValuedCostFunction * GetCostFunction(void) const { return m_CostFunction; } /** Delegate computation of the value to the CostFunction. */ virtual void f(const InternalParametersType & inparameters, InternalMeasureType & measures); /** Delegate computation of the gradient to the costFunction. */ virtual void gradf(const InternalParametersType & inparameters, InternalDerivativeType & gradient); /** Delegate computation of value and gradient to the costFunction. */ virtual void compute(const InternalParametersType & x, InternalMeasureType *f, InternalDerivativeType *g); /** Convert external derviative measures into internal type */ void ConvertExternalToInternalGradient( const DerivativeType & input, InternalDerivativeType & output); /** Convert external measures into internal type */ void ConvertExternalToInternalMeasures( const MeasureType & input, InternalMeasureType & output); /** Define if the Cost function should provide a customized Gradient computation or the gradient can be computed internally using a default approach */ void SetUseGradient(bool); void UseGradientOn() { this->SetUseGradient(true); } void UseGradientOff() { this->SetUseGradient(false); } bool GetUseGradient() const; /** Set current parameters scaling. */ void SetScales(const ScalesType & scales); /** This AddObserver method allows to simulate that this class derives from * an itkObject for the purpose of reporting iteration events. The goal of * this method is to allow ITK-vnl optimizer adaptors to get iteration events * despite the fact that VNL does not provide callbacks. */ unsigned long AddObserver(const EventObject & event, Command *) const; /** Return the value of the last evaluation to the value of the cost function. * Note that this method DOES NOT triggers a computation of the function or * the derivatives, it only returns previous values. Therefore the values here * are only valid after you invoke the f() or gradf() methods. */ const MeasureType & GetCachedValue() const; const DerivativeType & GetCachedDerivative() const; const ParametersType & GetCachedCurrentParameters() const; protected: /** This method is intended to be called by the derived classes in order to * notify of an iteration event to any Command/Observers */ void ReportIteration(const EventObject & event) const; private: /** Get current parameters scaling. */ itkGetConstReferenceMacro(InverseScales, ScalesType); MultipleValuedCostFunction::Pointer m_CostFunction; bool m_ScalesInitialized; ScalesType m_InverseScales; Object::Pointer m_Reporter; mutable MeasureType m_CachedValue; mutable DerivativeType m_CachedDerivative; mutable ParametersType m_CachedCurrentParameters; }; // end of Class CostFunction } // end namespace itk #endif
[ "amos.sironi@gmail.com" ]
amos.sironi@gmail.com
d4352b779c2736f54b4152cd09052c270f420710
6c4e391046022177244aeade63b03fc0824a4c50
/services/resource_coordinator/coordination_unit/coordination_unit_impl.cc
f5f79a7817f573a54dd1b47debc0595ef67a43e8
[ "BSD-3-Clause" ]
permissive
woshihoujinxin/chromium-2
d17cae43153d14673778bbdf0b739886d2461902
71aec55e801f801f89a81cfb219a219d953a5d5c
refs/heads/master
2022-11-15T00:18:39.821920
2017-07-14T19:59:33
2017-07-14T19:59:33
97,331,019
1
0
null
2017-07-15T17:16:35
2017-07-15T17:16:35
null
UTF-8
C++
false
false
9,567
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/resource_coordinator/coordination_unit/coordination_unit_impl.h" #include <unordered_map> #include "base/strings/string_number_conversions.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "services/resource_coordinator/coordination_unit/coordination_unit_graph_observer.h" #include "services/resource_coordinator/public/cpp/coordination_unit_id.h" namespace resource_coordinator { #define NOTIFY_OBSERVERS(observers, Method, ...) \ for (auto& observer : observers) { \ observer.Method(__VA_ARGS__); \ } namespace { using CUIDMap = std::unordered_map<CoordinationUnitID, CoordinationUnitImpl*>; CUIDMap& g_cu_map() { static CUIDMap* instance = new CUIDMap(); return *instance; } } // namespace CoordinationUnitImpl::CoordinationUnitImpl( const CoordinationUnitID& id, std::unique_ptr<service_manager::ServiceContextRef> service_ref) : id_(id.type, id.id) { auto it = g_cu_map().insert(std::make_pair(id_, this)); DCHECK(it.second); // Inserted successfully service_ref_ = std::move(service_ref); } CoordinationUnitImpl::~CoordinationUnitImpl() { g_cu_map().erase(id_); for (CoordinationUnitImpl* child : children_) { child->RemoveParent(this); } for (CoordinationUnitImpl* parent : parents_) { parent->RemoveChild(this); } } bool CoordinationUnitImpl::SelfOrParentHasFlagSet(StateFlags state) { const base::Optional<bool>& state_flag = state_flags_[state]; if (state_flag && *state_flag) { return true; } for (CoordinationUnitImpl* parent : parents_) { if (parent->SelfOrParentHasFlagSet(state)) { return true; } } return false; } void CoordinationUnitImpl::RecalcCoordinationPolicy() { for (CoordinationUnitImpl* child : children_) { child->RecalcCoordinationPolicy(); } if (!policy_callback_) { return; } bool background_priority = !SelfOrParentHasFlagSet(kTabVisible) && !SelfOrParentHasFlagSet(kAudioPlaying); // Send the priority to the client if it's new or changed. if (!current_policy_) { current_policy_ = mojom::CoordinationPolicy::New(); } else if ((current_policy_->use_background_priority == background_priority) && !SelfOrParentHasFlagSet(StateFlags::kTestState)) { return; } // current_policy_ should be kept in sync with the policy we // send to the client, to avoid redundant updates. // TODO(oysteine): Once this object becomes more complex, make // copying more robust. mojom::CoordinationPolicyPtr policy = mojom::CoordinationPolicy::New(); policy->use_background_priority = background_priority; current_policy_->use_background_priority = background_priority; policy_callback_->SetCoordinationPolicy(std::move(policy)); } void CoordinationUnitImpl::SendEvent(mojom::EventPtr event) { switch (event->type) { case mojom::EventType::kOnWebContentsShown: state_flags_[kTabVisible] = true; break; case mojom::EventType::kOnWebContentsHidden: state_flags_[kTabVisible] = false; break; case mojom::EventType::kOnProcessAudioStarted: state_flags_[kAudioPlaying] = true; break; case mojom::EventType::kOnProcessAudioStopped: state_flags_[kAudioPlaying] = false; break; case mojom::EventType::kOnLocalFrameNetworkIdle: state_flags_[kNetworkIdle] = true; break; case mojom::EventType::kTestEvent: state_flags_[kTestState] = true; break; default: return; } RecalcCoordinationPolicy(); } void CoordinationUnitImpl::GetID(const GetIDCallback& callback) { callback.Run(id_); } void CoordinationUnitImpl::AddBinding(mojom::CoordinationUnitRequest request) { bindings_.AddBinding(this, std::move(request)); } void CoordinationUnitImpl::AddChild(const CoordinationUnitID& child_id) { if (child_id == id_) { return; } auto child_iter = g_cu_map().find(child_id); if (child_iter != g_cu_map().end()) { CoordinationUnitImpl* child = child_iter->second; if (HasParent(child) || HasChild(child)) { return; } DCHECK(child->id_ == child_id); DCHECK(child != this); if (AddChild(child)) { child->AddParent(this); } } } bool CoordinationUnitImpl::AddChild(CoordinationUnitImpl* child) { // We don't recalculate the policy here as policies are only dependent // on the current CU or its parents, not its children. In other words, // policies only bubble down. bool success = children_.count(child) ? false : children_.insert(child).second; if (success) { NOTIFY_OBSERVERS(observers_, OnChildAdded, this, child); } return success; } void CoordinationUnitImpl::RemoveChild(const CoordinationUnitID& child_id) { auto child_iter = g_cu_map().find(child_id); if (child_iter == g_cu_map().end()) { return; } CoordinationUnitImpl* child = child_iter->second; if (!HasChild(child)) { return; } DCHECK(child->id_ == child_id); DCHECK(child != this); if (RemoveChild(child)) { child->RemoveParent(this); } } bool CoordinationUnitImpl::RemoveChild(CoordinationUnitImpl* child) { size_t children_removed = children_.erase(child); bool success = children_removed > 0; if (success) { NOTIFY_OBSERVERS(observers_, OnChildRemoved, this, child); } return success; } void CoordinationUnitImpl::AddParent(CoordinationUnitImpl* parent) { DCHECK_EQ(0u, parents_.count(parent)); parents_.insert(parent); NOTIFY_OBSERVERS(observers_, OnParentAdded, this, parent); RecalcCoordinationPolicy(); } void CoordinationUnitImpl::RemoveParent(CoordinationUnitImpl* parent) { size_t parents_removed = parents_.erase(parent); DCHECK_EQ(1u, parents_removed); // TODO(matthalp, oysteine) should this go before or // after RecalcCoordinationPolicy? NOTIFY_OBSERVERS(observers_, OnParentRemoved, this, parent); RecalcCoordinationPolicy(); } bool CoordinationUnitImpl::HasParent(CoordinationUnitImpl* unit) { for (CoordinationUnitImpl* parent : parents_) { if (parent == unit || parent->HasParent(unit)) { return true; } } return false; } bool CoordinationUnitImpl::HasChild(CoordinationUnitImpl* unit) { for (CoordinationUnitImpl* child : children_) { if (child == unit || child->HasChild(unit)) { return true; } } return false; } void CoordinationUnitImpl::SetCoordinationPolicyCallback( mojom::CoordinationPolicyCallbackPtr callback) { callback.set_connection_error_handler( base::Bind(&CoordinationUnitImpl::UnregisterCoordinationPolicyCallback, base::Unretained(this))); policy_callback_ = std::move(callback); RecalcCoordinationPolicy(); } void CoordinationUnitImpl::UnregisterCoordinationPolicyCallback() { policy_callback_.reset(); current_policy_.reset(); } std::set<CoordinationUnitImpl*> CoordinationUnitImpl::GetChildCoordinationUnitsOfType( CoordinationUnitType type) { std::set<CoordinationUnitImpl*> coordination_units; for (auto* child : children()) { if (child->id().type == type) { coordination_units.insert(child); } for (auto* coordination_unit : child->GetChildCoordinationUnitsOfType(type)) { coordination_units.insert(coordination_unit); } } return coordination_units; } std::set<CoordinationUnitImpl*> CoordinationUnitImpl::GetParentCoordinationUnitsOfType( CoordinationUnitType type) { std::set<CoordinationUnitImpl*> coordination_units; for (auto* parent : parents()) { if (parent->id().type == type) { coordination_units.insert(parent); } for (auto* coordination_unit : parent->GetParentCoordinationUnitsOfType(type)) { coordination_units.insert(coordination_unit); } } return coordination_units; } std::set<CoordinationUnitImpl*> CoordinationUnitImpl::GetAssociatedCoordinationUnitsOfType( CoordinationUnitType type) { NOTREACHED(); return std::set<CoordinationUnitImpl*>(); } base::Value CoordinationUnitImpl::GetProperty( const mojom::PropertyType property_type) const { auto value_it = properties_.find(property_type); return value_it != properties_.end() ? base::Value(*value_it->second) : base::Value(); } void CoordinationUnitImpl::SetProperty(mojom::PropertyType property_type, std::unique_ptr<base::Value> value) { // The |CoordinationUnitGraphObserver| API specification dictates that // the property is guarranteed to be set on the |CoordinationUnitImpl| // and propagated to the appropriate associated |CoordianationUnitImpl| // before |OnPropertyChanged| is invoked on all of the registered observers. const base::Value& property = *(properties_[property_type] = std::move(value)); PropagateProperty(property_type, property); NOTIFY_OBSERVERS(observers_, OnPropertyChanged, this, property_type, property); } void CoordinationUnitImpl::BeforeDestroyed() { NOTIFY_OBSERVERS(observers_, OnBeforeCoordinationUnitDestroyed, this); } void CoordinationUnitImpl::AddObserver( CoordinationUnitGraphObserver* observer) { observers_.AddObserver(observer); } void CoordinationUnitImpl::RemoveObserver( CoordinationUnitGraphObserver* observer) { observers_.RemoveObserver(observer); } } // namespace resource_coordinator
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f19598695649e48db0ea22e8f9a302dc43fde50b
8988c79ef789c3cd77245c8c05c09f6626c19140
/sight_height.h
f50e1db2a7556352bda9ff0089557d42479aa3a0
[]
no_license
kgo87/geo_surveying_cpp
faf8c7d217a5f875323314d9800abb196f047a6a
5f37562ecf76243f3cb8b822e2b79ff37aaa21b6
refs/heads/master
2021-08-18T22:06:14.310419
2017-11-24T03:04:22
2017-11-24T03:04:22
111,868,677
0
0
null
2017-11-24T02:43:54
2017-11-24T02:43:54
null
UTF-8
C++
false
false
556
h
#ifndef GEO_SURVEYING_SIGHT_HEIGHT_H #define GEO_SURVEYING_SIGHT_HEIGHT_H #include <string> struct SightHeight { double upper; double middle; double lower; explicit SightHeight(double upper = 0.0, double middle = 0.0, double lower = 0.0) : upper(upper), middle(middle), lower(lower) {} std::string to_string(); }; #endif //GEO_SURVEYING_SIGHT_HEIGHT_H
[ "eduard.dudar@teamaol.com" ]
eduard.dudar@teamaol.com
97646f2e025d09636215205fad18aaf95d03ccea
46ce9e33c14b2b36194dabc7af362b96113cdbf3
/programers/level3/Best_set.cpp
8b38a579c64a31e4498688f564ca3be4f9c85f81
[]
no_license
dnfwlq8054/coding_test
23e536d00b925a5c157c99afc4359e56dc321ce8
50400908137b50496e35263c0b2c99b8e6a28a3c
refs/heads/master
2023-08-28T06:15:46.289764
2021-10-10T10:36:20
2021-10-10T10:36:20
292,021,321
0
0
null
null
null
null
UTF-8
C++
false
false
507
cpp
#include <string> #include <vector> using namespace std; vector<int> solution(int n, int s) { vector<int> answer; if(n > s){ answer.emplace_back(-1); return answer; } int quo = s / n; int rem = s % n; int num = 0; if(s % n != 0) num = 1; //나누어 떨어지지 않는다면 나머지를 1씩 분배 for(int i = 0; i < n; i++) if(i >= n - rem) answer.emplace_back(quo + 1); else answer.emplace_back(quo); return answer; }
[ "dnfwlq8054@naver.com" ]
dnfwlq8054@naver.com
668326aac6f851498165c8b8b0bcf03eb9f82f4e
575f989fd61298fea3fddc92bd977f9f73d16c4e
/UwpByCpp/App.xaml.h
a06f1756d6490ece25c2dbefb9ac3941df936db6
[ "MIT" ]
permissive
soumunote/Samples
d824ed9bf616dad83b48c13914bd83e70fb29741
562edf0ef41f2dbc61e9c315e4129616402569ae
refs/heads/master
2023-08-17T03:21:55.583985
2023-08-16T02:04:34
2023-08-16T02:04:34
229,272,741
0
1
MIT
2023-03-05T23:27:21
2019-12-20T13:46:49
HTML
UTF-8
C++
false
false
650
h
// // App.xaml.h // Declaration of the App class. // #pragma once #include "App.g.h" namespace UwpByCpp { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> ref class App sealed { protected: virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override; internal: App(); private: void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e); void OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e); }; }
[ "soumunote@gmail.com" ]
soumunote@gmail.com
c9d6e8f5648b24c24ae6f90efc0c294a92462391
230fb8845f39bef0f30f5d3541eff5dc0641de14
/Connect3/Export/windows/obj/src/lime/net/_HTTPRequest/AbstractHTTPRequest.cpp
8098336c9e1e331fdf20355bf07c9e1b6ebb42bc
[]
no_license
vhlk/AlgoritmoMinMax
76abd62a6e2859ed229e5831264b6d8af27e318d
40eded4948794ca48d50d16d2133a9ab21207768
refs/heads/main
2023-06-30T15:16:17.492478
2021-08-02T13:29:32
2021-08-02T13:29:32
390,493,745
1
0
null
null
null
null
UTF-8
C++
false
true
14,190
cpp
// Generated by Haxe 4.2.0 #include <hxcpp.h> #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_lime__internal_backend_native_NativeHTTPRequest #include <lime/_internal/backend/native/NativeHTTPRequest.h> #endif #ifndef INCLUDED_lime_app_Future #include <lime/app/Future.h> #endif #ifndef INCLUDED_lime_net_HTTPRequestHeader #include <lime/net/HTTPRequestHeader.h> #endif #ifndef INCLUDED_lime_net__HTTPRequest_AbstractHTTPRequest #include <lime/net/_HTTPRequest/AbstractHTTPRequest.h> #endif #ifndef INCLUDED_lime_net__IHTTPRequest #include <lime/net/_IHTTPRequest.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_bc0cf2bf735ddd18_49_new,"lime.net._HTTPRequest.AbstractHTTPRequest","new",0x2f7ffcbb,"lime.net._HTTPRequest.AbstractHTTPRequest.new","lime/net/HTTPRequest.hx",49,0x339db723) HX_LOCAL_STACK_FRAME(_hx_pos_bc0cf2bf735ddd18_70_cancel,"lime.net._HTTPRequest.AbstractHTTPRequest","cancel",0x9e11abff,"lime.net._HTTPRequest.AbstractHTTPRequest.cancel","lime/net/HTTPRequest.hx",70,0x339db723) HX_LOCAL_STACK_FRAME(_hx_pos_bc0cf2bf735ddd18_76_load,"lime.net._HTTPRequest.AbstractHTTPRequest","load",0x5f323d6b,"lime.net._HTTPRequest.AbstractHTTPRequest.load","lime/net/HTTPRequest.hx",76,0x339db723) namespace lime{ namespace net{ namespace _HTTPRequest{ void AbstractHTTPRequest_obj::__construct(::String uri){ HX_GC_STACKFRAME(&_hx_pos_bc0cf2bf735ddd18_49_new) HXLINE( 50) this->uri = uri; HXLINE( 52) this->contentType = HX_("application/x-www-form-urlencoded",9e,61,91,fa); HXLINE( 53) this->followRedirects = true; HXLINE( 54) this->enableResponseHeaders = false; HXLINE( 55) this->formData = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 56) this->headers = ::Array_obj< ::Dynamic>::__new(0); HXLINE( 57) this->method = HX_("GET",76,1c,36,00); HXLINE( 58) this->timeout = 30000; HXLINE( 59) this->withCredentials = false; HXLINE( 62) this->_hx___backend = ::lime::_internal::backend::native::NativeHTTPRequest_obj::__alloc( HX_CTX ); HXLINE( 63) this->_hx___backend->init(::hx::ObjectPtr<OBJ_>(this)); } Dynamic AbstractHTTPRequest_obj::__CreateEmpty() { return new AbstractHTTPRequest_obj; } void *AbstractHTTPRequest_obj::_hx_vtable = 0; Dynamic AbstractHTTPRequest_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< AbstractHTTPRequest_obj > _hx_result = new AbstractHTTPRequest_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } bool AbstractHTTPRequest_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x09b24b15; } static ::lime::net::_IHTTPRequest_obj _hx_lime_net__HTTPRequest_AbstractHTTPRequest__hx_lime_net__IHTTPRequest= { ( void (::hx::Object::*)())&::lime::net::_HTTPRequest::AbstractHTTPRequest_obj::cancel, }; void *AbstractHTTPRequest_obj::_hx_getInterface(int inHash) { switch(inHash) { case (int)0x154a91b5: return &_hx_lime_net__HTTPRequest_AbstractHTTPRequest__hx_lime_net__IHTTPRequest; } #ifdef HXCPP_SCRIPTABLE return super::_hx_getInterface(inHash); #else return 0; #endif } void AbstractHTTPRequest_obj::cancel(){ HX_STACKFRAME(&_hx_pos_bc0cf2bf735ddd18_70_cancel) HXDLIN( 70) this->_hx___backend->cancel(); } HX_DEFINE_DYNAMIC_FUNC0(AbstractHTTPRequest_obj,cancel,(void)) ::lime::app::Future AbstractHTTPRequest_obj::load(::String uri){ HX_STACKFRAME(&_hx_pos_bc0cf2bf735ddd18_76_load) HXDLIN( 76) return null(); } HX_DEFINE_DYNAMIC_FUNC1(AbstractHTTPRequest_obj,load,return ) ::hx::ObjectPtr< AbstractHTTPRequest_obj > AbstractHTTPRequest_obj::__new(::String uri) { ::hx::ObjectPtr< AbstractHTTPRequest_obj > __this = new AbstractHTTPRequest_obj(); __this->__construct(uri); return __this; } ::hx::ObjectPtr< AbstractHTTPRequest_obj > AbstractHTTPRequest_obj::__alloc(::hx::Ctx *_hx_ctx,::String uri) { AbstractHTTPRequest_obj *__this = (AbstractHTTPRequest_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(AbstractHTTPRequest_obj), true, "lime.net._HTTPRequest.AbstractHTTPRequest")); *(void **)__this = AbstractHTTPRequest_obj::_hx_vtable; __this->__construct(uri); return __this; } AbstractHTTPRequest_obj::AbstractHTTPRequest_obj() { } void AbstractHTTPRequest_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(AbstractHTTPRequest); HX_MARK_MEMBER_NAME(contentType,"contentType"); HX_MARK_MEMBER_NAME(data,"data"); HX_MARK_MEMBER_NAME(enableResponseHeaders,"enableResponseHeaders"); HX_MARK_MEMBER_NAME(followRedirects,"followRedirects"); HX_MARK_MEMBER_NAME(formData,"formData"); HX_MARK_MEMBER_NAME(headers,"headers"); HX_MARK_MEMBER_NAME(method,"method"); HX_MARK_MEMBER_NAME(responseData,"responseData"); HX_MARK_MEMBER_NAME(responseHeaders,"responseHeaders"); HX_MARK_MEMBER_NAME(responseStatus,"responseStatus"); HX_MARK_MEMBER_NAME(timeout,"timeout"); HX_MARK_MEMBER_NAME(uri,"uri"); HX_MARK_MEMBER_NAME(userAgent,"userAgent"); HX_MARK_MEMBER_NAME(withCredentials,"withCredentials"); HX_MARK_MEMBER_NAME(_hx___backend,"__backend"); HX_MARK_END_CLASS(); } void AbstractHTTPRequest_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(contentType,"contentType"); HX_VISIT_MEMBER_NAME(data,"data"); HX_VISIT_MEMBER_NAME(enableResponseHeaders,"enableResponseHeaders"); HX_VISIT_MEMBER_NAME(followRedirects,"followRedirects"); HX_VISIT_MEMBER_NAME(formData,"formData"); HX_VISIT_MEMBER_NAME(headers,"headers"); HX_VISIT_MEMBER_NAME(method,"method"); HX_VISIT_MEMBER_NAME(responseData,"responseData"); HX_VISIT_MEMBER_NAME(responseHeaders,"responseHeaders"); HX_VISIT_MEMBER_NAME(responseStatus,"responseStatus"); HX_VISIT_MEMBER_NAME(timeout,"timeout"); HX_VISIT_MEMBER_NAME(uri,"uri"); HX_VISIT_MEMBER_NAME(userAgent,"userAgent"); HX_VISIT_MEMBER_NAME(withCredentials,"withCredentials"); HX_VISIT_MEMBER_NAME(_hx___backend,"__backend"); } ::hx::Val AbstractHTTPRequest_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"uri") ) { return ::hx::Val( uri ); } break; case 4: if (HX_FIELD_EQ(inName,"data") ) { return ::hx::Val( data ); } if (HX_FIELD_EQ(inName,"load") ) { return ::hx::Val( load_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"method") ) { return ::hx::Val( method ); } if (HX_FIELD_EQ(inName,"cancel") ) { return ::hx::Val( cancel_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"headers") ) { return ::hx::Val( headers ); } if (HX_FIELD_EQ(inName,"timeout") ) { return ::hx::Val( timeout ); } break; case 8: if (HX_FIELD_EQ(inName,"formData") ) { return ::hx::Val( formData ); } break; case 9: if (HX_FIELD_EQ(inName,"userAgent") ) { return ::hx::Val( userAgent ); } if (HX_FIELD_EQ(inName,"__backend") ) { return ::hx::Val( _hx___backend ); } break; case 11: if (HX_FIELD_EQ(inName,"contentType") ) { return ::hx::Val( contentType ); } break; case 12: if (HX_FIELD_EQ(inName,"responseData") ) { return ::hx::Val( responseData ); } break; case 14: if (HX_FIELD_EQ(inName,"responseStatus") ) { return ::hx::Val( responseStatus ); } break; case 15: if (HX_FIELD_EQ(inName,"followRedirects") ) { return ::hx::Val( followRedirects ); } if (HX_FIELD_EQ(inName,"responseHeaders") ) { return ::hx::Val( responseHeaders ); } if (HX_FIELD_EQ(inName,"withCredentials") ) { return ::hx::Val( withCredentials ); } break; case 21: if (HX_FIELD_EQ(inName,"enableResponseHeaders") ) { return ::hx::Val( enableResponseHeaders ); } } return super::__Field(inName,inCallProp); } ::hx::Val AbstractHTTPRequest_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"uri") ) { uri=inValue.Cast< ::String >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"data") ) { data=inValue.Cast< ::haxe::io::Bytes >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"method") ) { method=inValue.Cast< ::String >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"headers") ) { headers=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; } if (HX_FIELD_EQ(inName,"timeout") ) { timeout=inValue.Cast< int >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"formData") ) { formData=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"userAgent") ) { userAgent=inValue.Cast< ::String >(); return inValue; } if (HX_FIELD_EQ(inName,"__backend") ) { _hx___backend=inValue.Cast< ::lime::_internal::backend::native::NativeHTTPRequest >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"contentType") ) { contentType=inValue.Cast< ::String >(); return inValue; } break; case 12: if (HX_FIELD_EQ(inName,"responseData") ) { responseData=inValue.Cast< ::Dynamic >(); return inValue; } break; case 14: if (HX_FIELD_EQ(inName,"responseStatus") ) { responseStatus=inValue.Cast< int >(); return inValue; } break; case 15: if (HX_FIELD_EQ(inName,"followRedirects") ) { followRedirects=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"responseHeaders") ) { responseHeaders=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; } if (HX_FIELD_EQ(inName,"withCredentials") ) { withCredentials=inValue.Cast< bool >(); return inValue; } break; case 21: if (HX_FIELD_EQ(inName,"enableResponseHeaders") ) { enableResponseHeaders=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void AbstractHTTPRequest_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("contentType",93,3c,7b,2a)); outFields->push(HX_("data",2a,56,63,42)); outFields->push(HX_("enableResponseHeaders",82,32,47,05)); outFields->push(HX_("followRedirects",26,5a,40,75)); outFields->push(HX_("formData",8e,d5,80,56)); outFields->push(HX_("headers",46,52,08,63)); outFields->push(HX_("method",e1,f6,5a,09)); outFields->push(HX_("responseData",4b,05,e9,c4)); outFields->push(HX_("responseHeaders",c5,0d,ca,43)); outFields->push(HX_("responseStatus",93,60,a4,78)); outFields->push(HX_("timeout",a1,1a,f7,d8)); outFields->push(HX_("uri",6c,2b,59,00)); outFields->push(HX_("userAgent",7a,f0,12,c8)); outFields->push(HX_("withCredentials",56,86,c4,ca)); outFields->push(HX_("__backend",f4,0c,d6,7c)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo AbstractHTTPRequest_obj_sMemberStorageInfo[] = { {::hx::fsString,(int)offsetof(AbstractHTTPRequest_obj,contentType),HX_("contentType",93,3c,7b,2a)}, {::hx::fsObject /* ::haxe::io::Bytes */ ,(int)offsetof(AbstractHTTPRequest_obj,data),HX_("data",2a,56,63,42)}, {::hx::fsBool,(int)offsetof(AbstractHTTPRequest_obj,enableResponseHeaders),HX_("enableResponseHeaders",82,32,47,05)}, {::hx::fsBool,(int)offsetof(AbstractHTTPRequest_obj,followRedirects),HX_("followRedirects",26,5a,40,75)}, {::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(AbstractHTTPRequest_obj,formData),HX_("formData",8e,d5,80,56)}, {::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(AbstractHTTPRequest_obj,headers),HX_("headers",46,52,08,63)}, {::hx::fsString,(int)offsetof(AbstractHTTPRequest_obj,method),HX_("method",e1,f6,5a,09)}, {::hx::fsObject /* ::Dynamic */ ,(int)offsetof(AbstractHTTPRequest_obj,responseData),HX_("responseData",4b,05,e9,c4)}, {::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(AbstractHTTPRequest_obj,responseHeaders),HX_("responseHeaders",c5,0d,ca,43)}, {::hx::fsInt,(int)offsetof(AbstractHTTPRequest_obj,responseStatus),HX_("responseStatus",93,60,a4,78)}, {::hx::fsInt,(int)offsetof(AbstractHTTPRequest_obj,timeout),HX_("timeout",a1,1a,f7,d8)}, {::hx::fsString,(int)offsetof(AbstractHTTPRequest_obj,uri),HX_("uri",6c,2b,59,00)}, {::hx::fsString,(int)offsetof(AbstractHTTPRequest_obj,userAgent),HX_("userAgent",7a,f0,12,c8)}, {::hx::fsBool,(int)offsetof(AbstractHTTPRequest_obj,withCredentials),HX_("withCredentials",56,86,c4,ca)}, {::hx::fsObject /* ::lime::_internal::backend::native::NativeHTTPRequest */ ,(int)offsetof(AbstractHTTPRequest_obj,_hx___backend),HX_("__backend",f4,0c,d6,7c)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *AbstractHTTPRequest_obj_sStaticStorageInfo = 0; #endif static ::String AbstractHTTPRequest_obj_sMemberFields[] = { HX_("contentType",93,3c,7b,2a), HX_("data",2a,56,63,42), HX_("enableResponseHeaders",82,32,47,05), HX_("followRedirects",26,5a,40,75), HX_("formData",8e,d5,80,56), HX_("headers",46,52,08,63), HX_("method",e1,f6,5a,09), HX_("responseData",4b,05,e9,c4), HX_("responseHeaders",c5,0d,ca,43), HX_("responseStatus",93,60,a4,78), HX_("timeout",a1,1a,f7,d8), HX_("uri",6c,2b,59,00), HX_("userAgent",7a,f0,12,c8), HX_("withCredentials",56,86,c4,ca), HX_("__backend",f4,0c,d6,7c), HX_("cancel",7a,ed,33,b8), HX_("load",26,9a,b7,47), ::String(null()) }; ::hx::Class AbstractHTTPRequest_obj::__mClass; void AbstractHTTPRequest_obj::__register() { AbstractHTTPRequest_obj _hx_dummy; AbstractHTTPRequest_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("lime.net._HTTPRequest.AbstractHTTPRequest",49,83,86,4f); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(AbstractHTTPRequest_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< AbstractHTTPRequest_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = AbstractHTTPRequest_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = AbstractHTTPRequest_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace lime } // end namespace net } // end namespace _HTTPRequest
[ "vhlk@cin.ufpe.br" ]
vhlk@cin.ufpe.br
8c48b151d0a27c1889e47cab7518ba407b2d708c
84b541782632e0db73416c4185c885768683f910
/source/neuropod/bindings/java/src/main/native/com_uber_neuropod_NeuropodTensor.cc
906fcff16444efb14284aea9de3b656b39b60064
[ "Apache-2.0" ]
permissive
DinLei/neuropod
c512e24fe9d60fdfeffc6eb6df8d1fc61579ce77
6c3d499706565c6b06be7f4bdebd8ae11ff6f8dc
refs/heads/master
2022-12-01T12:44:42.333747
2020-08-13T16:47:43
2020-08-13T16:47:43
288,081,511
1
0
Apache-2.0
2020-08-17T04:15:28
2020-08-17T04:15:27
null
UTF-8
C++
false
false
2,504
cc
#include "com_uber_neuropod_NeuropodTensor.h" #include "jclass_register.h" #include "neuropod/neuropod.hh" #include "utils.h" #include <exception> #include <memory> #include <jni.h> using namespace neuropod::jni; JNIEXPORT void JNICALL Java_com_uber_neuropod_NeuropodTensor_nativeDoDelete(JNIEnv *env, jobject, jlong handle) { try { // Java NeuropodTensor stores a pointer to a shared_ptr auto tensorPtr = reinterpret_cast<std::shared_ptr<neuropod::NeuropodValue> *>(handle); std::unique_ptr<std::shared_ptr<neuropod::NeuropodValue>> scopeHolder(tensorPtr); tensorPtr->reset(); } catch (const std::exception &e) { throwJavaException(env, e.what()); } } JNIEXPORT jlongArray JNICALL Java_com_uber_neuropod_NeuropodTensor_nativeGetDims(JNIEnv *env, jclass, jlong handle) { try { auto tensor = (*reinterpret_cast<std::shared_ptr<neuropod::NeuropodValue> *>(handle))->as_tensor(); auto dims = tensor->as_tensor()->get_dims(); jlongArray result = env->NewLongArray(dims.size()); if (!result) { throw std::runtime_error("out of memory"); } env->SetLongArrayRegion(result, 0, dims.size(), reinterpret_cast<jlong *>(dims.data())); return result; } catch (const std::exception &e) { throwJavaException(env, e.what()); } return nullptr; } JNIEXPORT jobject JNICALL Java_com_uber_neuropod_NeuropodTensor_nativeGetTensorType(JNIEnv *env, jclass, jlong handle) { try { auto tensor = (*reinterpret_cast<std::shared_ptr<neuropod::NeuropodValue> *>(handle))->as_tensor(); auto type = tensor->as_tensor()->get_tensor_type(); return getTensorTypeField(env, tensorTypeToString(type).c_str()); } catch (const std::exception &e) { throwJavaException(env, e.what()); } return nullptr; } JNIEXPORT jlong JNICALL Java_com_uber_neuropod_NeuropodTensor_nativeGetNumberOfElements(JNIEnv *env, jclass, jlong handle) { try { auto tensor = (*reinterpret_cast<std::shared_ptr<neuropod::NeuropodValue> *>(handle))->as_tensor(); return tensor->get_num_elements(); } catch (const std::exception &e) { throwJavaException(env, e.what()); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
8192527b13f6ac1999540bb0908fa38b20baab4b
fd0205f587d05506396ce762849f28e92c2c1fea
/src/src/Impulse/Dataset/DatasetModifier/Modifier/MinMaxScaling.cpp
4aeff88bfcb06f2dfc2f51ca3ae6137d2467ab15
[]
no_license
houdini22/impulse-dataset
bdf4d0f2e4d6fedd30b7c1616dc441a4bd5c97dc
63eddf9ce15c01b77ab6138323e61ddbff9dead9
refs/heads/master
2021-08-24T00:09:08.472771
2017-12-07T06:34:28
2017-12-07T06:34:28
111,939,098
0
0
null
null
null
null
UTF-8
C++
false
false
1,039
cpp
#include "../../include.h" namespace Impulse { namespace Dataset { namespace DatasetModifier { namespace Modifier { void MinMaxScaling::applyToColumn(int columnIndex) { DatasetData samples = this->dataset.getSamples(); double min = std::numeric_limits<double>::max(); double max = std::numeric_limits<double>::min(); T_Size i; for (auto &sample : samples) { double value = sample->getColumnToDouble(columnIndex); min = MIN(value, min); max = MAX(value, max); } for (auto &sample : samples) { double value = sample->getColumnToDouble(columnIndex); double newValue = (value - min) / (max - min); sample->setColumn(columnIndex, newValue); } } } } } }
[ "baniczek@gmail.com" ]
baniczek@gmail.com
0b22cc6dc15b146793ac74b5675c7a6c29fc321b
8f29bbdbc1b29365eca840b72d61f63abe8f829f
/Semester2/3001/M3/SDLGameEngine/Scene0.h
14717f207322dbb05cf5526690ac37a2ceb87586
[]
no_license
CccrizzZ/GBC01
d294f01aab97de37f2b70bcf325ae713e4eed740
c44130872f609e5778992d8a6dad09caed29ff71
refs/heads/master
2022-02-22T11:32:54.720661
2019-10-14T00:07:50
2019-10-14T00:07:50
158,318,882
0
0
null
null
null
null
UTF-8
C++
false
false
227
h
#pragma once #include "Scene.h" class Scene0 : public Scene{ public: Scene0(); ~Scene0(); // Global instance static Scene0* Instance() { static Scene0* instance = new Scene0(); return instance; } void Setup(); };
[ "ccccrizzzz@gmail.com" ]
ccccrizzzz@gmail.com
6d894f8829a66bf1cdacab9295c5cfbaabfa10b7
9473d98a9c4bcba737ba8a1eaa3a9a852c73c0c4
/imeplusplus/2018-tryouts/h.cpp
b9702d4603da941db35e8399f9efbfa5bcd0a852
[]
no_license
joaopedroxavier/Competitive-Programming
e57528e99ddfbc88be67870974a42c5348fcc90c
fb73e2e23d1f904a35898fcdfa977d72a9ff4e8b
refs/heads/master
2018-10-29T04:22:39.267104
2018-09-14T18:25:49
2018-09-14T18:25:49
82,396,740
0
0
null
null
null
null
UTF-8
C++
false
false
775
cpp
// // 내가 나인 게 싫은 날 // 영영 사라지고 싶은 날 // 문을 하나 만들자 너의 맘 속에다 // 그 문을 열고 들어가면 // 이 곳이 기다릴 거야 // 믿어도 괜찮아 널 위로해줄 magic shop // #include <bits/stdc++.h> using namespace std; #define mp make_pair #define pb push_back #define st first #define nd second typedef long long ll; typedef long double ld; typedef pair<int,int> ii; const ld EPS = 1e-9; const ld PI = acos(-1); const int N = 1e5+5; const int MOD = 1e9+7; const int INF = 0x3f3f3f3f; ll n, a; ld p; int main(){ //freopen("in", "r", stdin); //freopen("out", "w", stdout); scanf("%lld %lld %Lf", &n, &a, &p); p /= 100.0; ld ans = n + a*p - a*(1-p); printf("%.12Lf\n", ans); return 0; }
[ "joaopedroaxavier@gmail.com" ]
joaopedroaxavier@gmail.com
6857be3725d1fea5acc0c35d9a8d52146e156ac8
4d5b0e2eca9a4700399262e917f18c2961bd1044
/Source/Private/Mouse.cpp
34d7e8fcb3255fc3ad70a47d9d03f85c38d09580
[]
no_license
AaronStone24/LearnDirectX11
42ad44fbe2ace42bd3a5f495761eed777cfcbd11
2a7fb3c330bfae80cd4a707d8a38e962ec3ae0b6
refs/heads/master
2023-06-25T05:43:03.183208
2021-07-29T17:19:28
2021-07-29T17:19:28
328,481,240
0
0
null
null
null
null
UTF-8
C++
false
false
2,444
cpp
#include "../Public//Mouse.h" #include "windows.h" std::pair<int, int> Mouse::GetPos() const noexcept { return std::make_pair(x, y); } int Mouse::GetPosX() const noexcept { return x; } int Mouse::GetPosY() const noexcept { return y; } bool Mouse::IsLeftPressed() const noexcept { return isLeftPressed; } bool Mouse::IsRightPressed() const noexcept { return isRightPressed; } bool Mouse::IsInWindow() const noexcept { return isInWindow; } Mouse::Event Mouse::Read() noexcept { if (buffer.size() > 0u) { Mouse::Event e = buffer.front(); buffer.pop(); return e; } else { return Mouse::Event(); } } void Mouse::Flush() noexcept { buffer = std::queue<Event>(); } void Mouse::OnMouseMove(int newx, int newy) noexcept { x = newx; y = newy; buffer.push(Mouse::Event(Mouse::Event::Type::Move, *this)); TrimBuffer(); } void Mouse::OnLeftPressed(int newx, int newy) noexcept { isLeftPressed = true; buffer.push(Mouse::Event(Mouse::Event::Type::LPress, *this)); TrimBuffer(); } void Mouse::OnLeftReleased(int newx, int newy) noexcept { isLeftPressed = false; buffer.push(Mouse::Event(Mouse::Event::Type::LRelease, *this)); TrimBuffer(); } void Mouse::OnRightPressed(int newx, int newy) noexcept { isRightPressed = true; buffer.push(Mouse::Event(Mouse::Event::Type::RPress, *this)); TrimBuffer(); } void Mouse::OnRightReleased(int newx, int newy) noexcept { isRightPressed = false; buffer.push(Mouse::Event(Mouse::Event::Type::RRelease, *this)); TrimBuffer(); } void Mouse::OnMouseLeave() noexcept { isInWindow = false; buffer.push(Mouse::Event(Mouse::Event::Type::Leave, *this)); TrimBuffer(); } void Mouse::OnMouseEnter() noexcept { isInWindow = true; buffer.push(Mouse::Event(Mouse::Event::Type::Enter, *this)); TrimBuffer(); } void Mouse::OnWheelUp(int newx, int newy) noexcept { buffer.push(Mouse::Event(Mouse::Event::Type::WheelUp, *this)); TrimBuffer(); } void Mouse::OnWheelDown(int newx, int newy) noexcept { buffer.push(Mouse::Event(Mouse::Event::Type::WheelDown, *this)); TrimBuffer(); } void Mouse::TrimBuffer() noexcept { while (buffer.size() > bufferSize) { buffer.pop(); } } void Mouse::OnWheelDelta(int x, int y, int delta) noexcept { wheelDeltaCarry += delta; while (wheelDeltaCarry >= WHEEL_DELTA) { wheelDeltaCarry -= WHEEL_DELTA; OnWheelUp(x, y); } while (wheelDeltaCarry <= -WHEEL_DELTA) { wheelDeltaCarry += WHEEL_DELTA; OnWheelDown(x, y); } }
[ "kartikup7@gmail.com" ]
kartikup7@gmail.com
0c80b3a970c3531f6aa7263b16207157a6c4d079
da2c2b6a4169d0467de7292ef036f496c3ec483a
/src/transforms/hlir/neutral/fuse_unary.cpp
bd7518960d4185668e8483fb947b5f8eadcbc175
[ "Apache-2.0" ]
permissive
mirecta/nncase
c6d9a3f3b168a94731e794d3992501d0ef51df56
d2efa59677a26f4259b3b6a5b6ec05ea16d4e40c
refs/heads/master
2021-04-14T17:21:17.382086
2020-04-05T18:10:01
2020-04-05T18:10:01
249,249,613
0
0
Apache-2.0
2020-03-22T18:44:44
2020-03-22T18:44:43
null
UTF-8
C++
false
false
11,116
cpp
/* Copyright 2019-2020 Canaan Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <hlir/ops/binary.h> #include <hlir/ops/constant.h> #include <hlir/ops/fused_unary.h> #include <hlir/ops/table_lookup.h> #include <hlir/ops/unary.h> #include <hlir/transforms/neutral/fuse_unary.h> #include <hlir/visitor.h> using namespace nncase; using namespace nncase::hlir; using namespace nncase::hlir::transforms; namespace { std::vector<fused_unary_op> merge_subgraph(const std::vector<fused_unary_op> &src1, const std::vector<fused_unary_op> &src2) { std::vector<fused_unary_op> result = src1; auto arg_inc = result.size(); for (auto &op : src2) { auto n_op = op; switch (n_op.opcode) { case fu_ldx: case fu_constant: break; case fu_unary: n_op.unary.input.op_id += arg_inc; break; case fu_binary: n_op.binary.input_a.op_id += arg_inc; n_op.binary.input_b.op_id += arg_inc; break; case fu_clamp: n_op.clamp.input.op_id += arg_inc; n_op.clamp.low.op_id += arg_inc; n_op.clamp.high.op_id += arg_inc; break; default: throw std::runtime_error("Invalid fused unary op"); } result.emplace_back(n_op); } return result; } std::vector<fused_unary_op> concat_subgraph(const std::vector<fused_unary_op> &src1, const std::vector<fused_unary_op> &src2) { std::vector<fused_unary_op> result = src1; // Turn ldx to identity auto src1_out_arg = result.size() - 1; auto arg_inc = result.size(); auto first_ldx = true; for (auto &op : src2) { auto n_op = op; switch (n_op.opcode) { case fu_ldx: if (!first_ldx) { result.emplace_back(fused_unary_op::make_identity({ src1_out_arg })); } else { first_ldx = false; arg_inc--; } continue; case fu_constant: break; case fu_unary: n_op.unary.input.op_id += arg_inc; break; case fu_binary: n_op.binary.input_a.op_id += arg_inc; n_op.binary.input_b.op_id += arg_inc; break; case fu_clamp: n_op.clamp.input.op_id += arg_inc; n_op.clamp.low.op_id += arg_inc; n_op.clamp.high.op_id += arg_inc; break; default: throw std::runtime_error("Invalid fused unary op"); } result.emplace_back(n_op); } return result; } } bool fuse_one_unary_transform::on_try_match(node &node, transform_context &context) { if (auto u = node_cast<unary>(node)) { context.matched_nodes.emplace_back(u); context.inputs.emplace_back(&u->input()); context.outputs.emplace_back(&u->output()); return true; } return false; } void fuse_one_unary_transform::process(transform_context &context) { auto &output = *context.inputs[0]->connection(); auto inputs = context.outputs[0]->connections(); auto &old_u = static_cast<unary &>(*context.matched_nodes[0]); std::vector<fused_unary_op> subgraph; subgraph.emplace_back(fused_unary_op::make_ldx()); subgraph.emplace_back(fused_unary_op::make_unary(old_u.unary_op(), { 0 })); auto f_u = context.graph.emplace<fused_unary>(std::move(subgraph), output.shape()); f_u->input().connect(output); for (auto &in : dup(inputs)) in->connect(f_u->output()); } bool fuse_one_binary_transform::on_try_match(node &node, transform_context &context) { if (auto bin = node_cast<binary>(node)) { constant *con; if ((con = node_cast<constant>(bin->input_b().connection()->owner())) && xt::compute_size(con->output().shape()) == 1) { context.matched_nodes.emplace_back(bin); context.matched_nodes.emplace_back(con); context.inputs.emplace_back(&bin->input_a()); context.outputs.emplace_back(&bin->output()); return true; } else if ((con = node_cast<constant>(bin->input_a().connection()->owner())) && xt::compute_size(con->output().shape()) == 1) { context.matched_nodes.emplace_back(bin); context.matched_nodes.emplace_back(con); context.inputs.emplace_back(&bin->input_b()); context.outputs.emplace_back(&bin->output()); return true; } } return false; } void fuse_one_binary_transform::process(transform_context &context) { auto &output = *context.inputs[0]->connection(); auto inputs = context.outputs[0]->connections(); auto &old_b = static_cast<binary &>(*context.matched_nodes[0]); auto &old_c = static_cast<constant &>(*context.matched_nodes[1]); std::vector<fused_unary_op> subgraph; subgraph.emplace_back(fused_unary_op::make_ldx()); subgraph.emplace_back(fused_unary_op::make_constant(*reinterpret_cast<const float *>(old_c.data().data()))); if (old_b.input_b().connection()->owner().runtime_opcode() == op_constant) subgraph.emplace_back(fused_unary_op::make_binary(old_b.binary_op(), { 0 }, { 1 })); else subgraph.emplace_back(fused_unary_op::make_binary(old_b.binary_op(), { 1 }, { 0 })); auto f_u = context.graph.emplace<fused_unary>(std::move(subgraph), output.shape()); f_u->input().connect(output); for (auto &in : dup(inputs)) in->connect(f_u->output()); } bool fuse_two_fused_unary_transform::on_try_match(node &node, transform_context &context) { if (auto f1 = node_cast<fused_unary>(node)) { if (auto f2 = try_get_direct_child<fused_unary>(*f1)) { context.matched_nodes.emplace_back(f1); context.matched_nodes.emplace_back(f2); context.inputs.emplace_back(&f1->input()); context.outputs.emplace_back(&f2->output()); return true; } } return false; } void fuse_two_fused_unary_transform::process(transform_context &context) { auto &output = *context.inputs[0]->connection(); auto inputs = context.outputs[0]->connections(); auto &old_f1 = static_cast<fused_unary &>(*context.matched_nodes[0]); auto &old_f2 = static_cast<fused_unary &>(*context.matched_nodes[1]); auto subgraph = concat_subgraph(old_f1.subgraph(), old_f2.subgraph()); auto f_u = context.graph.emplace<fused_unary>(std::move(subgraph), old_f1.input().shape()); f_u->input().connect(output); for (auto &in : dup(inputs)) in->connect(f_u->output()); } bool fuse_one_fused_unary_with_binary_transform::on_try_match(node &node, transform_context &context) { if (auto b = node_cast<binary>(node)) { if (auto f = try_get_direct_parent<fused_unary>(*b, 0)) { if (f->input().connection() == b->input_b().connection()) { context.matched_nodes.emplace_back(f); context.matched_nodes.emplace_back(b); context.inputs.emplace_back(&f->input()); context.inputs.emplace_back(&b->input_b()); context.outputs.emplace_back(&b->output()); return true; } } else if (auto f = try_get_direct_parent<fused_unary>(*b, 1)) { if (f->input().connection() == b->input_a().connection()) { context.matched_nodes.emplace_back(f); context.matched_nodes.emplace_back(b); context.inputs.emplace_back(&b->input_a()); context.inputs.emplace_back(&f->input()); context.outputs.emplace_back(&b->output()); return true; } } } return false; } void fuse_one_fused_unary_with_binary_transform::process(transform_context &context) { auto &output = *context.inputs[0]->connection(); auto inputs = context.outputs[0]->connections(); auto &old_f = static_cast<fused_unary &>(*context.matched_nodes[0]); auto &old_b = static_cast<binary &>(*context.matched_nodes[1]); auto subgraph = old_f.subgraph(); auto arg_f_id = subgraph.size() - 1; subgraph.emplace_back(fused_unary_op::make_ldx()); auto arg_x_id = subgraph.size() - 1; if (old_b.input_b().connection()->owner().runtime_opcode() == op_fused_unary) subgraph.emplace_back(fused_unary_op::make_binary(old_b.binary_op(), { arg_x_id }, { arg_f_id })); else subgraph.emplace_back(fused_unary_op::make_binary(old_b.binary_op(), { arg_f_id }, { arg_x_id })); auto f_u = context.graph.emplace<fused_unary>(std::move(subgraph), output.shape()); f_u->input().connect(output); for (auto &in : dup(inputs)) in->connect(f_u->output()); } bool fuse_two_fused_unary_with_binary_transform::on_try_match(node &node, transform_context &context) { if (auto b = node_cast<binary>(node)) { if (auto f1 = try_get_direct_parent<fused_unary>(*b, 0)) { if (auto f2 = try_get_direct_parent<fused_unary>(*b, 1)) { if (f1->input().connection() == f2->input().connection()) { context.matched_nodes.emplace_back(f1); context.matched_nodes.emplace_back(f2); context.matched_nodes.emplace_back(b); context.inputs.emplace_back(&f1->input()); context.outputs.emplace_back(&b->output()); return true; } } } } return false; } void fuse_two_fused_unary_with_binary_transform::process(transform_context &context) { auto &output = *context.inputs[0]->connection(); auto inputs = context.outputs[0]->connections(); auto &old_f1 = static_cast<fused_unary &>(*context.matched_nodes[0]); auto &old_f2 = static_cast<fused_unary &>(*context.matched_nodes[1]); auto &old_b = static_cast<binary &>(*context.matched_nodes[2]); auto subgraph = merge_subgraph(old_f1.subgraph(), old_f2.subgraph()); auto arg_a_id = old_f1.subgraph().size() - 1; auto arg_b_id = subgraph.size() - 1; subgraph.emplace_back(fused_unary_op::make_binary(old_b.binary_op(), { arg_a_id }, { arg_b_id })); auto f_u = context.graph.emplace<fused_unary>(std::move(subgraph), output.shape()); f_u->input().connect(output); for (auto &in : dup(inputs)) in->connect(f_u->output()); }
[ "sunnycase@live.cn" ]
sunnycase@live.cn
512b51be1f375c931caa90eed0272d139d9f1afa
f25bb5639b372d2f13aa8aa07ce47619307da344
/src/pmVectorArray.h
17d3aedd791316ec2fe78d30a0b3bb2aa915eb83
[ "Apache-2.0", "LicenseRef-scancode-other-permissive", "MIT" ]
permissive
snumrl/PmQm
5c315a1e425b359fa84d1266460f9a1f25f96492
c0d493b7cdd1a0d57ed76cb342a222c84c46975f
refs/heads/master
2021-01-10T03:37:24.733445
2019-12-06T06:30:09
2019-12-06T06:30:09
55,753,691
5
3
null
null
null
null
UTF-8
C++
false
false
1,881
h
// +------------------------------------------------------------------------- // | pmVectorArray.h // | // | Author: Jehee Lee // +------------------------------------------------------------------------- // | COPYRIGHT: // | Copyright Jehee Lee 2013 // | See the included COPYRIGHT.txt file for further details. // | // | This file is part of the PmQm library. // | PmQm library is free software: you can redistribute it and/or modify // | it under the terms of the MIT License. // | // | You should have received a copy of the MIT License // | along with PmQm library. If not, see <mit-license.org>. // +------------------------------------------------------------------------- #ifndef __PM_VECTOR_ARRAY_H #define __PM_VECTOR_ARRAY_H class PmLinearMotion; class PmVectorArray { private: int oSize; int size; public: PmVector* vectors; public: PmVectorArray(); ~PmVectorArray(); PmMaskType getMask() const; int getSize() const { return size; } void setSize( int ); PmVector& getVector( int i ) const { return vectors[i]; } void setVector( int i, PmVector const& v ) { vectors[i] = v; } void getLinearVectors( jhm::vector* ) const; void setLinearVectors( jhm::vector* ); void getAngularVectors( int, jhm::vector* ) const; void setAngularVectors( int, jhm::vector* ); void amplify( m_real, PmMaskType ); // // Operators // PmVectorArray& operator=( PmVectorArray const& ); PmVectorArray& operator+=( PmVectorArray const& ); PmVectorArray& operator*=( m_real ); PmVectorArray& operator*=( PmVectorArray const& ); PmVectorArray& operator/=( m_real ); PmVectorArray& difference( PmLinearMotion const&, PmLinearMotion const& ); PmVectorArray& difference( PmVectorArray const&, PmVectorArray const& ); }; #endif
[ "garethvlf@gmail.com" ]
garethvlf@gmail.com
910e1b7164b253165ea1f248dbb6d3076d9a34ee
6fb8585833e3aa7889e4b739febdbea654215ea0
/달리자/utils.h
df12d51777c13d138f345dfd0f45c3ae23bc8a40
[]
no_license
tagnopher/runrunrunrunrun
7db73b3445a6fc413864d89b99b119f03e8b3798
bd82659e47915320a8976c345c3d3f678e1f15c9
refs/heads/master
2021-04-15T14:38:35.358621
2018-03-21T06:43:34
2018-03-21T06:43:34
null
0
0
null
null
null
null
UHC
C++
false
false
509
h
#pragma once //상호참조를 피하기 위해 cpp파일에 stdafx.h 참조 #define PI 3.141592654f #define PI2 PI * 2 class gameNode; //일주일의 고생은 이것을 위함이여찌 namespace THETA_UTIL { struct ST_ImageAndRect //픽셀 충돌에 사용할 스트럭쳐 { image* _image; RECT _rc; }; float getDistance(float startX, float startY, float endX, float endY); float getAngle(float x1, float y1, float x2, float y2); bool pixelCol(ST_ImageAndRect* ir1, ST_ImageAndRect* ir2); }
[ "pao.kim.si.woong@gmail.com" ]
pao.kim.si.woong@gmail.com
aa0d8c2be80d6d80ea2b2894a990cb6dcf7bd8f9
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
/out/release/gen/skia/public/mojom/image_info.mojom-shared.cc
e3793e5d2eedb555f35b4e69f619bd29dd52ba0a
[ "BSD-3-Clause" ]
permissive
xueqiya/chromium_src
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
refs/heads/main
2022-07-30T03:15:14.818330
2021-01-16T16:47:22
2021-01-16T16:47:22
330,115,551
1
0
null
null
null
null
UTF-8
C++
false
false
4,380
cc
// skia/public/mojom/image_info.mojom-shared.cc is auto generated by mojom_bindings_generator.py, do not edit // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4065) #endif #include "skia/public/mojom/image_info.mojom-shared.h" #include <utility> #include "base/logging.h" #include "base/stl_util.h" // for base::size() #include "mojo/public/cpp/bindings/lib/validate_params.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/cpp/bindings/lib/validation_util.h" #include "skia/public/mojom/image_info.mojom-params-data.h" namespace skia { namespace mojom { std::ostream& operator<<(std::ostream& os, ColorType value) { switch(value) { case ColorType::UNKNOWN: return os << "ColorType::UNKNOWN"; case ColorType::ALPHA_8: return os << "ColorType::ALPHA_8"; case ColorType::RGB_565: return os << "ColorType::RGB_565"; case ColorType::ARGB_4444: return os << "ColorType::ARGB_4444"; case ColorType::RGBA_8888: return os << "ColorType::RGBA_8888"; case ColorType::BGRA_8888: return os << "ColorType::BGRA_8888"; case ColorType::INDEX_8: return os << "ColorType::INDEX_8"; case ColorType::GRAY_8: return os << "ColorType::GRAY_8"; default: return os << "Unknown ColorType value: " << static_cast<int32_t>(value); } } std::ostream& operator<<(std::ostream& os, AlphaType value) { switch(value) { case AlphaType::UNKNOWN: return os << "AlphaType::UNKNOWN"; case AlphaType::ALPHA_TYPE_OPAQUE: return os << "AlphaType::ALPHA_TYPE_OPAQUE"; case AlphaType::PREMUL: return os << "AlphaType::PREMUL"; case AlphaType::UNPREMUL: return os << "AlphaType::UNPREMUL"; default: return os << "Unknown AlphaType value: " << static_cast<int32_t>(value); } } namespace internal { // static bool ImageInfo_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) return false; // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const ImageInfo_Data* object = static_cast<const ImageInfo_Data*>(data); static constexpr struct { uint32_t version; uint32_t num_bytes; } kVersionSizes[] = {{ 0, 32 }}; if (object->header_.version <= kVersionSizes[base::size(kVersionSizes) - 1].version) { // Scan in reverse order to optimize for more recent versions. for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) { if (object->header_.version >= kVersionSizes[i].version) { if (object->header_.num_bytes == kVersionSizes[i].num_bytes) break; ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } } } else if (object->header_.num_bytes < kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) { ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } if (!::skia::mojom::internal::ColorType_Data ::Validate(object->color_type, validation_context)) return false; if (!::skia::mojom::internal::AlphaType_Data ::Validate(object->alpha_type, validation_context)) return false; if (!mojo::internal::ValidatePointerNonNullable( object->serialized_color_space, 3, validation_context)) { return false; } const mojo::internal::ContainerValidateParams serialized_color_space_validate_params( 0, false, nullptr); if (!mojo::internal::ValidateContainer(object->serialized_color_space, validation_context, &serialized_color_space_validate_params)) { return false; } return true; } ImageInfo_Data::ImageInfo_Data() : header_({sizeof(*this), 0}) {} } // namespace internal } // namespace mojom } // namespace skia #if defined(_MSC_VER) #pragma warning(pop) #endif
[ "xueqi@zjmedia.net" ]
xueqi@zjmedia.net
cda49c7d76b1c7934dad7b007a01f12f77f72a4c
60a15a584b00895e47628c5a485bd1f14cfeebbe
/common2/win_main.cpp
4b5938e2afbb1dd5acc06d489440e717057e69eb
[]
no_license
fcccode/vt5
ce4c1d8fe819715f2580586c8113cfedf2ab44ac
c88049949ebb999304f0fc7648f3d03f6501c65b
refs/heads/master
2020-09-27T22:56:55.348501
2019-06-17T20:39:46
2019-06-17T20:39:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,849
cpp
#include "stdafx.h" #include "com_main.h" #include "win_main.h" #include "nameconsts.h" //window funcs LRESULT __stdcall WorkWindowProc( HWND hWnd, UINT nMessage, WPARAM wParam, LPARAM lParam ) { CMessageFilterImpl *pFilter = (CMessageFilterImpl*)hWnd; LRESULT lres = pFilter->DoMessage(nMessage, wParam, lParam); return lres; } LRESULT __stdcall InitWindowProc( HWND hWnd, UINT nMessage, WPARAM wParam, LPARAM lParam ) { if( nMessage == WM_NCCREATE ) { CREATESTRUCT *pcs = (CREATESTRUCT*)lParam; CWinImpl *pwnd = (CWinImpl*)pcs->lpCreateParams; pwnd->Subclass( hWnd ); return pwnd->DoMessage( nMessage, wParam, lParam ); } return 0; } INT_PTR __stdcall InitDlgProc( HWND hWnd, UINT nMessage, WPARAM wParam, LPARAM lParam ) { if( nMessage == WM_INITDIALOG ) { CWinImpl *pwnd = (CWinImpl*)lParam; pwnd->Subclass( hWnd ); return pwnd->DoMessage( nMessage, wParam, lParam ); } return 0; } //implementation base functionality of window CWinImpl::CWinImpl() { m_hwnd = 0; m_dwWindowFlags = 0; m_pDefHandler = 0; strcpy( m_szClassName, szDefClassName ); } CWinImpl::~CWinImpl() { if( ::IsWindow( m_hwnd ) && m_pDefHandler ) ::SetWindowLongPtr( m_hwnd, GWLP_WNDPROC, (LONG_PTR)m_pDefHandler ); } IUnknown *CWinImpl::DoGetWinInterface( const IID &iid ) { if( iid == IID_IWindow2 )return (IWindow2*)this; else if( iid == IID_IWindow )return (IWindow*)this; else return 0; } void CWinImpl::Subclass( HWND hwnd ) { m_hwnd = hwnd; char szClassName[64]; ::GetClassName( m_hwnd, szClassName, 64 ); m_thunk.Init( (DWORD_PTR)WorkWindowProc, (IMessageFilter*)this ); m_pDefHandler = (WNDPROC)::GetWindowLongPtr( m_hwnd , GWLP_WNDPROC ); CWndClass *pclass = App::instance()->FindWindowClass( szClassName ); if( pclass && pclass->lpfnWndProc == m_pDefHandler ) m_pDefHandler = DefWindowProc; ::SetWindowLongPtr( m_hwnd, GWLP_WNDPROC, (LONG_PTR)m_thunk.GetCodeAddress() ); } void CWinImpl::Detach() { if( m_hwnd ) ::SetWindowLongPtr( m_hwnd, GWLP_WNDPROC, (LONG_PTR)m_pDefHandler ); m_pDefHandler = 0; m_hwnd = 0; } LRESULT CWinImpl::DoMessage( UINT nMsg, WPARAM wParam, LPARAM lParam ) { LRESULT lRes = CMessageFilterImpl::DoMessage( nMsg, wParam, lParam ); if( lRes != 0 )return lRes; switch( nMsg ) { case WM_CREATE: return DoCreate( (CREATESTRUCT*)lParam ); case WM_PAINT: DoPaint();return 1; case WM_COMMAND: DoCommand( (UINT)wParam );return 1; case WM_NOTIFY: DoNotify( (UINT)wParam, (NMHDR*)lParam ); case WM_GETINTERFACE: return (LRESULT)this; } /* if( nMsg == WM_CREATE ){return DoCreate( );}else if( nMsg == WM_PAINT ){ DoPaint(); return true;}else if( nMsg == WM_ERASEBACKRGND ){ return DoEraseBackgrnd(); }else if( nMsg == WM_ERASEBACKRGND ){ DoCommand(); }else*/ if( m_pDefHandler )lRes = CallWindowProc( m_pDefHandler, m_hwnd, nMsg, wParam, lParam ); if( lRes != 0 )return lRes; if( nMsg == WM_NCCREATE )return 1; if( nMsg == WM_NCDESTROY ) { m_hwnd = 0; m_pDefHandler = 0; } return 0; } HRESULT CWinImpl::CreateWnd( HANDLE hwndParent, RECT rect, DWORD dwStyles, UINT nID ) { m_hwnd = ::CreateWindow( m_szClassName, 0/*m_szTitle*/, dwStyles, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top, (HWND)hwndParent, (HMENU)nID, App::instance()->m_hInstance, this ); if( m_hwnd == 0 ) { App::instance()->handle_error(); return E_FAIL; } return S_OK; } HRESULT CWinImpl::DestroyWindow() { ::DestroyWindow( m_hwnd ); return S_OK; } HRESULT CWinImpl::GetHandle( HANDLE *phwnd ) { *phwnd = m_hwnd; return S_OK; } HRESULT CWinImpl::HelpHitTest( POINT pt, BSTR *pbstrHelpFileName, DWORD *pdwTopicID, DWORD *pdwHelpCommand ) { return S_OK; } HRESULT CWinImpl::PreTranslateMsg( MSG *pmsg, BOOL *pbReturn ) { TPOS pos = m_ptrsMsgListeners.head(); while( pos ) { IMsgListenerPtr ptrML( m_ptrsMsgListeners.get(pos) ); pos = m_ptrsMsgListeners.next(pos); if(ptrML==0) continue; LONG_PTR lRes = 0; if( ptrML->OnMessage( pmsg, &lRes ) == S_FALSE ) { *pbReturn = true; break; } } return S_OK; } HRESULT CWinImpl::GetWindowFlags( DWORD *pdwFlags ) { *pdwFlags = m_dwWindowFlags; return S_OK; } HRESULT CWinImpl::SetWindowFlags( DWORD dwFlags ) { m_dwWindowFlags = dwFlags; return S_OK; } HRESULT CWinImpl::PreTranslateAccelerator( MSG *pmsg ) { //paul not S_OK default S_FALSE; return S_FALSE; } //IWindow2 HRESULT CWinImpl::AttachMsgListener( IUnknown *punk ) { IUnknownPtr ptr(punk); dbg_assert( !m_ptrsMsgListeners.find( ptr ) ); m_ptrsMsgListeners.add_tail( punk ); return S_OK; } HRESULT CWinImpl::DetachMsgListener( IUnknown *punk ) { IUnknownPtr ptr(punk); TPOS pos = m_ptrsMsgListeners.find(ptr); dbg_assert( pos!=0 ); if(pos) m_ptrsMsgListeners.remove(pos); return S_OK; } HRESULT CWinImpl::AttachDrawing( IUnknown *punk ) { return E_NOTIMPL; } HRESULT CWinImpl::DetachDrawing( IUnknown *punk ) { return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// //window class implementation CWndClass::CWndClass( const char *pszName, WNDPROC pproc ) { ZeroMemory( (WNDCLASSEX*)this, sizeof( WNDCLASSEX ) ); strcpy( m_szClassName, pszName ); cbSize = sizeof( WNDCLASSEX ); style = CS_OWNDC|CS_OWNDC|CS_DBLCLKS; lpfnWndProc = pproc?pproc:InitWindowProc; cbClsExtra = 0; cbWndExtra = 0; hInstance = 0; hIcon = 0; hCursor = ::LoadCursor( hInstance, MAKEINTRESOURCE(IDC_ARROW) ); hbrBackground = 0; lpszMenuName = 0; lpszClassName = m_szClassName; hIconSm = 0; m_bRegistred = false; m_pnext = 0; } bool CWndClass::Register() { if( m_bRegistred )return true; hInstance = App::handle(); m_bRegistred = ::RegisterClassEx((WNDCLASSEXA*)this) != 0; if( !m_bRegistred ) App::instance()->handle_error(); return m_bRegistred; }
[ "videotestc@gmail.com" ]
videotestc@gmail.com
f3a5be5d6153f535da54a793ef6e498442f158f3
77086efce198577027ec783e85c87640b5eaf23a
/51-100/91_Decode Ways.cpp
946164b0449f3f1750b880206069debd23a6cc8f
[]
no_license
guisongchen/leetcode_try
42113c745dc0ce018c2b6a6ef7ad4b20bbfe055b
fdedc0b9a3501e25369459d6882c8e08f8cd1f79
refs/heads/master
2020-11-27T20:38:30.220535
2020-03-07T07:38:45
2020-03-07T07:38:45
229,593,324
0
0
null
null
null
null
UTF-8
C++
false
false
1,814
cpp
/* A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. Example 1: Input: "12" Output: 2 Explanation: It could be decoded as "AB" (1 2) or "L" (12). Example 2: Input: "226" Output: 3 Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). */ // keypoints: // 1. use dynamic planning // 2. like "climbing stairs" // 3. corner case: 1001, 010... // if (s[i-1] == '0') // if (i > 1 && s.substr(i-2,2) <= "26" && s.substr(i-2, 2) >= "10") class Solution { public: int numDecodings(string s) { // corner case "010" if (s.empty() || s[0] == '0') return 0; vector<int> dp(s.size()+1, 0); // we have make sure s[0] != '0' before dp[0] = 1; // transform equation, we consider 3 elements as a tuple // dp[i-1] stands for '1' cases, dp[i-2] stands for '12' cases // dp[i] = dp[i-1] + dp[i-2] // // also we should notice dp pointer is 1 step ahead of string pointer // aka we stand out of the string(not at the end), and count for (int i = 1, n = dp.size(); i < n; i++) { if (s[i-1] == '0') dp[i] += 0; // i-1_th is '0', no contribute to i else dp[i] += dp[i-1]; if (i > 1 && s.substr(i-2,2) <= "26" && s.substr(i-2, 2) >= "10") dp[i] += dp[i-2]; else dp[i] += 0; // "i-1, i-2" out range, no contribute to i // no way if (dp[i] == 0) break; } return dp.back(); } };
[ "noreply@github.com" ]
noreply@github.com
dcaa0d6b9974d15f7c540927a47ec33bd4a77a64
58cbd7a2a989a5cb683e714a53e23e5d43afebac
/src/vlCore/VLXVisitorCountIDs.hpp
570190e246cfe6f0324d21da0de963d66c710df0
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
kmatheussen/Visualization-Library
91711bb067b9bf5da4fbe59dc54cf9a618f92dda
16a3e8105ccd63cd6ca667fa061a63596102ef79
refs/heads/master
2020-12-28T19:57:33.901418
2017-07-05T09:46:22
2017-07-05T09:46:22
16,648,504
1
1
null
null
null
null
UTF-8
C++
false
false
5,554
hpp
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* 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. */ /* */ /* 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 VLXVisitorCountIDs_INCLUDE_ONCE #define VLXVisitorCountIDs_INCLUDE_ONCE #include <vlCore/VLXVisitor.hpp> #include <vlCore/VLXValue.hpp> #include <vlCore/Log.hpp> #include <vlCore/Say.hpp> namespace vl { /** Counts the number of occurrencies of each ID. If an ID is occurring more than 1 it means that belongs to a VLXStructure which is referenced by somebody. */ class VLXVisitorCountIDs: public VLXVisitor { VL_INSTRUMENT_CLASS(vl::VLXVisitorCountIDs, VLXVisitor) public: VLXVisitorCountIDs(): mIDSet(NULL) {} virtual void visitStructure(VLXStructure* obj) { if(!obj->uid().empty() && obj->uid() != "#NULL") (*mIDSet)[obj->uid()]++; if (isVisited(obj)) return; for(size_t i=0; i<obj->value().size(); ++i) { VLXStructure::Value& keyval = obj->value()[i]; if (keyval.value().type() == VLXValue::Structure) keyval.value().getStructure()->acceptVisitor(this); else if (keyval.value().type() == VLXValue::List) keyval.value().getList()->acceptVisitor(this); else /* if (keyval.value().type() == VLXValue::ArrayID) keyval.value().getArrayID()->acceptVisitor(this); else */ if (keyval.value().type() == VLXValue::ID) (*mIDSet)[keyval.value().getID()]++; } } virtual void visitList(VLXList* list) { // this should happen only if the user manually creates loops if (isVisited(list)) { Log::warning("VLXVisitorCountIDs: cycle detected on VLXList.\n"); return; } for(size_t i=0; i<list->value().size(); ++i) { if (list->value()[i].type() == VLXValue::Structure) list->value()[i].getStructure()->acceptVisitor(this); if (list->value()[i].type() == VLXValue::List) list->value()[i].getList()->acceptVisitor(this); else /* if (list->value()[i].type() == VLXValue::ArrayID) list->value()[i].getArrayID()->acceptVisitor(this); else */ if (list->value()[i].type() == VLXValue::ID) (*mIDSet)[list->value()[i].getID()]++; } } /* virtual void visitArray(VLXArrayString*) {} virtual void visitArray(VLXArrayID* arr) { // retrieves the assigned Structure for(size_t i=0 ;i<arr->value().size(); ++i) (*mIDSet)[arr->value()[i].uid()]++; } virtual void visitArray(VLXArrayIdentifier*) {} */ virtual void visitArray(VLXArrayInteger*) {} virtual void visitArray(VLXArrayReal*) {} void setIDSet(std::map< std::string, int >* uids) { mIDSet = uids; } std::map< std::string, int >* uidSet() { return mIDSet; } const std::map< std::string, int >* uidSet() const { return mIDSet; } private: std::map< std::string, int >* mIDSet; }; } #endif
[ "michele@visualizationlibrary.com" ]
michele@visualizationlibrary.com
a7e968fb1e48fc5b4805fdceba0469ccd7793cd6
f0c4ebbf54d5aed19df22b760c5b0ce5257829c5
/shared/render/zcolor.cpp
b45f1048c73ba96b1f9d0b4eb45cbc36c2962338
[ "MIT" ]
permissive
proydakov/zeptobird
e85f3c5a2e3eca9b2bb63624d898c83e05f50318
c9e64aa8bd11e4ed9254bea222b03c6d027b6145
refs/heads/master
2021-06-16T02:16:05.766348
2021-04-18T12:51:43
2021-04-18T12:51:43
67,238,634
6
1
MIT
2019-06-16T17:08:31
2016-09-02T16:34:38
C++
UTF-8
C++
false
false
20
cpp
#include "zcolor.h"
[ "admin@Mac-Admin.local" ]
admin@Mac-Admin.local
bad70cbb921ed73a40bd5bfb5b3a4450ee970a9b
3f422ccae084b5d1e5df0f87e58ae423bc15d7cb
/BinaryTreeNode/BinaryTreeNode/BinaryTree.h
b30bf348ea6a302520204261d16dad977b100740
[]
no_license
ZyyGitHub/Data-Structures-and-Algorithms
26404a8b54e5576de833a62a6344e2e0657d2540
c5eeb42e1dbf106c60f66370949f3511b9632c6a
refs/heads/master
2020-04-29T03:36:00.313963
2019-04-10T10:58:50
2019-04-10T10:58:50
175,816,129
0
0
null
null
null
null
UTF-8
C++
false
false
1,571
h
#pragma once #include <iostream> template <typename T> class BinaryTree { public: BinaryTree(); ~BinaryTree(); }; template <typename T> class BinaryTreeNode { friend class BinaryTree; public: BinaryTreeNode(); BinaryTreeNode(const T& ele); BinaryTreeNode(const T&ele, BinaryTreeNode<T> *l, BinaryTreeNode<T> *r); T value() const; BinaryTreeNode<T>* leftchild() const; BinaryTreeNode<T>* rightchild() const; void setLeftchild(BinaryTreeNode<T> *l); void setRightchild(BinaryTreeNode<T> *r); void setValue(const T& val); bool isLeaf() const; BinaryTreeNode<T> & operator = (const BinaryTreeNode<T>& Node); BinaryTreeNode<T> * Parent(BinaryTreeNode<T>*current); BinaryTreeNode<T> * LeftSibing(BinaryTreeNode<T>*current); BinaryTreeNode<T> * RightSibing(BinaryTreeNode<T>*current); void createTree(const T& info, BinaryTree<T> &leftTree, BinaryTree<T> &rightTree); void preOrder(BinaryTreeNode<T>*root); void inOrder(BinaryTreeNode<T>*root); void postOrder(BinaryTreeNode<T>*root); void levelOrder(BinaryTreeNode<T>*root); void DeleteOrder(BinaryTreeNode<T>*root); private: T info; }; template<class T> void BinaryTree<T>::PreOrderWithoutRecusion(BinaryTreeNode<T> *root) { using std::stack; stack<BinaryTreeNode<T>*> aStack; BinaryTreeNode<T> *pointer = root; aStack.push(NULL); while (pointer) { Visit(pointer->value); if (pointer->rightchild() != NULL) { aStack.push(pointer->rightchild()); } if (pointer->leftchild() != NULL) { pointer = pointer->leftchild(); } else { pointer = aStack.top(); aStack.pop(); } } }
[ "zyy_id@163.com" ]
zyy_id@163.com
c06ba31e759eda3380cc8851d0da821a07b5d757
ad5b72656f0da99443003984c1e646cb6b3e67ea
/src/frontends/tensorflow/src/op/interpolate.cpp
e4aa6ca322f371d7ae9c1a5540f16648c485c1e4
[ "Apache-2.0" ]
permissive
novakale/openvino
9dfc89f2bc7ee0c9b4d899b4086d262f9205c4ae
544c1acd2be086c35e9f84a7b4359439515a0892
refs/heads/master
2022-12-31T08:04:48.124183
2022-12-16T09:05:34
2022-12-16T09:05:34
569,671,261
0
0
null
null
null
null
UTF-8
C++
false
false
3,838
cpp
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "op_table.hpp" #include "openvino/opsets/opset8.hpp" using namespace std; using namespace ov::opset8; namespace ov { namespace frontend { namespace tensorflow { namespace op { ov::OutputVector translate_interpolate_op(const NodeContext& node) { default_op_checks(node, 2, {"ResizeBilinear", "ResizeNearestNeighbor"}); auto images = node.get_input(0); auto size = node.get_input(1); auto op_name = node.get_name(); auto op_type = node.get_op_type(); // retrieve optional attribute auto tf_align_corners = node.get_attribute<bool>("align_corners", false); auto tf_half_pixel_centers = node.get_attribute<bool>("half_pixel_centers", false); TENSORFLOW_OP_VALIDATION(node, !tf_half_pixel_centers || (tf_half_pixel_centers && !tf_align_corners), "If half_pixel_centers attribute of the node" + op_name + " with op " + op_type + " is True, the attribute align_corners must be False."); // prepare attributes for OpenVINO Interpolate operation Interpolate::InterpolateAttrs interpolate_attrs; interpolate_attrs.shape_calculation_mode = Interpolate::ShapeCalcMode::SIZES; if (op_type == "ResizeNearestNeighbor") { interpolate_attrs.mode = Interpolate::InterpolateMode::NEAREST; interpolate_attrs.nearest_mode = Interpolate::NearestMode::FLOOR; } else if (op_type == "ResizeBilinear") { interpolate_attrs.mode = Interpolate::InterpolateMode::LINEAR; interpolate_attrs.nearest_mode = Interpolate::NearestMode::ROUND_PREFER_FLOOR; } if (tf_align_corners) { interpolate_attrs.coordinate_transformation_mode = Interpolate::CoordinateTransformMode::ALIGN_CORNERS; if (interpolate_attrs.mode == Interpolate::InterpolateMode::NEAREST) { interpolate_attrs.nearest_mode = Interpolate::NearestMode::ROUND_PREFER_CEIL; } } else if (tf_half_pixel_centers) { if (interpolate_attrs.mode == Interpolate::InterpolateMode::NEAREST) { interpolate_attrs.coordinate_transformation_mode = Interpolate::CoordinateTransformMode::TF_HALF_PIXEL_FOR_NN; } else { interpolate_attrs.coordinate_transformation_mode = Interpolate::CoordinateTransformMode::HALF_PIXEL; } } else { interpolate_attrs.coordinate_transformation_mode = Interpolate::CoordinateTransformMode::ASYMMETRIC; } // prepare scales input auto images_shape = make_shared<ShapeOf>(images, ov::element::i32); auto spatial_shape = make_shared<Slice>(images_shape, make_shared<Constant>(element::i64, Shape{1}, std::vector<int64_t>{1}), make_shared<Constant>(element::i64, Shape{1}, std::vector<int64_t>{3}), make_shared<Constant>(element::i64, Shape{1}, std::vector<int64_t>{1}), make_shared<Constant>(element::i64, Shape{1}, std::vector<int64_t>{0})); auto scales = make_shared<Divide>(make_shared<Convert>(size, element::f32), make_shared<Convert>(spatial_shape, element::f32)); // since Interpolate is layout agnostic // we can avoid Transpose operation by specifying axes = {1, 2} for original NHWC layout auto axes = make_shared<Constant>(element::i32, Shape{2}, std::vector<int>({1, 2})); auto interpolate = make_shared<Interpolate>(images, size, scales, axes, interpolate_attrs); set_node_name(node.get_name(), interpolate); return {interpolate}; } } // namespace op } // namespace tensorflow } // namespace frontend } // namespace ov
[ "noreply@github.com" ]
noreply@github.com
6768c7c38b3fa286c95650fb22fb3b7a4937a274
437b2aa8703956fda3ea478ce584f4853e73287f
/SymulacjaCyfrowaABC_MichalSzozdowski/Table.h
e27216668c730c05741b5836b91c490903cdc1a9
[]
no_license
MSzozdowski/Symulacja-Cyfrowa
062b2ca977fcfef337196ad9aecd7f5a3acdce8f
87f69003fddb9122f382639cc161c5e82a794f9b
refs/heads/master
2020-07-26T07:09:08.344860
2019-09-15T09:46:57
2019-09-15T09:46:57
208,573,368
1
0
null
null
null
null
UTF-8
C++
false
false
277
h
#pragma once #include "GroupOfClients.h" class Table { public: GroupOfClients* actual_client_;//klient zajmujacy stolik int size_of_table_; //liczba miejsc przy danym stoliku explicit Table(const int size=0) { actual_client_ = nullptr; size_of_table_ = size; }; };
[ "mszozdowski@gmail.com" ]
mszozdowski@gmail.com
8ec5d47e29ee2fd6d4419e32db523dd354fd32c0
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/statistics/iterator/boost/iterator/range_cycle.hpp
60db23462c95b2b61c15f28c7628ef37f965a12c
[ "BSL-1.0" ]
permissive
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
2,583
hpp
/////////////////////////////////////////////////////////////////////////////// // iterator::range_cycle.hpp // // // // Copyright 2009 Erwann Rogard. Distributed under the Boost // // Software License, Version 1.0. (See accompanying file // // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // /////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_ITERATOR_RANGE_CYCLE_ER_2009 #define BOOST_ITERATOR_RANGE_CYCLE_ER_2009 #include <boost/range.hpp> #include <boost/utility.hpp> #include <boost/iterator/cycle_iterator_ext.hpp> #include <boost/iterator/cycle_iterator2_ext.hpp> #include <boost/numeric/conversion/bounds.hpp> #include <boost/iterator/iterator_traits.hpp> namespace boost{ // W = cycle_iterator_ext or = cycle_iterator2_ext template<template<typename,typename> class W> class iterator_cycle{ public: typedef std::size_t size_type; template<typename It> struct apply{ typedef W<It,size_type> it_; typedef iterator_range<it_> type; }; template<typename It> typename apply<It>::type static make( It b, It e, size_type offset , size_type n ){ typedef typename apply<It>::it_ it_; typedef typename apply<It>::type res_; it_ it(b,e,offset); return res_( it, boost::next(it,n) ); } }; // From a range to a cycle template<template<typename,typename> class W = cycle_iterator_ext> class range_cycle{ public: typedef iterator_cycle<W> it_cycle_; typedef typename it_cycle_::size_type size_type; template<typename R> struct apply : it_cycle_::template apply<typename range_iterator<R>::type> {}; template<typename R> typename apply<R>::type static make( R& r, size_type offset, size_type n ){ return it_cycle_::make( boost::begin(r), boost::end(r), offset, n ); } }; } //boost #endif
[ "erwann.rogard@gmail.com" ]
erwann.rogard@gmail.com
c1120e2a30e495f2082ac5f4906324338e0bedf1
1518a567c1e4dc1d926301e577320f2d48c31ee8
/2darraytranspose.cpp
c8739b180b3f9cd1cd4bfa5026d2f3dd402026a5
[]
no_license
pratyooshanand/C-codes
39458e5399ea96827042d5254da693bef13c5fe9
d967a06fbabd39950270a06ba7fa350712bc5e83
refs/heads/master
2023-05-10T10:32:42.226293
2021-06-08T13:51:01
2021-06-08T13:51:01
374,399,114
0
0
null
2021-06-08T13:51:02
2021-06-06T15:43:00
C++
UTF-8
C++
false
false
305
cpp
#include <iostream> using namespace std; int main(){ char a[50]; cin>>a; int i=0,length=0; while(a[i]!='\0'){ length++; i++; } bool result=true; for(int i=0;i<length;i++){ if(a[i]!=a[length-1-i]){ result=false; break; } } if(result){ cout<<"Palindrome"; }else{ cout<<"Not palindrome"; } }
[ "pratyooshanand00.17@gmail.com" ]
pratyooshanand00.17@gmail.com
5b0553f74e1a37a65e95f22bc589ad63862c8d15
daf011143a2d7a93a968efcbea498f626a657014
/PSCIOB/Optimizer/OptimizerCostFunction.h
37752eab1c93d8d0896b9eb045758d05f77e41a7
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
rblanc/PSCIOB
1f5a288e6972eaf5a1479f19fcb0452d12982428
61f210fa955c18bb126a67f48db82cee90cae211
refs/heads/master
2021-01-13T02:38:16.918396
2013-01-26T17:32:17
2013-01-26T17:32:17
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
3,846
h
/* * This file is part of the psciob library. * * Copyright (c) 2012, Remi Blanc, University of Bordeaux * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /** * \file OptimizerCostFunction.h * \author Rémi Blanc * \date 22. September 2011 */ #ifndef OPTIMIZERCOSTFUNCTION_H_ #define OPTIMIZERCOSTFUNCTION_H_ #include <vnl/vnl_cost_function.h> #include "OptimizationManager_Base.h" namespace psciob { /**\class OptimizerCostFunction * \brief OptimizerCostFunction * wrapping vnl_cost_function, for use with optimizers taken from the vnl library */ /** */ class OptimizerCostFunction: public vnl_cost_function { public: OptimizerCostFunction(int n) : vnl_cost_function(n) { m_outputForbiddenParameters = 1e50; } /** */ void SetCaller(OptimizationManager_Base *c) { m_caller=c; this->set_number_of_unknowns(m_caller->GetNumberOfParameters()); } /** */ inline double GetValue(const vnl_vector<double>& x) {return f(x);} /** */ inline double f(const vnl_vector<double>& x) { if (m_caller->SetParameters(x)) { return m_caller->GetValue(); } else { return m_outputForbiddenParameters; } //return a very large energy value if the parameters are invalid } /** */ void SetCostForForbiddenParameters(double v) { m_outputForbiddenParameters = v; } /** */ double GetCostForForbiddenParameters(double v) { return m_outputForbiddenParameters; } protected: OptimizationManager_Base::Pointer m_caller; double m_outputForbiddenParameters; }; /** Same but using scaling of the values, to handle parameters with different dynamics / sensitivity */ class OptimizerScaledCostFunction: public OptimizerCostFunction { public: OptimizerScaledCostFunction(int n) : OptimizerCostFunction(n) { m_scales.set_size(n); m_scales.fill(1); } /** */ void SetCaller(OptimizationManager_Base *c) { m_caller=c; this->set_number_of_unknowns(m_caller->GetNumberOfParameters()); m_scales.set_size(m_caller->GetNumberOfParameters()); m_scales.fill(1); } /** */ inline double f(const vnl_vector<double>& x) { if (m_caller->SetParameters( element_product(x, m_scales) )) { return m_caller->GetValue(); } else { return m_outputForbiddenParameters; } //return a very large energy value if the parameters are invalid } /** */ void SetScales(vnl_vector<double> sc) { if (sc.size() != m_scales.size()) throw DeformableModelException("OptimizerScaledCostFunction::SetScales : unexpected vector dimension"); m_scales = sc; } protected: vnl_vector<double> m_scales; }; } // namespace psciob #endif /* OPTIMIZERCOSTFUNCTION_H_ */
[ "rblanc33@gmail.com" ]
rblanc33@gmail.com
fad72f0e08b70fdb8aa129e9cd21a417dd87e740
568b5430a43c50177f68ec1e189a8d24c1fc1a76
/test/omp/test_omp_bond_angle_interaction.cpp
1ea0f756b157e6b0e62223556857f9ad82adc55a
[ "MIT" ]
permissive
0ncorhynchus/Mjolnir
070447445d783cd7df15287bf68e393020553eda
548dad6b1365ddcdf3979ef3474d6b8ac11cecaf
refs/heads/master
2020-08-24T20:38:40.833191
2019-10-19T06:33:46
2019-10-19T06:33:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,420
cpp
#define BOOST_TEST_MODULE "test_omp_bond_angle_interaction" #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <mjolnir/math/math.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/potential/local/HarmonicPotential.hpp> #include <mjolnir/omp/System.hpp> #include <mjolnir/omp/RandomNumberGenerator.hpp> #include <mjolnir/omp/BondAngleInteraction.hpp> #include <mjolnir/util/make_unique.hpp> BOOST_AUTO_TEST_CASE(omp_BondAngle) { constexpr double tol = 1e-8; mjolnir::LoggerManager::set_default_logger("test_omp_bond_angle_interaction.log"); using traits_type = mjolnir::OpenMPSimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = typename traits_type::real_type; using coordinate_type = typename traits_type::coordinate_type; using boundary_type = typename traits_type::boundary_type; using system_type = mjolnir::System<traits_type>; using potential_type = mjolnir::HarmonicPotential<real_type>; using interaction_type = mjolnir::BondAngleInteraction<traits_type, potential_type>; using rng_type = mjolnir::RandomNumberGenerator<traits_type>; using sequencial_system_type = mjolnir::System< mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>>; using sequencial_interaction_type = mjolnir::BondAngleInteraction< mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>, potential_type>; const int max_number_of_threads = omp_get_max_threads(); BOOST_TEST_WARN(max_number_of_threads > 2); BOOST_TEST_MESSAGE("maximum number of threads = " << omp_get_max_threads()); for(int num_thread=1; num_thread<=max_number_of_threads; ++num_thread) { omp_set_num_threads(num_thread); BOOST_TEST_MESSAGE("maximum number of threads = " << omp_get_max_threads()); potential_type potential(/* k = */100.0, /* native angle = */ 3.1415 * 0.5); interaction_type interaction(/*topol = */"none", { {std::array<std::size_t, 3>{{0, 1, 2}}, potential}, {std::array<std::size_t, 3>{{1, 2, 3}}, potential}, {std::array<std::size_t, 3>{{2, 3, 4}}, potential}, {std::array<std::size_t, 3>{{3, 4, 5}}, potential}, {std::array<std::size_t, 3>{{4, 5, 6}}, potential}, {std::array<std::size_t, 3>{{5, 6, 7}}, potential}, {std::array<std::size_t, 3>{{6, 7, 8}}, potential}, {std::array<std::size_t, 3>{{7, 8, 9}}, potential} }); sequencial_interaction_type seq_interaction("none", { {std::array<std::size_t, 3>{{0, 1, 2}}, potential}, {std::array<std::size_t, 3>{{1, 2, 3}}, potential}, {std::array<std::size_t, 3>{{2, 3, 4}}, potential}, {std::array<std::size_t, 3>{{3, 4, 5}}, potential}, {std::array<std::size_t, 3>{{4, 5, 6}}, potential}, {std::array<std::size_t, 3>{{5, 6, 7}}, potential}, {std::array<std::size_t, 3>{{6, 7, 8}}, potential}, {std::array<std::size_t, 3>{{7, 8, 9}}, potential} }); rng_type rng(123456789); system_type sys(10, boundary_type{}); for(std::size_t i=0; i<sys.size(); ++i) { sys.mass(i) = 1.0; sys.velocity(i) = mjolnir::math::make_coordinate<coordinate_type>(0, 0, 0); sys.force(i) = mjolnir::math::make_coordinate<coordinate_type>(0, 0, 0); sys.name(i) = "X"; sys.group(i) = "TEST"; } sys.position(0) = mjolnir::math::make_coordinate<coordinate_type>( 0.0, 0.0, 0.0); sys.position(1) = mjolnir::math::make_coordinate<coordinate_type>( 5.0, 0.0, 0.0); sys.position(2) = mjolnir::math::make_coordinate<coordinate_type>( 5.0, 5.0, 0.0); sys.position(3) = mjolnir::math::make_coordinate<coordinate_type>(10.0, 5.0, 0.0); sys.position(4) = mjolnir::math::make_coordinate<coordinate_type>(10.0, 10.0, 0.0); sys.position(5) = mjolnir::math::make_coordinate<coordinate_type>(15.0, 10.0, 0.0); sys.position(6) = mjolnir::math::make_coordinate<coordinate_type>(15.0, 15.0, 0.0); sys.position(7) = mjolnir::math::make_coordinate<coordinate_type>(20.0, 15.0, 0.0); sys.position(8) = mjolnir::math::make_coordinate<coordinate_type>(20.0, 20.0, 0.0); sys.position(9) = mjolnir::math::make_coordinate<coordinate_type>(25.0, 20.0, 0.0); // add perturbation for(std::size_t i=0; i<sys.size(); ++i) { mjolnir::math::X(sys.position(i)) += rng.uniform_real(-0.1, 0.1); mjolnir::math::Y(sys.position(i)) += rng.uniform_real(-0.1, 0.1); mjolnir::math::Z(sys.position(i)) += rng.uniform_real(-0.1, 0.1); } // init sequential one with the same coordinates sequencial_system_type seq_sys(10, boundary_type{}); for(std::size_t i=0; i<sys.size(); ++i) { seq_sys.mass(i) = sys.mass(i); seq_sys.position(i) = sys.position(i); seq_sys.velocity(i) = sys.velocity(i); seq_sys.force(i) = sys.force(i); seq_sys.name(i) = sys.name(i); seq_sys.group(i) = sys.group(i); } #pragma omp parallel { // calculate forces with openmp interaction.calc_force(sys); } sys.merge_forces(); // calculate forces without openmp seq_interaction.calc_force(seq_sys); // check the values are the same for(std::size_t i=0; i<sys.size(); ++i) { BOOST_TEST(mjolnir::math::X(seq_sys.force(i)) == mjolnir::math::X(sys.force(i)), boost::test_tools::tolerance(tol)); BOOST_TEST(mjolnir::math::Y(seq_sys.force(i)) == mjolnir::math::Y(sys.force(i)), boost::test_tools::tolerance(tol)); BOOST_TEST(mjolnir::math::Z(seq_sys.force(i)) == mjolnir::math::Z(sys.force(i)), boost::test_tools::tolerance(tol)); } BOOST_TEST(interaction.calc_energy(sys) == seq_interaction.calc_energy(seq_sys), boost::test_tools::tolerance(tol)); } }
[ "niina.toru.68u@gmail.com" ]
niina.toru.68u@gmail.com
f7c72c0d44e0bc32499f56f2af617b0ef4fe5ebb
c1e01ac2663ae7f764e48a97b59b4abc4802e91a
/FeatureExtractor/evaluator.cc
989245dae76ddd02b17c8de495b03e4364f3550a
[]
no_license
krsnewwave/CS282-Mini-Project
485763982e98f7e6b71b98e119a17d7fae4fdbed
5679467918f27cca5b53f97dbdfa84fcba51baf7
refs/heads/master
2021-01-20T04:39:36.710383
2015-06-01T11:15:29
2015-06-01T11:15:29
35,522,873
2
0
null
null
null
null
UTF-8
C++
false
false
13,073
cc
/* * File: Evaluator.cpp * Author: dylan * * Created on May 13, 2015, 5:18 PM */ #include "evaluator.h" #include "sampler.h" #include "opencv_sift_extractor.h" #include "feature_extractor.h" #include <sys/stat.h> using namespace std; using namespace cv; Evaluator::Evaluator() { } Evaluator::~Evaluator() { } void Evaluator::getLabelsForKnn(string sample_file, const map<string, int>& categories, Mat& labels) { Sampler s; Dataset ds = s.getDataset(sample_file, ""); vector<int> trainingClasses; for (int i = 0; i < ds.size(); i++) { string cat = get<0>(ds[i]); //assign to category -> number map auto search = categories.find(cat); if (search == categories.end()) { throw new runtime_error("Category string not recognized."); } trainingClasses.push_back(search->second); } float trng_class_array[trainingClasses.size()]; //copy contents of vector to float array copy(trainingClasses.begin(), trainingClasses.end(), trng_class_array); labels = Mat(1, trainingClasses.size(), CV_32F, &trng_class_array).clone(); cout << "Response size: " << labels.size() << endl; } void Evaluator::evaluateUsingKNN(string sample_file, string img_file, string dict_file, string feature_type, string training_set, const map<string, int>& categories) { if (feature_type == "sift") { cout << "Feature type: sift" << endl; //load dictionary Mat dictionary; FileStorage fsDict(dict_file, FileStorage::READ); fsDict["vocabulary"] >> dictionary; fsDict.release(); cout << "Dictionary size: " << dictionary.size() << endl; //load training data //convert training to something that can be read by knn cout << "Loading training set" << endl; Mat trainingData; FileStorage fs(training_set, FileStorage::READ); fs["features"] >> trainingData; fs.release(); cout << "Training set size: " << trainingData.size() << endl; //prepare the map for training classes -> vector<int> Mat trainingClasses_mat; getLabelsForKnn(sample_file, categories, trainingClasses_mat); //declare KNN int K = 32; KNearest knn(trainingData, trainingClasses_mat, Mat(), false, 32); cout << "Processing test image" << endl; //load test image OpenCVSIFTDescExtractor ex; Mat img = imread(img_file, CV_LOAD_IMAGE_COLOR); Mat dst; vector<KeyPoint> keyPoints; ex.getSIFTDescriptor(img, dst, keyPoints); //get nearest neighbor FlannBasedMatcher matcher; vector<DMatch> matches; matcher.match(dst, dictionary, matches); float bins[dictionary.rows]; for (int i = 0; i < matches.size(); i++) { bins[matches.at(i).trainIdx] = bins[matches.at(i).trainIdx] + 1; //update number of bins } Mat norm_bins(1, dictionary.rows, CV_32F, &bins); normalize(norm_bins, norm_bins, 0, 1, NORM_MINMAX, -1, Mat()); float predicted = knn.find_nearest(norm_bins, K); //get the integer's equivalent in the map string cat = get_associated_key(categories, static_cast<int> (predicted)); cout << "Predicted category: " << cat << endl; } if (feature_type == "lbp") { cout << "Loading classifier" << endl; Ptr<FaceRecognizer> faceRecognizer = createLBPHFaceRecognizer(); cout << training_set << endl; faceRecognizer->load(training_set); cout << "Classifier loaded. Info:" << faceRecognizer->info() << endl; Mat img = imread(img_file, CV_LOAD_IMAGE_GRAYSCALE); int predicted_label = -1; double predicted_confidence = 0.0; faceRecognizer->predict(img, predicted_label, predicted_confidence); string category = get_associated_key(categories, predicted_label); cout << "Predicted: " << category << endl; } } void Evaluator::evaluate(string train_categories, string test_categories, string imgdir, string dict_file, string feature_type, string training_set_file, const map<string, int>& categories) { if (feature_type == "sift") { cout << "Batch evaluation: SIFT" << endl; //load model //load training data cout << "Loading training set" << endl; Mat trainingData; FileStorage fs(training_set_file, FileStorage::READ); fs["features"] >> trainingData; fs.release(); cout << "Training set size: " << trainingData.size() << endl; //convert training to something that can be read by knn //prepare the map for training classes -> vector<int> //process test dataset Mat training_labels; getLabelsForKnn(train_categories, categories, training_labels); //declare KNN int K = 32; KNearest knn(trainingData, training_labels, Mat(), false, 32); //load dictionary Mat dict; FileStorage fs2(dict_file, FileStorage::READ); fs2["vocabulary"] >> dict; fs2.release(); //prepare the map for training classes -> vector<int> cout << "Preparing test set labels" << endl; Mat test_labels; getLabelsForKnn(test_categories, categories, test_labels); const float* p = (float*) (test_labels.ptr(0)); vector<float> labels(p, p + test_labels.cols); cout << "Extracting test set features" << endl; OpenCVSIFTDescExtractor siftExtractor(2000, 3, 0.004); //reading all images vector<Mat> images; Sampler s; Dataset testDs = s.getDataset(test_categories, imgdir); for (int i = 0; i < testDs.size(); i++) { //read images string file_name = get<1>(testDs[i]); Mat img = imread(file_name, CV_LOAD_IMAGE_COLOR); images.push_back(img); } Mat features; siftExtractor.process_images(images, dict, features); cout << "Features size: " << features.size() << endl; //iterate the test set's features Mat predictionMat, n, d; knn.find_nearest(features, knn.get_max_k(), predictionMat, n, d); cout << "Predictions: [true] [predicted]" << endl; //iterate through the predictions for (int i = 0; i < features.rows; i++) { int pred = static_cast<int> (predictionMat.at<float>(i, 0)); int truth = static_cast<int> (labels[i]); string predicted_class = get_associated_key(categories, pred); string true_class = get_associated_key(categories, truth); string file_name = get<1>(testDs[i]); cout << file_name << "\t" << true_class << "\t" << predicted_class << endl; } } else if (feature_type == "lbp") { cout << "Loading classifier" << endl; Ptr<FaceRecognizer> faceRecognizer = createLBPHFaceRecognizer(); cout << training_set_file << endl; faceRecognizer->load(training_set_file); cout << "Classifier loaded. Info:" << faceRecognizer->name() << endl; Sampler s; Dataset testDs = s.getDataset(test_categories, imgdir); cout << "Predictions: [true] [predicted]" << endl; for (int i = 0; i < testDs.size(); i++) { //read images string file_name = get<1>(testDs[i]); string true_label = get<0>(testDs[i]); Mat img = imread(file_name, CV_LOAD_IMAGE_GRAYSCALE); Mat imgEq; equalizeHist(img, imgEq); int predicted_label = -1; double predicted_confidence = 0.0; faceRecognizer->predict(img, predicted_label, predicted_confidence); string predicted_class = get_associated_key(categories, predicted_label); cout << file_name << "\t" << true_label << "\t" << predicted_class << endl; } } } void Evaluator::evaluateSavedFiles(string train_file, string test_file, string train_categories, string test_categories, const map<string, int>& categories) { cout << "YAML evaluation" << endl; //load model //load training data cout << "Loading training set" << endl; Mat trainingData; FileStorage fs(train_file, FileStorage::READ); fs["features"] >> trainingData; fs.release(); cout << "Training set size: " << trainingData.size() << endl; //convert training to something that can be read by knn //prepare the map for training classes -> vector<int> //process test dataset Mat training_labels; getLabelsForKnn(train_categories, categories, training_labels); //declare KNN int K = 32; KNearest knn(trainingData, training_labels, Mat(), false, 32); cout << "Loading test set" << endl; Mat testData; FileStorage fs3(test_file, FileStorage::READ); fs3["features"] >> testData; fs3.release(); cout << "Test set size: " << testData.size() << endl; //convert training to something that can be read by knn //prepare the map for training classes -> vector<int> //process test dataset //prepare the map for training classes -> vector<int> cout << "Preparing test set labels" << endl; Mat test_labels; getLabelsForKnn(test_categories, categories, test_labels); const float* p = (float*) (test_labels.ptr(0)); vector<float> labels(p, p + test_labels.cols); predict(knn, testData, labels, test_categories, categories); } void Evaluator::predict(KNearest& knn, Mat& features, const vector<float>& labels, string test_categories, const map<string, int> & categories) { Sampler s; Dataset testDs = s.getDataset(test_categories, ""); //iterate the test set's features Mat predictionMat, n, d; knn.find_nearest(features, knn.get_max_k(), predictionMat, n, d); cout << "Predictions: [true] [predicted]" << endl; //iterate through the predictions for (int i = 0; i < features.rows; i++) { int pred = static_cast<int> (predictionMat.at<float>(i, 0)); int truth = static_cast<int> (labels[i]); string predicted_class = get_associated_key(categories, pred); string true_class = get_associated_key(categories, truth); string file_name = get<1>(testDs[i]); cout << file_name << "\t" << true_class << "\t" << predicted_class << endl; } } /** @function main @usage [sample file] [imgdir] [dictionary] [feature type] [model file] * [category file name] [output predictions] */ int main(int argc, char** argv) { if (argc == 1) { cout << "Batch classification: usage: ./evaluator single " "[train categories file] [test categories file] " "[imgdir] [dictionary] " "[feature type] [model file / training set] " "[category file name]" << endl; cout << "Single classification: usage: ./evaluator single [train set] " " [img] [dictionary] feature type] [training set / model file] " "[category file name]" << endl; cout << "Test your YAML: ./evaluation [train yaml] [test yaml] " "[train categories] [test categories] [feature type] " "[dictionary] [categories]" << endl; return 0; } /* The variables' names are quite confusing now. Just refer to the above usage */ string mode = argv[1]; Evaluator e; struct stat sb; if (mode == "batch") { string train_categories = argv[2]; string test_categories = argv[3]; string imgdir_file = argv[4]; string dict_file = argv[5]; string feature_type = argv[6]; string model_file = argv[7]; string category_file_name = argv[8]; map<string, int> categories; categoryMap(category_file_name, categories); e.evaluate(train_categories, test_categories, imgdir_file, dict_file, feature_type, model_file, categories); } else if (mode == "yaml") { string train_yaml = argv[2]; string test_yaml = argv[3]; string train_sample_file = argv[4]; string test_sample_file = argv[5]; string category_file_name = argv[6]; map<string, int> categories; categoryMap(category_file_name, categories); e.evaluateSavedFiles(train_yaml, test_yaml, train_sample_file, test_sample_file, categories); } else if (mode == "single") { string train_categories = argv[2]; string imgdir_file = argv[3]; string dict_file = argv[4]; string feature_type = argv[5]; string model_file = argv[6]; string category_file_name = argv[7]; map<string, int> categories; categoryMap(category_file_name, categories); e.evaluateUsingKNN(train_categories, imgdir_file, dict_file, feature_type, model_file, categories); } }
[ "dylan@ubuntu" ]
dylan@ubuntu
907e07b7a83cd8be1e60ad2fd687d29cdd271c51
a4a71609cb38e8d2bac69c39bc423c19e5ff7737
/algo/flodfill/657 The die is cast.cpp
dac1c1e254af683a292e619285d711d6a4bd1cbf
[]
no_license
fahadahmedocean/srbd
3822c1e6de3de2f484d0dafe11882f2a22e5382a
6aa656fcdd9fbdb2cdc98c74c73cd64fb355ff28
refs/heads/master
2020-04-27T12:31:51.941635
2019-03-07T12:14:01
2019-03-07T12:14:01
174,334,763
0
0
null
null
null
null
UTF-8
C++
false
false
1,937
cpp
//657 The die is cast #include <stdio.h> using namespace std; char pic[51][51]; int w, h; int fx[]= {1,0,-1,0}; int fy[]= {0,1,0,-1}; void floodfill_X (int i, int j) { if(pic[i][j] == 'X') { pic[i][j] = '*'; int a,b; for(int k=0; k<4; k++) { a=i+fx[k]; b=j+fy[k]; floodfill_X(a,b); } } } void ff_dot (int i, int j, int &dots) { if (pic[i][j] == 'X') { dots++; floodfill_X(i, j); } if(pic[i][j] != '.' && i>=0 && j>=0 && i<h && j<w) { pic[i][j] = '.'; int a,b; for(int k=0; k<4; k++) { a=i+fx[k]; b=j+fy[k]; ff_dot(a, b, dots); } } } int main() { // freopen("input.txt","rt",stdin); int Case = 1; while (scanf("%d%d", &w, &h)) { if (0==w && 0==h) break; getchar(); for (int i = 0; i < h; i++) gets(pic[i]); int ans[100] = {0}, nOfans = 0; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) if (pic[i][j] == '*') { ff_dot(i, j, ans[nOfans]); nOfans++; } //just sort the ans array for(int k=0; k<nOfans-1; k++) { for(int p=0; p<nOfans-1-k; p++) { if (ans[p] > ans[p+1]) { int temp= ans[p]; ans[p]=ans[p+1]; ans[p+1]=temp; } } } printf("Throw %d\n", Case++); for (int i = 0; i < nOfans; i++) { if (i) printf(" "); printf("%d", ans[i]); } printf("\n\n"); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
e2d5007912f1cf22af9c2436bb8d859fb8a46a3e
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-securityhub/source/model/UpdateStandardsControlRequest.cpp
e6e9fb6f198571c29beba1aa207333fb0ce32710
[ "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,435
cpp
/* * 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. */ #include <aws/securityhub/model/UpdateStandardsControlRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::SecurityHub::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateStandardsControlRequest::UpdateStandardsControlRequest() : m_standardsControlArnHasBeenSet(false), m_controlStatus(ControlStatus::NOT_SET), m_controlStatusHasBeenSet(false), m_disabledReasonHasBeenSet(false) { } Aws::String UpdateStandardsControlRequest::SerializePayload() const { JsonValue payload; if(m_controlStatusHasBeenSet) { payload.WithString("ControlStatus", ControlStatusMapper::GetNameForControlStatus(m_controlStatus)); } if(m_disabledReasonHasBeenSet) { payload.WithString("DisabledReason", m_disabledReason); } return payload.View().WriteReadable(); }
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
b670c81c716fb2d56b717374e0d223596a9e77f7
2927dcbbb0723e8e76710040407c5561fb6b0121
/04096/windows/sprite-o-mat/sprite-o-mat_src/main.cpp
e193bf837bee7d1ef283814089dcbc0f9216c7b5
[]
no_license
cafferta10/hardcode
9583599825010c16d46e199aaff9b15834730c65
2033e906d3a7850f88dda431f15a70f0981729b9
refs/heads/master
2021-05-22T01:06:19.072005
2019-10-26T03:28:44
2019-10-26T03:28:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,377
cpp
#define WIN32_LEAN_AND_MEAN #define WIN32_EXTRA_LEAN #include "windows.h" #include "d3d9.h" #include "d3dx9.h" #include "mmsystem.h" #include "dsound.h" ///////////////////////////////////////////////////////////////////////////////// // defines ///////////////////////////////////////////////////////////////////////////////// #ifdef _DEBUG #include "stdio.h" #define MYDEBUG //#define EXPORT_SOUND #endif //#define SAFE_CALL(func, msg) if (D3D_OK != func) MessageBox(NULL, msg, "Error", MB_OK); #define SAFE_CALL(func, msg) func; #define MY_RGBA(redval, greenval, blueval, alphaval) ((alphaval << 24) | (redval << 16) | (greenval << 8) | blueval) #define FULLSCREEN #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480 #define BLUR_WIDTH SCREEN_WIDTH/4 #define BLUR_HEIGHT SCREEN_HEIGHT/4 #define TEXT_WIDTH 64 #define TEXT_HEIGHT 64 ///////////////////////////////////////////////////////////////////////////////// // uninitialized data ///////////////////////////////////////////////////////////////////////////////// LPDIRECT3D9 lpD3D; LPDIRECT3DDEVICE9 lpD3DDevice; LPD3DXFONT lpFont; LPD3DXMATRIXSTACK lpMatrixStack; struct RenderTarget { LPDIRECT3DTEXTURE9 lpTexture; LPDIRECT3DSURFACE9 lpColorSurface; LPDIRECT3DSURFACE9 lpDepthSurface; }; // screen sized maps and surfaces #define SCREEN_TARGET 0 // blur maps and surfaces #define BLUR1_TARGET 1 #define BLUR2_TARGET 2 // text maps and surfaces #define TEXT_TARGET 3 // backup target for the original color and depth buffer #define ORIGINAL_TARGET 4 #define MAX_TARGETS 5 RenderTarget lpRenderTarget[MAX_TARGETS]; LPDIRECT3DSURFACE9 lpTextSurface; // shader LPDIRECT3DPIXELSHADER9 lpDirBlurPS; // screen FVF struct QuadVertex { D3DXVECTOR4 p; D3DXVECTOR2 t; }; #define FVF_QUADVERTEX (D3DFVF_XYZRHW | D3DFVF_TEX1) // point sprite FVF struct SpriteVertex { D3DXVECTOR3 p; float s; D3DCOLOR c; }; #define FVF_SPRITEVERTEX (D3DFVF_XYZ | D3DFVF_PSIZE | D3DFVF_DIFFUSE) LPDIRECT3DVERTEXBUFFER9 lpSpriteVB; LPDIRECT3DTEXTURE9 lpSpriteTex; // metaballs struct MetaObject { D3DXVECTOR3 pos; float a, b; }; #define METABALL_COUNT 128 MetaObject MetaBalls[METABALL_COUNT]; #define GP_TYPE_META 0x1 #define GP_TYPE_BORDER 0x2 #define GP_TYPE_TEXT 0x4 struct GridPoint { float value; DWORD flags; }; #define METAGRID_DIM 64 #define METAGRID_SHIFT1 6 #define METAGRID_SHIFT2 12 GridPoint MetaGrid[METAGRID_DIM*METAGRID_DIM*METAGRID_DIM]; // sound #define SAMPLES_PER_SEC 22050 #define SONG_LENGTH 5*60*2*SAMPLES_PER_SEC #define SOUND_BUFFERS 2 #define DBUFFER_SIZE 65536 #define DBUFFER_MASK 0xffff int dbuffer[DBUFFER_SIZE]; LPDIRECTSOUNDBUFFER8 lpDSBuffer[SOUND_BUFFERS]; // the buffer where the gm.dls file name is copied to and then the data itself char lpFileBuffer[0x800000]; // beat state for base, snare. 3rd entry is pattern index int BeatState[3][SONG_LENGTH]; DWORD LastTick; #ifdef EXPORT_SOUND // the export sound buffer signed short lpSoundBuffer[SONG_LENGTH*2]; #endif char ClearFlags; DWORD RandSeed; struct SceneVars { float fov; float fend; float minI; float maxI; float yaw; float pitch; float roll; float up; float zoom; DWORD blendfactor; }; SceneVars Scene_Vars; float PatternTick; float RadPatternTick; ///////////////////////////////////////////////////////////////////////////////// // initialized data ///////////////////////////////////////////////////////////////////////////////// #include "music.h" #include "shaders.h" #pragma data_seg(".screen") D3DPRESENT_PARAMETERS screen_params = { SCREEN_WIDTH, SCREEN_HEIGHT, D3DFMT_A8R8G8B8, 1, D3DMULTISAMPLE_NONE, 0, D3DSWAPEFFECT_DISCARD, 0, // HWND #ifdef FULLSCREEN 0, #else 1, #endif 1, D3DFMT_D24S8, 0, D3DPRESENT_RATE_DEFAULT, D3DPRESENT_INTERVAL_DEFAULT }; #pragma data_seg(".quadvtx") float quad_vertices[2][24] = { // blur sized { 0.0f, 0.0f, 0.0f, 1.0f, 0.5f/(BLUR_WIDTH), 0.5f/(BLUR_HEIGHT), BLUR_WIDTH, 0.0f, 0.0f, 1.0f, 1.0f+0.5f/(BLUR_WIDTH), 0.5f/(BLUR_HEIGHT), 0.0f, BLUR_HEIGHT, 0.0f, 1.0f, 0.5f/(BLUR_WIDTH), 1.0f+0.5f/(BLUR_HEIGHT), BLUR_WIDTH, BLUR_HEIGHT, 0.0f, 1.0f, 1.0f+0.5f/(BLUR_WIDTH), 1.0f+0.5f/(BLUR_HEIGHT) }, // screen sized { 0.0f, 0.0f, 0.0f, 1.0f, 0.5f/(SCREEN_WIDTH), 0.5f/(SCREEN_HEIGHT), SCREEN_WIDTH, 0.0f, 0.0f, 1.0f, 1.0f+0.5f/(SCREEN_WIDTH), 0.5f/(SCREEN_HEIGHT), 0.0f, SCREEN_HEIGHT, 0.0f, 1.0f, 0.5f/(SCREEN_WIDTH), 1.0f+0.5f/(SCREEN_HEIGHT), SCREEN_WIDTH, SCREEN_HEIGHT, 0.0f, 1.0f, 1.0f+0.5f/(SCREEN_WIDTH), 1.0f+0.5f/(SCREEN_HEIGHT) } }; #pragma data_seg(".blurpar") float blur_params[3][4] = { { 1.0f/(SCREEN_WIDTH), 1.0f/(SCREEN_WIDTH), 0.00f, 1.0f }, // downsample4 + brightpass { 1.2f/(BLUR_WIDTH), 0.0f, 0.0f, 2.0f }, // blurx, no threshold { 0.0f, 1.2f/(BLUR_HEIGHT), 0.0f, 2.0f}, // blury, no threshold }; #ifdef EXPORT_SOUND char WaveHeader[44] = { 'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ', 16, 0, 0, 0, 1, 0, 1, 0, 0x22, 0x56, 0, 0, 0x44, 0xac, 0, 0, 2, 0, 16, 0, 'd', 'a', 't', 'a', 0, 0, 0, 0 }; #endif #pragma data_seg(".sndfmt") WAVEFORMATEX WaveFMT = { WAVE_FORMAT_PCM, 1, // channels SAMPLE_RATE, // samples per sec SAMPLE_RATE*2, // bytes per sec 2, // block alignment; 16, // bits per sample 0 // extension not needed }; #pragma data_seg(".snddesc") DSBUFFERDESC SoundDesc = { 36, DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2, MAX_SAMPLES, 0, &WaveFMT, GUID_NULL }; #pragma data_seg(".sndfx") float vcf[5] = { 0.0f, 0.0f, 0.0f, 1.0f, 0.3f }; #pragma data_seg(".sndfx") int dpos = 0; #pragma data_seg(".sndfx") int ddelay = SAMPLES_PER_PATTERN/8; #pragma data_seg(".greet") #define NUM_GREETS 8 char* Greetings[NUM_GREETS] = { "fairlight", "farb rausch", "bypass", "tbl", "mfx", "sts", "s!p", "0ok" }; #pragma data_seg(".greet") LONG GreetRect[4] = { 0, 0, TEXT_WIDTH, TEXT_HEIGHT }; #pragma data_seg(".sysstr") char FontName[] = "System"; #pragma data_seg(".sysstr") char WindowName[] = "EDIT"; #pragma data_seg(".sysstr") char DLSPath[] = "\\drivers\\gm.dls"; #pragma data_seg(".metavar") float GridOffset[3] = {METAGRID_DIM/2, METAGRID_DIM/2, METAGRID_DIM/2}; #pragma data_seg(".metavar") float axis[3][3] = { {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 1.0f} }; float fPointScaleC = 1.0f; #pragma data_seg(".viewvar") DWORD HDRBlendFactor = 0xffffffff; #pragma data_seg(".scnvar") SceneVars scv[6] = { { 0.0f, 40.0f, 0.0f, 0.1f, 0.0f, D3DX_PI, 0.0f, 0.0f, 6.0f, D3DBLEND_INVBLENDFACTOR }, { 1.5f, 40.0f, 0.5f, 64.0f, 0.0f, D3DX_PI, 0.0f, 0.0f, 20.0f, D3DBLEND_ONE }, { 1.4f, 80.0f, 0.5f, 64.0f, 0.0f, D3DX_PI, 0.0f, 0.0f, 30.0f, D3DBLEND_ONE }, { 1.0f, 80.0f, 0.5f, 64.0f, 0.0f, 0.0f, 0.0f, 0.0f, 30.0f, D3DBLEND_ONE }, { 2.0f, 7.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, D3DBLEND_ONE }, { 1.0f, 80.0f, 0.5f, 64.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, D3DBLEND_ONE } }; ///////////////////////////////////////////////////////////////////////////////// // crt emulation ///////////////////////////////////////////////////////////////////////////////// #ifndef MYDEBUG extern "C" { int _fltused = 1; } #endif #pragma code_seg(".crtemuf") int lrintf (float flt) { int reti; __asm { fld flt fistp reti } return reti; } #pragma code_seg(".crtemuf") float HzDsqrtf(float i) { __asm fld i __asm fsqrt } #pragma code_seg(".crtemuf") float HzDsinf(float i) { __asm fld i __asm fsin } #pragma code_seg(".crtemuf") float HzDcosf(float i) { __asm fld i __asm fcos } #pragma code_seg(".crtemuf") float HzDfmodf(float i, float j) { __asm fld j __asm fld i __asm fprem __asm fxch __asm fstp i } #pragma code_seg(".crtemuf") float HzDfabsf(float i) { __asm fld i __asm fabs } #pragma code_seg(".crtemui") void HzDZeroMemory(void* dest, SIZE_T s) { __asm mov edi, dest __asm xor eax, eax __asm mov ecx, s __asm rep stosb } #pragma code_seg(".crtemui") void HzDCopyMemory(void* dest, void* source, SIZE_T s) { __asm mov esi, source __asm mov edi, dest __asm mov ecx, s __asm rep movsb } #pragma code_seg(".crtemui") unsigned long RandomNumber() { RandSeed = (RandSeed * 196314165) + 907633515; return RandSeed; } ///////////////////////////////////////////////////////////////////////////////// // code ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // Render Stuff ///////////////////////////////////////////////////////////////////////////////// #pragma code_seg(".crtgt") void CreateRenderTarget(RenderTarget* tgt, DWORD sizex, DWORD sizey) { // create the color surface SAFE_CALL(lpD3DDevice->CreateTexture( sizex, sizey, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &(tgt->lpTexture), NULL ), "RT CreateTexture failed"); // grab and store color surfaces SAFE_CALL(tgt->lpTexture->GetSurfaceLevel( 0, &(tgt->lpColorSurface)), "RT GetSurfaceLevel failed"); // create the depth surface SAFE_CALL(lpD3DDevice->CreateDepthStencilSurface( sizex, sizey, D3DFMT_D24S8, D3DMULTISAMPLE_NONE, 0, TRUE, &(tgt->lpDepthSurface), NULL ), "RT CreateDepthStencilSurface failed"); } #pragma code_seg(".setrs") void SetRenderState(D3DRENDERSTATETYPE type, DWORD value) { SAFE_CALL(lpD3DDevice->SetRenderState(type, value), "SetRenderState failed"); } #pragma code_seg(".sadtrt") void SetAndDrawToRenderTarget(int tgt, int src, int which) { SAFE_CALL(lpD3DDevice->SetRenderTarget( 0, lpRenderTarget[tgt].lpColorSurface ), "SetRenderTarget failed"); SAFE_CALL(lpD3DDevice->SetDepthStencilSurface( lpRenderTarget[tgt].lpDepthSurface ), "SetDepthStencilSurface failed"); lpD3DDevice->SetTexture( 0, 0 ); lpD3DDevice->Clear(0, NULL, ClearFlags, 0, 1.0f, 0); if (which >= 0) { lpD3DDevice->SetTexture( 0, lpRenderTarget[src].lpTexture ); lpD3DDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 2, quad_vertices[which], sizeof(QuadVertex) ); } } #pragma code_seg(".updmb") void Update_Metaballs(int from, int num) { while (from < num) { int influenceRange = 1+lrintf(MetaBalls[from].b); int posx = lrintf(MetaBalls[from].pos.x); int posy = lrintf(MetaBalls[from].pos.y); int posz = lrintf(MetaBalls[from].pos.z); for (int z = posz-influenceRange; z < posz+influenceRange; ++z) { if (z < 0 || z >= METAGRID_DIM) continue; for (int y = posy-influenceRange; y < posy+influenceRange; ++y) { if (y < 0 || y >= METAGRID_DIM) continue; for (int x = posx-influenceRange; x < posx+influenceRange; ++x) { if (x < 0 || x >= METAGRID_DIM) continue; D3DXVECTOR3 grid(x, y, z); D3DXVECTOR3 dist = MetaBalls[from].pos-grid; float dist2 = dist.x*dist.x+dist.y*dist.y+dist.z*dist.z; float range2 = MetaBalls[from].b*MetaBalls[from].b; if (range2 > dist2) { GridPoint *gp = &MetaGrid[(z<<METAGRID_SHIFT2)+(y<<METAGRID_SHIFT1)+x]; gp->value += MetaBalls[from].a * (1.0f - 0.4444444f*dist2*dist2*dist2/(range2*range2*range2) + 1.8888888f*dist2*dist2/(range2*range2) - 2.4444444f*dist2/range2); gp->flags |= GP_TYPE_META; } } } } ++from; } } #pragma code_seg(".movemb") void Move_Metaballs(float fac) { int movecount = METAGRID_DIM*METAGRID_DIM*METAGRID_DIM; while (movecount--) { if (((movecount >> 12) & 0x3f) > 0) { MetaGrid[movecount].value = fac*MetaGrid[movecount-METAGRID_DIM*METAGRID_DIM].value; MetaGrid[movecount].flags = MetaGrid[movecount-METAGRID_DIM*METAGRID_DIM].flags; } else MetaGrid[movecount].value = 0; } } #pragma code_seg(".drawbra") void DrawBranch(int tick, int axis1, int axis2, int from, float rot) { float translation = BeatState[2][tick]; if (translation > 8.0f) translation = 8.0f; float metarange = 8.0f; lpMatrixStack->LoadIdentity(); lpMatrixStack->RotateAxisLocal((D3DXVECTOR3*)axis[1], tick/44100.0f); lpMatrixStack->RotateAxisLocal((D3DXVECTOR3*)axis[0], tick/44100.0f); lpMatrixStack->RotateAxisLocal((D3DXVECTOR3*)axis[axis1], tick/44100.0f); lpMatrixStack->RotateAxisLocal((D3DXVECTOR3*)axis[axis2], rot); int i = 10; while (i--) { MetaBalls[i+from].pos = *((D3DXVECTOR3*)(&(lpMatrixStack->GetTop()->_41)))+*((D3DXVECTOR3*)&GridOffset); MetaBalls[i+from].a = 1; MetaBalls[i+from].b = metarange; metarange *= 0.9f; lpMatrixStack->ScaleLocal(0.9f, 0.9f, 0.9f); lpMatrixStack->TranslateLocal(0.0f, translation, 0.0f); lpMatrixStack->RotateAxisLocal((D3DXVECTOR3*)axis[0], 0.3f*HzDsinf(tick/88200.0f)); lpMatrixStack->RotateAxisLocal((D3DXVECTOR3*)axis[1], 0.9f*HzDsinf(tick/44100.0f)); } } #pragma code_seg(".mbcol") DWORD Metaball_Color(GridPoint* gp, float* maxval) { *maxval = 2.0f*gp->value-1.0f; if (*maxval > 1.0f) *maxval = 1.0f; DWORD metacolor = MY_RGBA(196, 64+lrintf(192.0f*(1.0f-*maxval)), 0, 0); if (gp->flags & GP_TYPE_META) { if (gp->flags & GP_TYPE_BORDER) return ((metacolor & 0xfefefefe) >> 1) + MY_RGBA(0, 64, 92, 0); else return metacolor; } else { if (gp->flags & GP_TYPE_BORDER) return MY_RGBA(0, 128, 196, 0); else return MY_RGBA(128, 228, 128, 0); } } #pragma code_seg(".crespr") DWORD Create_Sprites() { int counter = 0; SpriteVertex* sprites; SAFE_CALL(lpSpriteVB->Lock(0, 0, (void**)(&sprites),D3DLOCK_DISCARD), "Vertexbuffer Lock failed"); int spritecount = METAGRID_DIM*METAGRID_DIM*METAGRID_DIM; while (spritecount--) { int posx, posy, posz; posx = spritecount & 0x3f; posy = (spritecount >> 6) & 0x3f; posz = (spritecount >> 12) & 0x3f; GridPoint *gp = &MetaGrid[spritecount]; if (gp->value > Scene_Vars.minI && gp->value < Scene_Vars.maxI) { float maxval; D3DXVECTOR3 mpos(posx, posy, posz); sprites->p = mpos-*((D3DXVECTOR3*)&GridOffset); sprites->c = Metaball_Color(gp, &maxval); sprites->s = HzDfabsf(1.5f*maxval); ++counter; ++sprites; } } SAFE_CALL(lpSpriteVB->Unlock(), "Vertexbuffer Unlock failed"); return counter; } #pragma code_seg(".drawspr") void Draw_Sprites(DWORD num) { // set projection matrix float proj[16]; D3DXMatrixPerspectiveFovLH((D3DXMATRIX*)proj, Scene_Vars.fov, (float)SCREEN_WIDTH/(float)SCREEN_HEIGHT, 1.0f, 1000.0f); lpD3DDevice->SetTransform(D3DTS_PROJECTION, (D3DXMATRIX*)proj); // set view matrix lpMatrixStack->LoadIdentity(); lpMatrixStack->TranslateLocal(0.0f, Scene_Vars.up, Scene_Vars.zoom); lpMatrixStack->RotateAxisLocal((D3DXVECTOR3*)axis[1], Scene_Vars.yaw); lpMatrixStack->RotateAxisLocal((D3DXVECTOR3*)axis[0], Scene_Vars.pitch); lpMatrixStack->RotateAxisLocal((D3DXVECTOR3*)axis[2], Scene_Vars.roll); lpD3DDevice->SetTransform(D3DTS_VIEW, lpMatrixStack->GetTop()); SetRenderState(D3DRS_ALPHATESTENABLE, true); SetRenderState(D3DRS_FOGENABLE, true); SetRenderState(D3DRS_POINTSPRITEENABLE, true); SetRenderState(D3DRS_POINTSCALEENABLE, true); SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_EQUAL);; SetRenderState(D3DRS_FOGTABLEMODE, D3DFOG_LINEAR); SetRenderState(D3DRS_ALPHAREF, 0xff); SetRenderState(D3DRS_FOGEND, *((DWORD*)&(Scene_Vars.fend))); SetRenderState(D3DRS_POINTSCALE_C, *((DWORD*)axis)); lpD3DDevice->SetTexture(0, lpSpriteTex); lpD3DDevice->SetFVF(FVF_SPRITEVERTEX); lpD3DDevice->SetStreamSource(0, lpSpriteVB, 0, sizeof(SpriteVertex)); lpD3DDevice->DrawPrimitive(D3DPT_POINTLIST, 0, num); SetRenderState(D3DRS_ALPHATESTENABLE, false); SetRenderState(D3DRS_FOGENABLE, false); SetRenderState(D3DRS_POINTSPRITEENABLE, false); SetRenderState(D3DRS_POINTSCALEENABLE, false); } #pragma code_seg(".render1") void Render_Field(DWORD tick) { static DWORD lasttick = 0; if (!lasttick) HzDZeroMemory(MetaGrid, sizeof(GridPoint)*METAGRID_DIM*METAGRID_DIM*METAGRID_DIM); DWORD delta = (tick-lasttick) / 1760; //fix animation to about 25Hz if (delta) lasttick = tick; while (delta--) { Move_Metaballs(0.98f); for (int i = 0; i < 4; i++) { MetaBalls[i].pos = D3DXVECTOR3(RandomNumber()>>26, RandomNumber()>>26, 8); MetaBalls[i].a = 1; MetaBalls[i].b = 4+(RandomNumber()>>29); } Update_Metaballs(0, 4); } } void Draw_Cube() { int bordercount = METAGRID_DIM*METAGRID_DIM*METAGRID_DIM; while (bordercount--) { int xyzmod; bool border = false; int runner = bordercount; xyzmod = runner & 0x3f; if (!xyzmod || xyzmod == METAGRID_DIM-1) border = true; runner = runner >> 6; xyzmod = runner & 0x3f; if (!xyzmod || xyzmod == METAGRID_DIM-1) border = true; runner = runner >> 6; xyzmod = runner & 0x3f; if (!xyzmod || xyzmod == METAGRID_DIM-1) border = true; runner = runner >> 6; if (border) { MetaGrid[bordercount].value = 0.75; MetaGrid[bordercount].flags = GP_TYPE_BORDER; } } } #pragma code_seg(".render4") void Render_Tentacle(DWORD tick) { HzDZeroMemory(MetaGrid, sizeof(GridPoint)*METAGRID_DIM*METAGRID_DIM*METAGRID_DIM); Draw_Cube(); // metaball tentacle DrawBranch(tick, 1, 0, 0, 0.0f); DrawBranch(tick, 1, 0, 10, D3DX_PI); DrawBranch(tick, 2, 0, 20, D3DX_PI/2); DrawBranch(tick, 2, 0, 30, -D3DX_PI/2); DrawBranch(tick, 0, 2, 40, D3DX_PI/2); DrawBranch(tick, 0, 2, 50, -D3DX_PI/2); Update_Metaballs(0, 60); } #pragma code_seg(".render5") void Render_Greetings(DWORD tick) { HzDZeroMemory(MetaGrid, sizeof(GridPoint)*METAGRID_DIM*METAGRID_DIM*METAGRID_DIM); Draw_Cube(); static int oldgreet = -1; int greet = BeatState[2][tick] & (NUM_GREETS-1); if (greet != oldgreet) { ClearFlags = D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER; SetAndDrawToRenderTarget(TEXT_TARGET, NULL, -1); lpFont->DrawText(NULL, Greetings[greet], -1, (LPRECT)GreetRect, DT_WORDBREAK | DT_NOCLIP | DT_CENTER | DT_VCENTER, 0xffffffff); ClearFlags = 0; SetAndDrawToRenderTarget(SCREEN_TARGET, NULL, -1); SAFE_CALL(lpD3DDevice->GetRenderTargetData(lpRenderTarget[TEXT_TARGET].lpColorSurface, lpTextSurface), "Text GetRenderTargetData failed"); oldgreet = greet; } D3DLOCKED_RECT lrect; SAFE_CALL(lpTextSurface->LockRect(&lrect, NULL, D3DLOCK_READONLY), "Text LockRect failed");; int z = 30; while (z++ < 34) { int yx = METAGRID_DIM*METAGRID_DIM; while (yx--) { if (*(((DWORD*)lrect.pBits)+yx)) { MetaGrid[(z<<METAGRID_SHIFT2)+yx].value = 0.75; MetaGrid[(z<<METAGRID_SHIFT2)+yx].flags = GP_TYPE_TEXT; } } } SAFE_CALL(lpTextSurface->UnlockRect(), "Text LockRect failed");; } #pragma code_seg(".preren") void Prepare_Scene(int i) { HzDCopyMemory(&Scene_Vars, &scv[i], sizeof(Scene_Vars)); } #pragma code_seg(".render") void Render(DWORD tick) { if (BeatState[2][tick] < 16) { // birth Prepare_Scene(0); Render_Tentacle(tick); Scene_Vars.fov = 3.0414f-HzDsinf(RadPatternTick)*0.1f; } else if (BeatState[2][tick] < 32) { // metaball field Prepare_Scene(1); Render_Field(tick - 16*SAMPLES_PER_PATTERN); Scene_Vars.yaw = HzDsinf(RadPatternTick)*0.2f; Scene_Vars.pitch += BeatState[0][tick+100]*0.1f; Scene_Vars.roll = tick/88200.0f; } else if (BeatState[2][tick] < 40) { // greetings Prepare_Scene(2); Render_Greetings(tick); Scene_Vars.yaw = 0.5f-HzDfmodf(PatternTick, 1); Scene_Vars.up = -5.0f+HzDfmodf(PatternTick*20.0f, 20.0f); } else if (BeatState[2][tick] < 56) { // tentacle Prepare_Scene(3); Render_Tentacle(tick - 40*SAMPLES_PER_PATTERN); Scene_Vars.yaw = RadPatternTick/10.0f; Scene_Vars.roll = RadPatternTick/10.0f; } else if (BeatState[2][tick] < 64) { // pseudo plasma Prepare_Scene(4); Render_Tentacle(tick); Scene_Vars.yaw = RadPatternTick*0.2f; } else if (BeatState[2][tick] < 72) { // tentacle Prepare_Scene(5); Render_Tentacle(tick); Scene_Vars.yaw = RadPatternTick/10.0f; Scene_Vars.roll = RadPatternTick/10.0f; Scene_Vars.zoom = -800.0f+RadPatternTick*2.0f; } LastTick = tick; // draw the scene Draw_Sprites(Create_Sprites()); } void SetPixelShaderConstantF(float* p1) { SAFE_CALL(lpD3DDevice->SetPixelShaderConstantF(0, p1, 1), "SetPixelShaderConstantF failed"); } #pragma code_seg(".rintro") void RenderIntro(DWORD tick) { lpD3DDevice->BeginScene(); // render scenes to screen buffer ClearFlags = D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER; SetAndDrawToRenderTarget(SCREEN_TARGET, NULL, -1); lpD3DDevice->SetPixelShader(0); Render(tick); // do post processing ... ClearFlags = 0; lpD3DDevice->SetFVF( FVF_QUADVERTEX ); lpD3DDevice->SetPixelShader(lpDirBlurPS); // downsample4 + brightpass SetPixelShaderConstantF(blur_params[0]); SetAndDrawToRenderTarget(BLUR1_TARGET, SCREEN_TARGET, 0); // blur horizontal SetPixelShaderConstantF(blur_params[1]); SetAndDrawToRenderTarget(BLUR2_TARGET, BLUR1_TARGET, 0); // blur vertical SetPixelShaderConstantF(blur_params[2]); SetAndDrawToRenderTarget(BLUR1_TARGET, BLUR2_TARGET, 0); lpD3DDevice->SetPixelShader(0); SetRenderState(D3DRS_SRCBLEND, D3DBLEND_BLENDFACTOR); SetRenderState(D3DRS_DESTBLEND, Scene_Vars.blendfactor); SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); SetRenderState(D3DRS_BLENDFACTOR, HDRBlendFactor); SetAndDrawToRenderTarget(SCREEN_TARGET, BLUR1_TARGET, 1); SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); SetAndDrawToRenderTarget(ORIGINAL_TARGET, SCREEN_TARGET, 1); lpD3DDevice->EndScene(); lpD3DDevice->Present(NULL,NULL,NULL,NULL); } ///////////////////////////////////////////////////////////////////////////////// // Initialization ///////////////////////////////////////////////////////////////////////////////// #pragma code_seg(".clamps") int ClampSound(int val) { if (val > 32767) val = 32767; if (val < -32767) val = -32767; return val; } #pragma code_seg(".fxsnd") void Process_Effects(short* data[], DWORD s) { short* dest; int input; // lowpass for 1st buffer dest = (data[0]+s); input = *dest; vcf[0] = vcf[0] + vcf[3]*vcf[2]; vcf[1] = input - vcf[0] - vcf[4]*vcf[2]; vcf[2] = vcf[3]*vcf[1] + vcf[2]; *dest = ClampSound(lrintf(vcf[0])); // delay for 2nd buffer dest = (data[1]+s); input = *dest; int val = dbuffer[(dpos + DBUFFER_SIZE - ddelay) & DBUFFER_MASK]; dbuffer[dpos++] = input + (val>>1); dpos &= DBUFFER_MASK; *dest = ClampSound((input+val)>>1); } #pragma code_seg(".reninst") void Render_Instrument(Instrument* inst, short* data[], DWORD s, float speed) { short* dest = (data[inst->flags & TARGET_BUFFER_MASK]+s); short* src = (short*)(lpFileBuffer+inst->waveDataOffset); int bla = *dest; bla += (*(src+lrintf(inst->playPos))*inst->volume)>>8; *dest++ = ClampSound(bla); inst->playPos += speed; } #pragma code_seg(".rensnd") void Render_Sound() { DWORD size; short *data[2]; SAFE_CALL(lpDSBuffer[0]->Lock(0, 0, (LPVOID*)(&(data[0])), &size, 0, 0, DSBLOCK_ENTIREBUFFER), "Sound Lock failed"); SAFE_CALL(lpDSBuffer[1]->Lock(0, 0, (LPVOID*)(&(data[1])), &size, 0, 0, DSBLOCK_ENTIREBUFFER), "Sound Lock failed"); #ifdef EXPORT_SOUND FILE *ef = fopen("sound.wav", "wb"); HzDCopyMemory(lpSoundBuffer, WaveHeader, sizeof(WaveHeader)); int exportoffset = 22; #endif // fill all buffers with samples for (int s = 0; s < MAX_SAMPLES; s++) { int pindex = s / SAMPLES_PER_PATTERN; int tindex = (s / SAMPLES_PER_TICK) & 15; if (pindex == MAX_PATTERNS) break; for (int i = 0; i < MAX_INSTRUMENTS; i++) { Instrument* inst = &IntroInstruments[i]; int whichPattern = inst->patternSeq[pindex]; NotePattern* npat = &(((NotePattern*)(inst->patterns))[whichPattern]); int curpattern = ((WORD*)(inst->patterns))[whichPattern]; int samples2Render = 0; float playspeed = 1.0f; // percussion? if (inst->flags & NOTE_PATTERN_TYPE_BIT) { BYTE note = npat->tick[tindex]; if (note != inst->lastVal) inst->playPos = 0.0f; inst->lastVal = note; if (note) { float mul; if (note > 128) { note -= 128; mul = SQRT_12_2; } else { note = 128-note; mul = SQRT_12_2_INV; } float freq = 1.0f; while (note--) freq *= mul; playspeed = freq; samples2Render = 1; } } else { int beat = (curpattern >> tindex) & 1; // new tick pos? if (tindex != inst->lastVal) { inst->lastVal = tindex; // have to play? if (beat) { inst->playPos = 0.0f; samples2Render = inst->length; } } // remember beat state at each ms for sync lateron BeatState[i][s] = beat; } int cs = s; while (samples2Render--) { Render_Instrument(inst, data, cs++, playspeed); } } BeatState[2][s] = pindex; Process_Effects(data, s); if (pindex >= 40 && pindex < 48) { float fac = (((float)s/(float)SAMPLES_PER_PATTERN)-40.0f)/8.0f; vcf[3] = fac*fac; } #ifdef EXPORT_SOUND lpSoundBuffer[exportoffset] = ClampSound(data[0][s] + data[1][s]); exportoffset++; #endif } #ifdef EXPORT_SOUND *((DWORD*)(&lpSoundBuffer[2])) = exportoffset*2 - 8; *((DWORD*)(&lpSoundBuffer[20])) = exportoffset*2 - 44; fwrite(lpSoundBuffer, 1, exportoffset*2, ef); fclose(ef); #endif SAFE_CALL(lpDSBuffer[0]->Unlock(data[0], size, 0, 0), "Sound Unlock failed"); SAFE_CALL(lpDSBuffer[1]->Unlock(data[1], size, 0, 0), "Sound Unlock failed"); } #pragma code_seg(".initsnd") void Init_Sound() { // init sound objects LPDIRECTSOUND8 lpDS; LPDIRECTSOUNDBUFFER lpDSB; SAFE_CALL(DirectSoundCreate8(NULL, &lpDS, NULL), "Sound DirectSoundCreate8 failed"); SAFE_CALL(lpDS->SetCooperativeLevel(screen_params.hDeviceWindow, DSSCL_PRIORITY), "Sound SetCooperativeLevel failed"); SAFE_CALL(lpDS->CreateSoundBuffer(&SoundDesc, &lpDSB, 0), "Sound CreateSoundBuffer failed"); SAFE_CALL(lpDSB->QueryInterface( IID_IDirectSoundBuffer8, (LPVOID*) &lpDSBuffer[0] ), "Sound QueryInterface failed"); SAFE_CALL(lpDS->CreateSoundBuffer(&SoundDesc, &lpDSB, 0), "Sound CreateSoundBuffer failed"); SAFE_CALL(lpDSB->QueryInterface( IID_IDirectSoundBuffer8, (LPVOID*) &lpDSBuffer[1] ), "Sound QueryInterface failed"); // open gm.dls file DWORD size = GetSystemDirectory(lpFileBuffer, 0x7f); HzDCopyMemory(lpFileBuffer+size, DLSPath, sizeof(DLSPath)); _lread(_lopen(lpFileBuffer, 0), lpFileBuffer, 0x800000); // add a synth base drum to the basedrum of the gm.dls short* src = (short*)(lpFileBuffer+0x26b3d0); int samples = 4930/2; int amp = 20000; float freq = 220.0f/22050.0f; float phase = 0.0f; while (samples--) { int bla = *src >> 2; bla += lrintf(amp*HzDsinf(phase*2.0f*D3DX_PI)); phase += freq; freq *= 0.999f; if (samples < 500) amp -= 40; *src++ = ClampSound(bla); } Render_Sound(); // play sound lpDSBuffer[0]->Play(0, 0, 0); lpDSBuffer[1]->Play(0, 0, 0); } #pragma code_seg(".initmb") void Init_Graphics() { SAFE_CALL(lpD3DDevice->CreateVertexBuffer(sizeof(SpriteVertex)*METAGRID_DIM*METAGRID_DIM*METAGRID_DIM, D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY | D3DUSAGE_POINTS, FVF_SPRITEVERTEX, D3DPOOL_DEFAULT, &lpSpriteVB, NULL), "Sprite CreateVertexBuffer failed"); SAFE_CALL(lpD3DDevice->CreateTexture( 256, 256, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &lpSpriteTex, NULL ), "Sprite CreateTexture failed"); // create a sphere texture D3DLOCKED_RECT lr; SAFE_CALL(lpSpriteTex->LockRect(0, &lr, 0, 0), "Sprite LockRect failed"); D3DCOLOR* pixel = (D3DCOLOR*)lr.pBits; int texcount = 256*256; while (texcount--) { int x = (texcount & 0xff) - 128; int y = ((texcount >> 8) & 0xff) -128; int cval = lrintf((1.0f-HzDsqrtf(x*x + y*y)/128.0f)*256.0f); if (cval < 0) cval = 0; int aval = cval > 0 ? 255 : 0; *pixel++ = MY_RGBA(cval, cval, cval, aval); } SAFE_CALL(lpSpriteTex->UnlockRect(0), "Sprite UnlockRect failed"); } #pragma code_seg(".init") void Init() { // create the window screen_params.hDeviceWindow = CreateWindowEx( WS_EX_TOPMOST | WS_EX_APPWINDOW, WindowName, WindowName, WS_VISIBLE | WS_POPUP,0,0, SCREEN_WIDTH,SCREEN_HEIGHT, 0,0,0,0); // create d3d object lpD3D = Direct3DCreate9(D3D_SDK_VERSION); // create 3d3 device SAFE_CALL(lpD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, screen_params.hDeviceWindow, D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &screen_params, &lpD3DDevice), "Create Device Failed"); // create the screen map CreateRenderTarget(&lpRenderTarget[SCREEN_TARGET], SCREEN_WIDTH, SCREEN_HEIGHT); // create the half screen map CreateRenderTarget(&lpRenderTarget[BLUR1_TARGET], BLUR_WIDTH, BLUR_HEIGHT); // create the half screen map CreateRenderTarget(&lpRenderTarget[BLUR2_TARGET], BLUR_WIDTH, BLUR_HEIGHT); // create the text map CreateRenderTarget(&lpRenderTarget[TEXT_TARGET], TEXT_WIDTH, TEXT_HEIGHT); SAFE_CALL(lpD3DDevice->CreateOffscreenPlainSurface( TEXT_WIDTH, TEXT_HEIGHT, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &lpTextSurface, NULL ), "CreateOffscreenPlainSurface Failed"); // save original color and depth surfaces SAFE_CALL(lpD3DDevice->GetRenderTarget( 0, &(lpRenderTarget[ORIGINAL_TARGET].lpColorSurface) ), "GetRenderTarget Failed"); SAFE_CALL(lpD3DDevice->GetDepthStencilSurface( &(lpRenderTarget[ORIGINAL_TARGET].lpDepthSurface) ), "GetDepthStencilSurface Failed"); // some state init lpD3DDevice->SetRenderState(D3DRS_LIGHTING, false); lpD3DDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); lpD3DDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_BORDER ); lpD3DDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_BORDER ); // create the pixel shader SAFE_CALL(lpD3DDevice->CreatePixelShader((DWORD*)DirBlurPS, &lpDirBlurPS), "CreatePixelShader Failed"); // create the font SAFE_CALL(D3DXCreateFont( lpD3DDevice, // D3D device 0, // Height 0, // Width FW_DONTCARE, // Weight 0, // MipLevels, 0 = autogen mipmaps FALSE, // Italic ANSI_CHARSET, // CharSet OUT_DEFAULT_PRECIS, // OutputPrecision DEFAULT_QUALITY, // Quality DEFAULT_PITCH | FF_DONTCARE, // PitchAndFamily FontName, // pFaceName &lpFont), "D3DXCreateFont failed"); // ppFont */ // create a matrix stack SAFE_CALL(D3DXCreateMatrixStack(0, &lpMatrixStack), "D3DXCreateMatrixStack failed"); // sound Init_Graphics(); Init_Sound(); // hide the mouse cursor ShowCursor(false); } ///////////////////////////////////////////////////////////////////////////////// // entry point for the executable if msvcrt is not used ///////////////////////////////////////////////////////////////////////////////// #pragma code_seg(".main") #ifndef MYDEBUG void mainCRTStartup(void) #else void main() #endif { Init(); while(!GetAsyncKeyState(VK_ESCAPE)) { DWORD playpos; lpDSBuffer[0]->GetCurrentPosition(&playpos, 0); PatternTick = HzDfmodf(playpos*0.5f/(float)SAMPLES_PER_PATTERN, 1.0f); RadPatternTick = playpos*D3DX_PI/(float)SAMPLES_PER_PATTERN; RenderIntro(playpos>>1); if (playpos > 4762800) ExitProcess(0); } ExitProcess(0); }
[ "youngthug@youngthug.com" ]
youngthug@youngthug.com
4272d957fecfde2aceead209f7f29e0aae1faf56
07953cbf62e36b1e05f03b4c4e0bdfa26501561c
/98 octalto hexa.cpp
38f12ce1ec3942e8625f5fa67f09765a06fdb796
[]
no_license
SiD3110/100-Programs
0925ea3ef347a59ced484648f2a230908bacd0c4
7344d50b212157ab737832bf5e534ebde4e63075
refs/heads/master
2022-01-20T20:56:03.141529
2019-07-22T21:29:06
2019-07-22T21:29:06
198,266,532
0
0
null
null
null
null
UTF-8
C++
false
false
289
cpp
#include<stdio.h> #include<cmath> int main() { int oct,j=0; scanf("%d",&oct); int dec=0; while(oct) { int d=oct%10; dec+=d*pow(8,j); j++; oct/=10; } int hex=0,p=0; while(dec) { int d=dec%16; hex+=d*pow(10,p); p++; dec/=16; } printf("%d",hex); return 0; }
[ "noreply@github.com" ]
noreply@github.com
426448ddbf7ff617e5685478fef4d1d2e1df5fe4
c97236faf7fc44fe6115dadffcd01dc1b910df2b
/2019-06/4 - Range projections.cpp
3efad69b491f9fd36b84f05fe6445e986b2c06a0
[ "CC-BY-4.0" ]
permissive
st-louis-cpp-meetup/Presentations
f3377d05bbb93874c548e9fd3b73ffe7d7809f4d
2e3a31a6285aabf295a9bf494bf7470844196857
refs/heads/master
2020-04-28T20:29:57.093659
2020-04-02T00:38:55
2020-04-02T00:38:55
175,546,243
2
0
null
null
null
null
UTF-8
C++
false
false
1,250
cpp
//-std=c++2a -I/opt/compiler-explorer/libs/cmcstl2/include -fconcepts #include <iostream> #include <string> #include <vector> #include <experimental/ranges/algorithm> // from cmcstl2 namespace ranges = std::experimental::ranges; //projections //"transformation that an algorithm applies before inspecting the values of elements" struct Employee { int id; std::string name; Employee(int id_, std::string name_): id(id_), name(name_) {} }; void old_and_busted(std::vector<Employee>& v) { std::sort(v.begin(), v.end(), [](Employee a, Employee b) { return a.id < b.id; }); } void new_hotness(std::vector<Employee>& v) { ranges::sort(v, ranges::less{}, &Employee::id); } int main() { std::vector<Employee> employees = {{5, "Kubrick"}, {2, "Burgess"}, {7, "Carlos"} }; old_and_busted(employees); for (auto employee: employees) { std::cout << employee.id << " " << employee.name << "\n"; } std::vector<Employee> employees2 = {{5, "Stanley"}, {2, "Anthony"}, {7, "Wendy"} }; new_hotness(employees2); for (auto employee: employees2) { std::cout << employee.id << " " << employee.name << "\n"; } } // other ranges versions of most algorithms also support projections: // find, for_each, replace_if, etc
[ "jfultz@wolfram.com" ]
jfultz@wolfram.com
7e3dfe5d25b2860e072612b87edb90a6bb499381
1286c49e178f3171cc986e677feceb8a2094a009
/Algorithms/Math/Permutation_and_Combination/prev_permutation.cpp
e6d8f10ce875061afe20c782d4e8875b98f3267f
[ "MIT" ]
permissive
amlesh-dev/Data-Structure-and-Algorithm
8ed3b494309c6a94d6e8f7402eb30dba05f12663
a5a58f7c74cf5ce3b445b8b90bcae2ac76a3c684
refs/heads/master
2022-12-19T00:30:36.742508
2020-10-01T08:38:29
2020-10-01T08:38:29
300,206,960
0
0
MIT
2020-10-01T08:36:37
2020-10-01T08:36:36
null
UTF-8
C++
false
false
524
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; bool PrevPermutation(string &str) { int n = str.size(); int i = n - 1; while(i && str[i - 1] <= str[i]) i--; if (!i) return false; int j = i + 1; while(j < n && str[i - 1] >= str[j]) j++; swap(str[i - 1], str[j-1]); reverse(str.begin() + i, str.end()); return true; } int main() { string str; cout << "Enter string : "; cin >> str; PrevPermutation(str); cout << "Prev Permutation : " << str << "\n"; }
[ "cr7.aditya.cs@gmail.com" ]
cr7.aditya.cs@gmail.com
02619dfb45aa0f9d4d0548f9607e551f25819da1
ef516abbf3cafc99dec7e12ddd9ee9423a0ccd93
/Synergy/src/Synergy/System/SystemBase.h
5dad53c257ea243f7f532c62d8beaa11e64f0551
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
nmrsmn/synergy
15fb3baf851ab600b7a716c8ee26ee39b2f369a0
7f77c70c131debe66d2e91e00827fd30e736cf81
refs/heads/develop
2021-04-13T06:32:56.229898
2020-05-17T15:08:24
2020-05-17T15:08:24
249,143,774
0
0
MIT
2020-05-22T11:15:13
2020-03-22T08:40:09
C
UTF-8
C++
false
false
1,261
h
// Created by Niels Marsman on 15-05-2020. // Copyright © 2020 Niels Marsman. All rights reserved. #ifndef SYNERGY_SYSTEM_SYSTEM_BASE_H #define SYNERGY_SYSTEM_SYSTEM_BASE_H #include "Synergy/Core.h" #include "Synergy/System/SystemTraits.h" namespace Synergy { class SYNERGY_API SystemBase { public: virtual ~SystemBase() {} virtual bool HasEntities() const = 0; virtual bool HasInitialize() const = 0; virtual bool HasDestroy() const = 0; virtual bool HasEnable() const = 0; virtual bool HasDisable() const = 0; virtual bool HasLoad() const = 0; virtual bool HasUnload() const = 0; virtual bool HasReload() const = 0; virtual bool HasFrameStart() const = 0; virtual bool HasFrameEnd() const = 0; virtual bool HasFixedUpdate() const = 0; virtual bool HasPreProcess() const = 0; virtual bool HasProcess() const = 0; virtual bool HasPostProcess() const = 0; virtual bool HasUpdate() const = 0; virtual bool HasPostUpdate() const = 0; virtual void OnFrameStart() = 0; virtual void OnFrameEnd() = 0; virtual void OnUpdate(float dt) = 0; }; } #endif
[ "niels.marsman@luminis.eu" ]
niels.marsman@luminis.eu
97688fff5b00072ed274ab19464c4e05f783a1db
cb77dcbbce6c480f68c3dcb8610743f027bee95c
/android/art/tools/titrace/titrace.cc
981ad56e86f781b273a82275ea51cfec6c3b857b
[ "MIT", "Apache-2.0", "NCSA" ]
permissive
fengjixuchui/deoptfuscator
c888b93361d837ef619b9eb95ffd4b01a4bef51a
dec8fbf2b59f8dddf2dbd10868726b255364e1c5
refs/heads/master
2023-03-17T11:49:00.988260
2023-03-09T02:01:47
2023-03-09T02:01:47
333,074,914
0
0
MIT
2023-03-09T02:01:48
2021-01-26T12:16:31
null
UTF-8
C++
false
false
9,946
cc
// Copyright (C) 2017 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. // #include "instruction_decoder.h" #include <android-base/logging.h> #include <atomic> #include <jni.h> #include <jvmti.h> #include <map> #include <memory> #include <mutex> // We could probably return a JNI_ERR here but lets crash instead if something fails. #define CHECK_JVMTI_ERROR(jvmti, errnum) \ CHECK_EQ(JVMTI_ERROR_NONE, (errnum)) << GetJvmtiErrorString((jvmti), (errnum)) << (" ") namespace titrace { static const char* GetJvmtiErrorString(jvmtiEnv* jvmti, jvmtiError errnum) { char* errnum_str = nullptr; jvmti->GetErrorName(errnum, /*out*/ &errnum_str); if (errnum_str == nullptr) { return "Unknown"; } return errnum_str; } // Type-safe wrapper for JVMTI-allocated memory. // Deallocates with jvmtiEnv::Deallocate. template <typename T> struct TiMemory { explicit TiMemory(jvmtiEnv* env, T* mem, size_t size) : env_(env), mem_(mem), size_(size) { } ~TiMemory() { if (mem_ != nullptr) { env_->Deallocate(static_cast<unsigned char*>(mem_)); } mem_ = nullptr; } TiMemory(const TiMemory& other) = delete; TiMemory(TiMemory&& other) { env_ = other.env_; mem_ = other.mem_; size_ = other.size_; if (this != &other) { other.env_ = nullptr; other.mem_ = nullptr; other.size_ = 0u; } } TiMemory& operator=(TiMemory&& other) { if (mem_ != other.mem_) { TiMemory::~TiMemory(); } new (this) TiMemory(std::move(other)); return *this; } T* GetMemory() { return mem_; } size_t Size() { return size_ / sizeof(T); } private: jvmtiEnv* env_; T* mem_; size_t size_; }; struct MethodBytecode { explicit MethodBytecode(jvmtiEnv* env, unsigned char* memory, jint size) : bytecode_(env, memory, static_cast<size_t>(size)) { } TiMemory<uint8_t> bytecode_; }; struct TraceStatistics { static void Initialize(jvmtiEnv* jvmti) { TraceStatistics& stats = GetSingleton(); bool is_ri = true; { jvmtiError error; char* value_ptr; error = jvmti->GetSystemProperty("java.vm.name", /*out*/ &value_ptr); CHECK_JVMTI_ERROR(jvmti, error) << "Failed to get property 'java.vm.name'"; CHECK(value_ptr != nullptr) << "Returned property was null for 'java.vm.name'"; if (strcmp("Dalvik", value_ptr) == 0) { is_ri = false; } } InstructionFileFormat format = is_ri ? InstructionFileFormat::kClass : InstructionFileFormat::kDex; stats.instruction_decoder_.reset(InstructionDecoder::NewInstance(format)); CHECK_GE(arraysize(stats.instruction_counter_), stats.instruction_decoder_->GetMaximumOpcode()); } static TraceStatistics& GetSingleton() { static TraceStatistics stats; return stats; } void Log() { LOG(INFO) << "================================================"; LOG(INFO) << " TI Trace // Summary "; LOG(INFO) << "++++++++++++++++++++++++++++++++++++++++++++++++"; LOG(INFO) << " * Single step counter: " << single_step_counter_; LOG(INFO) << "+++++++++++ Instructions Count ++++++++++++"; size_t total = single_step_counter_; for (size_t i = 0; i < arraysize(instruction_counter_); ++i) { size_t inst_count = instruction_counter_[i]; if (inst_count > 0) { const char* opcode_name = instruction_decoder_->GetName(i); LOG(INFO) << " * " << opcode_name << "(op:" << i << "), count: " << inst_count << ", % of total: " << (100.0 * inst_count / total); } } LOG(INFO) << "------------------------------------------------"; } void OnSingleStep(jvmtiEnv* jvmti_env, jmethodID method, jlocation location) { // Counters do not need a happens-before. // Use the weakest memory order simply to avoid tearing. single_step_counter_.fetch_add(1u, std::memory_order_relaxed); MethodBytecode& bytecode = LookupBytecode(jvmti_env, method); // Decode jlocation value that depends on the bytecode format. size_t actual_location = instruction_decoder_->LocationToOffset(static_cast<size_t>(location)); // Decode the exact instruction and increment its counter. CHECK_LE(actual_location, bytecode.bytecode_.Size()); RecordInstruction(bytecode.bytecode_.GetMemory() + actual_location); } private: void RecordInstruction(const uint8_t* instruction) { uint8_t opcode = instruction[0]; // Counters do not need a happens-before. // Use the weakest memory order simply to avoid tearing. instruction_counter_[opcode].fetch_add(1u, std::memory_order_relaxed); } MethodBytecode& LookupBytecode(jvmtiEnv* jvmti_env, jmethodID method) { jvmtiError error; std::lock_guard<std::mutex> lock(bytecode_cache_mutex_); auto it = bytecode_cache_.find(method); if (it == bytecode_cache_.end()) { jint bytecode_count_ptr = 0; unsigned char* bytecodes_ptr = nullptr; error = jvmti_env->GetBytecodes(method, &bytecode_count_ptr, &bytecodes_ptr); CHECK_JVMTI_ERROR(jvmti_env, error) << "Failed to get bytecodes for method " << method; CHECK(bytecodes_ptr != nullptr) << "Bytecode ptr was null for method " << method; CHECK_GE(bytecode_count_ptr, 0) << "Bytecode size too small for method " << method; // std::pair<iterator, bool inserted> auto&& pair = bytecode_cache_.insert( std::make_pair(method, MethodBytecode(jvmti_env, bytecodes_ptr, bytecode_count_ptr))); it = pair.first; } // Returning the address is safe. if map is resized, the contents will not move. return it->second; } std::unique_ptr<InstructionDecoder> instruction_decoder_; std::atomic<size_t> single_step_counter_{0u}; std::atomic<size_t> instruction_counter_[256]{}; // Cache the bytecode to avoid calling into JVMTI repeatedly. // TODO: invalidate if the bytecode was updated? std::map<jmethodID, MethodBytecode> bytecode_cache_; // bytecode cache is thread-safe. std::mutex bytecode_cache_mutex_; }; struct EventCallbacks { static void SingleStep(jvmtiEnv* jvmti_env, JNIEnv* jni_env ATTRIBUTE_UNUSED, jthread thread ATTRIBUTE_UNUSED, jmethodID method, jlocation location) { TraceStatistics& stats = TraceStatistics::GetSingleton(); stats.OnSingleStep(jvmti_env, method, location); } // Use "kill -SIGQUIT" to generate a data dump request. // Useful when running an android app since it doesn't go through // a normal Agent_OnUnload. static void DataDumpRequest(jvmtiEnv* jvmti_env ATTRIBUTE_UNUSED) { TraceStatistics& stats = TraceStatistics::GetSingleton(); stats.Log(); } }; } // namespace titrace // Late attachment (e.g. 'am attach-agent'). JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM *vm, char* options, void* reserved) { return Agent_OnLoad(vm, options, reserved); } // Early attachment (e.g. 'java -agent[lib|path]:filename.so'). JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* jvm, char* /* options */, void* /* reserved */) { using namespace titrace; // NOLINT [build/namespaces] [5] android::base::InitLogging(/* argv */nullptr); jvmtiEnv* jvmti = nullptr; { jint res = 0; res = jvm->GetEnv(reinterpret_cast<void**>(&jvmti), JVMTI_VERSION_1_1); if (res != JNI_OK || jvmti == nullptr) { LOG(FATAL) << "Unable to access JVMTI, error code " << res; } } LOG(INFO) << "Agent_OnLoad: Hello World"; { // Initialize our instruction file-format decoder. TraceStatistics::Initialize(jvmti); } jvmtiError error{}; // Set capabilities. { jvmtiCapabilities caps = {}; caps.can_generate_single_step_events = 1; caps.can_get_bytecodes = 1; error = jvmti->AddCapabilities(&caps); CHECK_JVMTI_ERROR(jvmti, error) << "Unable to get necessary JVMTI capabilities"; } // Set callbacks. { jvmtiEventCallbacks callbacks = {}; callbacks.SingleStep = &EventCallbacks::SingleStep; callbacks.DataDumpRequest = &EventCallbacks::DataDumpRequest; error = jvmti->SetEventCallbacks(&callbacks, static_cast<jint>(sizeof(callbacks))); CHECK_JVMTI_ERROR(jvmti, error) << "Unable to set event callbacks"; } // Enable events notification. { error = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_SINGLE_STEP, nullptr /* all threads */); CHECK_JVMTI_ERROR(jvmti, error) << "Failed to enable SINGLE_STEP notification"; error = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_DATA_DUMP_REQUEST, nullptr /* all threads */); CHECK_JVMTI_ERROR(jvmti, error) << "Failed to enable DATA_DUMP_REQUEST notification"; } return JNI_OK; } // Note: This is not called for normal Android apps, // use "kill -SIGQUIT" instead to generate a data dump request. JNIEXPORT void JNICALL Agent_OnUnload(JavaVM* vm ATTRIBUTE_UNUSED) { using namespace titrace; // NOLINT [build/namespaces] [5] LOG(INFO) << "Agent_OnUnload: Goodbye"; TraceStatistics::GetSingleton().Log(); }
[ "gyoonus@gmail.com" ]
gyoonus@gmail.com
f333a8556e80cc64c1065672d2d7aa5dfe93d0ea
2e3732dea31ca0e02730c0b4157e794835c1ac5a
/ElectricNet/ElectricDevice.h
f5d0af481bad07a23516d9464f5acc83d1d0e890
[]
no_license
bdmarinov/OOP
9a0a4b6f83f2fb6f57aa5ca746c5fe7e15c1d565
d27d6ba020c7ea67bb4f491cce956c9b6dab52d9
refs/heads/main
2023-01-21T17:11:28.359150
2020-11-28T16:56:42
2020-11-28T16:56:42
315,653,697
0
0
null
null
null
null
UTF-8
C++
false
false
746
h
#ifndef ELECTRICDEVICE_H #define ELECTRICDEVICE_H #include <iostream> #include <string.h> using namespace std; bool isEqual(const char*, const char *); class ElectricDevice { public: ElectricDevice(); ElectricDevice(const char *, int); ElectricDevice(const ElectricDevice &); ElectricDevice &operator=(const ElectricDevice &); void setName(const char *); void setPower(int); char *getName() const { return name; } int getPower() const { return power; } bool operator ==(const ElectricDevice &); friend ostream & operator <<(ostream &, const ElectricDevice &); friend istream & operator >>(istream &, ElectricDevice &); ~ElectricDevice(); private: char *name; int power; }; #endif
[ "noreply@github.com" ]
noreply@github.com
8079944b6a7269f44241af1146fd08145e546ef6
e1ea14e40291110665d16899fcedd9c8dbc46b82
/QueryEngine/TableFunctions/TableFunctionsTesting.hpp
05b49eef52f4d90f2a9314202aeb10dbfc53d830
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
lidi100/omniscidb
3ea2f6b64e6baf603ac1f7d06161f1bdf396c9df
f4f962edca97885843a6d55b19949d17966b551b
refs/heads/master
2023-06-14T15:45:25.177860
2021-07-06T04:56:24
2021-07-06T20:05:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,813
hpp
/* This file contains tesing compile-time UDTFs. The unit-tests are implemented within the RBC package. */ #define CPU_DEVICE_CODE 0x637075; // 'cpu' in hex #define GPU_DEVICE_CODE 0x677075; // 'gpu' in hex // clang-format off /* UDTF: ct_device_selection_udtf_any(Cursor<int32_t>, Constant<1>) -> Column<int32_t> UDTF: ct_device_selection_udtf_cpu__cpu_(Cursor<int32_t>, Constant<1>) -> Column<int32_t> UDTF: ct_device_selection_udtf_gpu__gpu_(Cursor<int32_t>, Constant<1>) -> Column<int32_t> UDTF: ct_device_selection_udtf_both__cpu_(Cursor<int32_t>, Constant<1>) -> Column<int32_t> UDTF: ct_device_selection_udtf_both__gpu_(Cursor<int32_t>, Constant<1>) -> Column<int32_t> */ // clang-format on EXTENSION_NOINLINE int32_t ct_device_selection_udtf_any(const Column<int32_t>& input, Column<int64_t>& out) { #ifdef __CUDACC__ out[0] = GPU_DEVICE_CODE; #else out[0] = CPU_DEVICE_CODE; #endif return 1; } EXTENSION_NOINLINE int32_t ct_device_selection_udtf_cpu__cpu_(const Column<int32_t>& input, Column<int64_t>& out) { out[0] = CPU_DEVICE_CODE; return 1; } EXTENSION_NOINLINE int32_t ct_device_selection_udtf_gpu__gpu_(const Column<int32_t>& input, Column<int64_t>& out) { out[0] = GPU_DEVICE_CODE; return 1; } EXTENSION_NOINLINE int32_t ct_device_selection_udtf_both__cpu_(const Column<int32_t>& input, Column<int64_t>& out) { out[0] = CPU_DEVICE_CODE; return 1; } EXTENSION_NOINLINE int32_t ct_device_selection_udtf_both__gpu_(const Column<int32_t>& input, Column<int64_t>& out) { out[0] = GPU_DEVICE_CODE; return 1; } #undef CPU_DEVICE_CODE #undef GPU_DEVICE_CODE // clang-format off /* Test functions for constant sizer parameter: UDTF: ct_binding_udtf_constant__cpu_1(Cursor<int32_t>, Constant<1>) -> Column<int32_t> UDTF: ct_binding_udtf_constant__cpu_2(Cursor<int32_t, int32_t>, Constant<1>) -> Column<int32_t> UDTF: ct_binding_udtf_constant__cpu_3(Cursor<int32_t, int32_t, int32_t>, Constant<1>) -> Column<int32_t> UDTF: ct_binding_udtf_constant__cpu_4(Cursor<int64_t, int32_t, int32_t>, Constant<1>) -> Column<int32_t> UDTF: ct_binding_udtf_constant__cpu_5(Cursor<int64_t, int64_t, int32_t>, Constant<1>) -> Column<int32_t> UDTF: ct_binding_udtf_constant__cpu_6(Cursor<int64_t, int32_t, int64_t>, Constant<1>) -> Column<int32_t> UDTF: ct_binding_udtf_constant__cpu_7(Cursor<int32_t, ColumnList<int32_t>>, Constant<1>) -> Column<int32_t> UDTF: ct_binding_udtf_constant__cpu_8(Cursor<ColumnList<int32_t>, int64_t>, Constant<1>) -> Column<int32_t> UDTF: ct_binding_udtf_constant__cpu_9(Cursor<ColumnList<int32_t>, ColumnList<int64_t>>, Constant<1>) -> Column<int32_t> UDTF: ct_binding_udtf_constant__cpu_10(Cursor<int64_t, ColumnList<int64_t>, int64_t>, Constant<1>) -> Column<int32_t> Test functions for row multiplier sizer parameter: UDTF: ct_binding_udtf__cpu_11(Cursor<int32_t>, RowMultiplier) -> Column<int32_t> UDTF: ct_binding_udtf__cpu_12(Cursor<int32_t, int32_t>, RowMultiplier) -> Column<int32_t> UDTF: ct_binding_udtf__cpu_13(Cursor<int32_t, int32_t, int32_t>, RowMultiplier) -> Column<int32_t> UDTF: ct_binding_udtf__cpu_14(Cursor<int64_t, int32_t, int32_t>, RowMultiplier) -> Column<int32_t> UDTF: ct_binding_udtf__cpu_15(Cursor<int64_t, int64_t, int32_t>, RowMultiplier) -> Column<int32_t> UDTF: ct_binding_udtf__cpu_16(Cursor<int64_t, int32_t, int64_t>, RowMultiplier) -> Column<int32_t> UDTF: ct_binding_udtf__cpu_17(Cursor<int32_t, ColumnList<int32_t>>, RowMultiplier) -> Column<int32_t> UDTF: ct_binding_udtf__cpu_18(Cursor<ColumnList<int32_t>, int64_t>, RowMultiplier) -> Column<int32_t> UDTF: ct_binding_udtf__cpu_19(Cursor<ColumnList<int32_t>, ColumnList<int64_t>>, RowMultiplier) -> Column<int32_t> UDTF: ct_binding_udtf__cpu_20(Cursor<int64_t, ColumnList<int64_t>, int64_t>, RowMultiplier) -> Column<int32_t> UDTF: ct_binding_udtf2__cpu_21(RowMultiplier, Cursor<int32_t>) -> Column<int32_t> UDTF: ct_binding_udtf6__cpu_22(Cursor<int32_t>, RowMultiplier, int32_t) -> Column<int32_t> UDTF: ct_binding_udtf4__cpu_23(Cursor<ColumnList<int32_t>>, RowMultiplier, int32_t) -> Column<int32_t> UDTF: ct_binding_udtf5__cpu_24(Cursor<ColumnList<int32_t>>, int32_t, RowMultiplier) -> Column<int32_t> UDTF: ct_binding_udtf3__cpu_25(Cursor<Column<int32_t>>, int32_t, RowMultiplier) -> Column<int32_t> */ // clang-format on EXTENSION_NOINLINE int32_t ct_binding_udtf_constant__cpu_1(const Column<int32_t>& input1, Column<int32_t>& out) { out[0] = 1; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf_constant__cpu_2(const Column<int32_t>& input1, const Column<int32_t>& input2, Column<int32_t>& out) { out[0] = 11; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf_constant__cpu_3(const Column<int32_t>& input1, const Column<int32_t>& input2, const Column<int32_t>& input3, Column<int32_t>& out) { out[0] = 111; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf_constant__cpu_4(const Column<int64_t>& input1, const Column<int32_t>& input2, const Column<int32_t>& input3, Column<int32_t>& out) { out[0] = 211; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf_constant__cpu_5(const Column<int64_t>& input1, const Column<int64_t>& input2, const Column<int32_t>& input3, Column<int32_t>& out) { out[0] = 221; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf_constant__cpu_6(const Column<int64_t>& input1, const Column<int32_t>& input2, const Column<int64_t>& input3, Column<int32_t>& out) { out[0] = 212; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf_constant__cpu_7(const Column<int32_t>& input1, const ColumnList<int32_t>& input2, Column<int32_t>& out) { out[0] = 13; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf_constant__cpu_8(const ColumnList<int32_t>& input1, const Column<int64_t>& input2, Column<int32_t>& out) { out[0] = 32; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf_constant__cpu_9(const ColumnList<int32_t>& input1, const ColumnList<int64_t>& input2, Column<int32_t>& out) { out[0] = 34; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf_constant__cpu_10(const Column<int64_t>& input1, const ColumnList<int64_t>& input2, const Column<int64_t>& input3, Column<int64_t>& out) { out[0] = 242; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf__cpu_11(const Column<int32_t>& input1, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 19 + multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf__cpu_12(const Column<int32_t>& input1, const Column<int32_t>& input2, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 119 + multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf__cpu_13(const Column<int32_t>& input1, const Column<int32_t>& input2, const Column<int32_t>& input3, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 1119 + multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf__cpu_14(const Column<int64_t>& input1, const Column<int32_t>& input2, const Column<int32_t>& input3, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 2119 + multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf__cpu_15(const Column<int64_t>& input1, const Column<int64_t>& input2, const Column<int32_t>& input3, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 2219 + multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf__cpu_16(const Column<int64_t>& input1, const Column<int32_t>& input2, const Column<int64_t>& input3, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 2129 + multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf__cpu_17(const Column<int32_t>& input1, const ColumnList<int32_t>& input2, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 139 + multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf__cpu_18(const ColumnList<int32_t>& input1, const Column<int64_t>& input2, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 329 + multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf__cpu_19(const ColumnList<int32_t>& input1, const ColumnList<int64_t>& input2, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 349 + multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf__cpu_20(const Column<int64_t>& input1, const ColumnList<int64_t>& input2, const Column<int64_t>& input3, const int32_t multiplier, Column<int64_t>& out) { out[0] = 1000 + 2429 + multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf2__cpu_21(const int32_t multiplier, const Column<int32_t>& input1, Column<int32_t>& out) { out[0] = 1000 + 91 + multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf6__cpu_22(const Column<int32_t>& input1, const int32_t multiplier, const int32_t input2, Column<int32_t>& out) { out[0] = 1000 + 196 + multiplier + 10 * input2; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf4__cpu_23(const ColumnList<int32_t>& input1, const int32_t multiplier, const int32_t input2, Column<int32_t>& out) { out[0] = 1000 + 396 + multiplier + 10 * input2; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf5__cpu_24(const ColumnList<int32_t>& input1, const int32_t input2, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 369 + multiplier + 10 * input2; return 1; } EXTENSION_NOINLINE int32_t ct_binding_udtf3__cpu_25(const Column<int32_t>& input1, const int32_t input2, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 169 + multiplier + 10 * input2; return 1; } /* Test functions for default sizer parameter: */ // clang-format off /* UDTF: ct_udtf_default_sizer1a__cpu_1(Cursor<int32_t>, RowMultiplier) -> Column<int32_t> UDTF: ct_udtf_default_sizer1b__cpu_2(Cursor<int32_t>, Cursor<int32_t>, RowMultiplier) -> Column<int32_t> UDTF: ct_udtf_default_sizer1c__cpu_3(Cursor<int32_t, int32_t, int32_t>, RowMultiplier, Cursor<int32_t>, int32_t) -> Column<int32_t> UDTF: ct_udtf_default_sizer1d__cpu_4(RowMultiplier, int32_t, Cursor<int32_t>) -> Column<int32_t> UDTF: ct_udtf_default_sizer2a__cpu_1(Cursor<int32_t>, int32_t, RowMultiplier) -> Column<int32_t> UDTF: ct_udtf_default_sizer2b__cpu_2(Cursor<int32_t>, RowMultiplier, Cursor<int32_t>) -> Column<int32_t> UDTF: ct_udtf_default_sizer2c__cpu_3(int32_t, RowMultiplier, Cursor<int32_t>) -> Column<int32_t> UDTF: ct_udtf_default_sizer3a__cpu_1(Cursor<int32_t>, RowMultiplier, int32_t) -> Column<int32_t> UDTF: ct_udtf_default_sizer3b__cpu_2(Cursor<int32_t>, int32_t, Cursor<int32_t>, RowMultiplier) -> Column<int32_t> UDTF: ct_udtf_default_sizer4a__cpu_1(Cursor<int32_t>, RowMultiplier, Cursor<int32_t>, int32_t) -> Column<int32_t> UDTF: ct_udtf_default_sizer4b__cpu_2(RowMultiplier, Cursor<int32_t>, int32_t) -> Column<int32_t> */ // clang-format on EXTENSION_NOINLINE int32_t ct_udtf_default_sizer1a__cpu_1(const Column<int32_t>& input1, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 1 + 10 * multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_udtf_default_sizer1b__cpu_2(const Column<int32_t>& input1, const Column<int32_t>& input2, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 2 + 11 * multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_udtf_default_sizer1c__cpu_3(const Column<int32_t>& input1, const Column<int32_t>& input2, const Column<int32_t>& input3, const int32_t multiplier, const Column<int32_t>& input4, const int32_t x, Column<int32_t>& out) { out[0] = 1000 + 101 + 10 * multiplier + x; return 1; } EXTENSION_NOINLINE int32_t ct_udtf_default_sizer1d__cpu_4(const int32_t multiplier, const int32_t x, const Column<int32_t>& input1, Column<int32_t>& out) { out[0] = 1000 + 99 + 10 * multiplier + x; return 1; } EXTENSION_NOINLINE int32_t ct_udtf_default_sizer2a__cpu_1(const Column<int32_t>& input1, const int32_t x, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 98 + multiplier + 10 * x; return 1; } EXTENSION_NOINLINE int32_t ct_udtf_default_sizer2b__cpu_2(const Column<int32_t>& input1, const int32_t multiplier, const Column<int32_t>& input2, Column<int32_t>& out) { out[0] = 1000 + 2 + multiplier; return 1; } EXTENSION_NOINLINE int32_t ct_udtf_default_sizer2c__cpu_3(const int32_t x, const int32_t multiplier, const Column<int32_t>& input1, Column<int32_t>& out) { out[0] = 1000 + 99 + multiplier + 11 * x; return 1; } EXTENSION_NOINLINE int32_t ct_udtf_default_sizer3a__cpu_1(const Column<int32_t>& input1, const int32_t multiplier, const int32_t x, Column<int32_t>& out) { out[0] = 1000 + 98 + 100 * multiplier + x; return 1; } EXTENSION_NOINLINE int32_t ct_udtf_default_sizer3b__cpu_2(const Column<int32_t>& input1, const int32_t x, const Column<int32_t>& input2, const int32_t multiplier, Column<int32_t>& out) { out[0] = 1000 + 99 + 100 * multiplier + x; return 1; } EXTENSION_NOINLINE int32_t ct_udtf_default_sizer4a__cpu_1(const Column<int32_t>& input1, const int32_t multiplier, const Column<int32_t>& input2, const int32_t x, Column<int32_t>& out) { out[0] = 1000 + 99 + 10 * multiplier + x; return 1; } EXTENSION_NOINLINE int32_t ct_udtf_default_sizer4b__cpu_2(const int32_t multiplier, const Column<int32_t>& input, const int32_t x, Column<int32_t>& out) { out[0] = 1000 + 99 + 9 * multiplier + x; return 1; } // clang-format off /* UDTF: ct_binding_dict_encoded1__cpu_1(Cursor<TextEncodingDict>, RowMultiplier) -> Column<TextEncodingDict> */ // clang-format on EXTENSION_NOINLINE int32_t ct_binding_dict_encoded1__cpu_1(const Column<TextEncodingDict>& input, const int32_t multiplier, Column<TextEncodingDict>& out) { for (int64_t i = 0; i < input.size(); i++) { out[i] = input[i]; // assign string id } return multiplier * input.size(); }
[ "dev@aas.io" ]
dev@aas.io
3f994965eee03a55345103332738b0dc70fdc902
4c045ae92728a84bbedf5b3497ce810a28bb212a
/src/patternfactory.cpp
5a25467cf2f0355bc76316028183aa1c70da22a4
[]
no_license
tathitungly/pattern_call_assignment
7ef7727fadb98d9fb540c35232e1f208cc6f955c
3ce6ed9cc912ab5cc0efed0cfdbc201f355a71b7
refs/heads/master
2020-05-18T13:04:18.869883
2017-03-12T13:57:29
2017-03-12T13:57:29
84,240,143
0
0
null
null
null
null
UTF-8
C++
false
false
1,338
cpp
#include "patternfactory.h" #include <sstream> #include <iostream> #include <vector> #include <cstdlib> PatternFactory::PatternFactory() { // Do nothing } Pattern* PatternFactory::stringToPattern(const std::string str) { // Parse input string to vector std::vector<std::string> stringVector; std::istringstream strStream(str); std::string temp; while (std::getline(strStream, temp, ';')) { stringVector.push_back(temp); } // Validate input string int numOfParams = stringVector.size(); if (numOfParams < 4) { std::cout << "ERROR: lack of parameter to create a pattern."; } else { if (numOfParams > 4) { std::cout << "WARN: redundant parameter will be ignored." << std::endl; } Pattern *result = new Pattern(); result->setId(std::atoi(stringVector[0].c_str())); std::cout << "Reading ID: " << result->getId() << std::endl; result->setName(stringVector[1]); std::cout << "Reading Name: " << result->getName() << std::endl; result->setPath(stringVector[2]); std::cout << "Reading Path: " << result->getPath() << std::endl; result->setFlag(stringVector[3] != "0"); std::cout << "Reading Flag: " << result->getFlag() << std::endl; return result; } return NULL; }
[ "ly.ta@outlook.com" ]
ly.ta@outlook.com
005bfaad5156fd838dd4e3e119c762594debd060
2480ceee9f28f5e8a69fb6f5ed42fd63c22b4205
/include/Pomdog/Experimental/GUI/HorizontalAlignment.hpp
a46148f8b27138e1466f6ba74b85ca05f86a8dd8
[ "MIT" ]
permissive
rokrepo/pomdog
165db7884598c74bd530a4b7a1e83bc1e315c945
b21fd4fef295aaa3e06ca15e5952109cd8e93f00
refs/heads/master
2022-10-25T04:09:09.721827
2020-06-18T05:33:25
2020-06-18T05:33:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
259
hpp
// Copyright (c) 2013-2020 mogemimi. Distributed under the MIT license. #pragma once #include <cstdint> namespace Pomdog::GUI { enum class HorizontalAlignment : std::uint8_t { Left, //Center, Stretch, Right, }; } // namespace Pomdog::GUI
[ "mogemimi@enginetrouble.net" ]
mogemimi@enginetrouble.net
5d963f222896a471cfc52918887615fd0260eb41
ebbfa162f63661c6d89bc99053248d60f6100e3c
/src/Module/Utils/MyModule.h
8f482da6522d7f5b4075c7e575ca54e3c6c21026
[]
no_license
leafletC/DeviceMonitor
02da60fb8fbc50cbbb73b4aead3f46700ed02600
f0b8f4ea8469c8fd3051cfc94cb9c2ab6cd9b32c
refs/heads/master
2023-01-23T06:18:30.709470
2020-12-04T03:53:53
2020-12-04T03:53:53
318,396,619
0
0
null
null
null
null
UTF-8
C++
false
false
413
h
#pragma once #include <map> #include <stdint.h> #include <functional> using namespace std; class MyModule { public: MyModule(); using Fn = function<void *(void *)>; void connect(uint32_t msgId, Fn fn); void disconnect(uint32_t msgId); void *emit(uint32_t msgId, void *arg); private: static uint32_t allocModuleId(); map<uint32_t, Fn> messageMap; const uint32_t moduleId; };
[ "yeyusong@localhost.localdomain" ]
yeyusong@localhost.localdomain
4d179c77fe8cda7df909369d95dd555d41c30811
5844ccf99a19d83d3da7f44ec30b3cc5c2d008fe
/part1/string_array.cpp
df70e39ccca75eeee88a8eea3b52c1e508295eb9
[ "MIT" ]
permissive
isoleph/cpp_crash
ead78b3c83296b3435a0538fc2af1ebd9e9d69c2
625ead4f394a73925b23f348736aa155fa9d2d5f
refs/heads/master
2020-06-10T10:37:12.971704
2019-09-29T22:03:55
2019-09-29T22:03:55
193,635,607
0
0
null
null
null
null
UTF-8
C++
false
false
245
cpp
#include <iostream> #include <array> using namespace std; // print all contents of a string array int main () { string v[2] = {"yes","no"}; for (int i = 0; i < std::size(v) ; i++) { cout << v[i] << endl; } return 0; }
[ "valdenegro.angel@gmail.com" ]
valdenegro.angel@gmail.com
a880026bf89465f75dc8c4973361211345f010f0
51635684d03e47ebad12b8872ff469b83f36aa52
/external/gcc-12.1.0/libstdc++-v3/testsuite/25_algorithms/generate_n/87982.cc
33a2c82cf99a61a8d72788d30218b88dd3bccff4
[ "LGPL-2.1-only", "GPL-3.0-only", "GCC-exception-3.1", "GPL-2.0-only", "LGPL-3.0-only", "LGPL-2.0-or-later", "Zlib", "LicenseRef-scancode-public-domain" ]
permissive
zhmu/ananas
8fb48ddfe3582f85ff39184fc7a3c58725fe731a
30850c1639f03bccbfb2f2b03361792cc8fae52e
refs/heads/master
2022-06-25T10:44:46.256604
2022-06-12T17:04:40
2022-06-12T17:04:40
30,108,381
59
8
Zlib
2021-09-26T17:30:30
2015-01-31T09:44:33
C
UTF-8
C++
false
false
2,074
cc
// Copyright (C) 2019-2022 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, 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 General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-do run } #include <algorithm> #include <testsuite_hooks.h> int a[4] = { 0, 1, 2, 3 }; int g; int gen() { return g; } enum E { e2 = 2 }; struct Num { char val; operator char() const { return val; } private: void operator+() const; void operator+(int) const; void operator+(Num) const; void operator<(int) const; void operator>(int) const; void operator<=(int) const; void operator>=(int) const; void operator==(int) const; void operator!=(int) const; }; void test01() { int* p; g = -1; p = std::generate_n(a, true, &gen); // bool as Size VERIFY( p == a+1 ); VERIFY( a[0] == g ); VERIFY( a[1] == 1 ); VERIFY( a[2] == 2 ); VERIFY( a[3] == 3 ); g = -2; p = std::generate_n(a, e2, &gen); // enumeration type as Size VERIFY( p == a+2 ); VERIFY( a[0] == g ); VERIFY( a[1] == g ); VERIFY( a[2] == 2 ); VERIFY( a[3] == 3 ); g = -3; p = std::generate_n(a, 3.5, &gen); // floating point type as Size VERIFY( p == a+3 ); VERIFY( a[0] == g ); VERIFY( a[1] == g ); VERIFY( a[2] == g ); VERIFY( a[3] == 3 ); g = -4; Num n = { 3 }; p = std::generate_n(a, n, &gen); // non-scalar type as Size VERIFY( p == a+3 ); VERIFY( a[0] == g ); VERIFY( a[1] == g ); VERIFY( a[2] == g ); VERIFY( a[3] == 3 ); } int main() { test01(); }
[ "rink@rink.nu" ]
rink@rink.nu
256a2956be2e9c8ef770208ce39ed96d0f05b71d
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14649/function14649_schedule_20/function14649_schedule_20.cpp
bec4c5dbca97b3b99ec6d3d3c8a2c64356f20289
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
1,881
cpp
#include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv){ tiramisu::init("function14649_schedule_20"); constant c0("c0", 128), c1("c1", 64), c2("c2", 64), c3("c3", 64); var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i3("i3", 0, c3), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06"); input input00("input00", {i0}, p_int32); input input01("input01", {i2, i3}, p_int32); input input02("input02", {i3}, p_int32); input input03("input03", {i0, i1, i2}, p_int32); input input04("input04", {i2, i3}, p_int32); input input05("input05", {i1, i2, i3}, p_int32); input input06("input06", {i0, i1}, p_int32); computation comp0("comp0", {i0, i1, i2, i3}, input00(i0) * input01(i2, i3) + input02(i3) - input03(i0, i1, i2) * input04(i2, i3) * input05(i1, i2, i3) + input06(i0, i1)); comp0.tile(i0, i1, i2, 32, 64, 64, i01, i02, i03, i04, i05, i06); comp0.parallelize(i01); buffer buf00("buf00", {128}, p_int32, a_input); buffer buf01("buf01", {64, 64}, p_int32, a_input); buffer buf02("buf02", {64}, p_int32, a_input); buffer buf03("buf03", {128, 64, 64}, p_int32, a_input); buffer buf04("buf04", {64, 64}, p_int32, a_input); buffer buf05("buf05", {64, 64, 64}, p_int32, a_input); buffer buf06("buf06", {128, 64}, p_int32, a_input); buffer buf0("buf0", {128, 64, 64, 64}, p_int32, a_output); input00.store_in(&buf00); input01.store_in(&buf01); input02.store_in(&buf02); input03.store_in(&buf03); input04.store_in(&buf04); input05.store_in(&buf05); input06.store_in(&buf06); comp0.store_in(&buf0); tiramisu::codegen({&buf00, &buf01, &buf02, &buf03, &buf04, &buf05, &buf06, &buf0}, "../data/programs/function14649/function14649_schedule_20/function14649_schedule_20.o"); return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
fe351d9fd20d6fecbe60a859d002fc24a06b5989
925af441a33f4b67c1484e486d62db138e6c9024
/leetcode/搜索/面试题 04.04. 检查平衡性/solution.cpp
d316f8ce9ce1051fb8a64154b044fcf9736d1551
[]
no_license
HanpyBin/CP-Note
2f1b4f9a5c3dad58396ce21c45c09bac786cea02
40e65572550f836c3dc5f764ea58c0ddf30bbfd4
refs/heads/main
2023-08-11T05:24:17.947751
2021-10-02T13:44:26
2021-10-02T13:44:26
378,935,630
0
0
null
null
null
null
UTF-8
C++
false
false
574
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int f(TreeNode* root) { if (!root) return 0; int l = f(root->left); int r = f(root->right); return l == -1 || r == -1 || abs(r-l) > 1 ? -1 : 1+max(l, r); } bool isBalanced(TreeNode* root) { if (f(root) != -1) return true; else return false; } };
[ "975189452@qq.com" ]
975189452@qq.com
d93a5a74610cb34eb6ad3e6b55ed30e64fbd2144
7d618c23a8855e3ed7b8f410517ffff54dd1df7a
/rawhide_ws/devel/include/intera_motion_msgs/MotionCommandGoal.h
8dbf06de25ac3d8969e67c98a0cfb5fe494ab77a
[]
no_license
rachelmh/rawhide
25b854cdc595b115dbc69e89ee33978a39e30df7
0efe318ef16d4975f75f19b6d2358105c905040e
refs/heads/master
2020-04-27T19:21:58.203708
2019-07-24T15:24:36
2019-07-24T15:24:36
174,612,822
0
0
null
null
null
null
UTF-8
C++
false
false
17,464
h
// Generated by gencpp from file intera_motion_msgs/MotionCommandGoal.msg // DO NOT EDIT! #ifndef INTERA_MOTION_MSGS_MESSAGE_MOTIONCOMMANDGOAL_H #define INTERA_MOTION_MSGS_MESSAGE_MOTIONCOMMANDGOAL_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <intera_motion_msgs/Trajectory.h> namespace intera_motion_msgs { template <class ContainerAllocator> struct MotionCommandGoal_ { typedef MotionCommandGoal_<ContainerAllocator> Type; MotionCommandGoal_() : command() , trajectory() { } MotionCommandGoal_(const ContainerAllocator& _alloc) : command(_alloc) , trajectory(_alloc) { (void)_alloc; } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _command_type; _command_type command; typedef ::intera_motion_msgs::Trajectory_<ContainerAllocator> _trajectory_type; _trajectory_type trajectory; static const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > MOTION_START; static const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > MOTION_STOP; static const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > MOTION_GENERATE; typedef boost::shared_ptr< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> const> ConstPtr; }; // struct MotionCommandGoal_ typedef ::intera_motion_msgs::MotionCommandGoal_<std::allocator<void> > MotionCommandGoal; typedef boost::shared_ptr< ::intera_motion_msgs::MotionCommandGoal > MotionCommandGoalPtr; typedef boost::shared_ptr< ::intera_motion_msgs::MotionCommandGoal const> MotionCommandGoalConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > MotionCommandGoal_<ContainerAllocator>::MOTION_START = "start" ; template<typename ContainerAllocator> const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > MotionCommandGoal_<ContainerAllocator>::MOTION_STOP = "stop" ; template<typename ContainerAllocator> const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > MotionCommandGoal_<ContainerAllocator>::MOTION_GENERATE = "generate # Generate path, but do not run" ; template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> & v) { ros::message_operations::Printer< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace intera_motion_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'intera_core_msgs': ['/home/rachel/rawhide/rawhide_ws/src/intera_common/intera_core_msgs/msg', '/home/rachel/rawhide/rawhide_ws/devel/share/intera_core_msgs/msg'], 'sensor_msgs': ['/opt/ros/melodic/share/sensor_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/melodic/share/actionlib_msgs/cmake/../msg'], 'intera_motion_msgs': ['/home/rachel/rawhide/rawhide_ws/src/intera_common/intera_motion_msgs/msg', '/home/rachel/rawhide/rawhide_ws/devel/share/intera_motion_msgs/msg'], 'std_msgs': ['/opt/ros/melodic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/melodic/share/geometry_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> > { static const char* value() { return "0b2003b52edbd59dd10da219c3a7fdb0"; } static const char* value(const ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x0b2003b52edbd59dULL; static const uint64_t static_value2 = 0xd10da219c3a7fdb0ULL; }; template<class ContainerAllocator> struct DataType< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> > { static const char* value() { return "intera_motion_msgs/MotionCommandGoal"; } static const char* value(const ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> > { static const char* value() { return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n" "# Engine command goal\n" "string command\n" "string MOTION_START=start\n" "string MOTION_STOP=stop\n" "string MOTION_GENERATE=generate # Generate path, but do not run\n" "\n" "Trajectory trajectory\n" "\n" "\n" "================================================================================\n" "MSG: intera_motion_msgs/Trajectory\n" "# Representation of a trajectory used by the engine and motion controller.\n" "\n" "# optional label\n" "string label\n" "\n" "# Array of joint names that correspond to the waypoint joint_positions\n" "string[] joint_names\n" "\n" "# Array of waypoints that comprise the trajectory\n" "Waypoint[] waypoints\n" "\n" "# Trajectory level options\n" "TrajectoryOptions trajectory_options\n" "================================================================================\n" "MSG: intera_motion_msgs/Waypoint\n" "# Representation of a waypoint used by the motion controller\n" "\n" "# Desired joint positions\n" "# For Cartesian segments, the joint positions are used as nullspace biases\n" "float64[] joint_positions\n" "\n" "# Name of the endpoint that is currently active\n" "string active_endpoint\n" "\n" "# Cartesian pose\n" "# This is not used in trajectories using joint interpolation\n" "geometry_msgs/PoseStamped pose\n" "\n" "# Waypoint specific options\n" "# Default values will be used if not set\n" "# All waypoint options are applied to the segment moving to that waypoint\n" "WaypointOptions options\n" "\n" "================================================================================\n" "MSG: geometry_msgs/PoseStamped\n" "# A Pose with reference coordinate frame and timestamp\n" "Header header\n" "Pose pose\n" "\n" "================================================================================\n" "MSG: std_msgs/Header\n" "# Standard metadata for higher-level stamped data types.\n" "# This is generally used to communicate timestamped data \n" "# in a particular coordinate frame.\n" "# \n" "# sequence ID: consecutively increasing ID \n" "uint32 seq\n" "#Two-integer timestamp that is expressed as:\n" "# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n" "# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n" "# time-handling sugar is provided by the client library\n" "time stamp\n" "#Frame this data is associated with\n" "string frame_id\n" "\n" "================================================================================\n" "MSG: geometry_msgs/Pose\n" "# A representation of pose in free space, composed of position and orientation. \n" "Point position\n" "Quaternion orientation\n" "\n" "================================================================================\n" "MSG: geometry_msgs/Point\n" "# This contains the position of a point in free space\n" "float64 x\n" "float64 y\n" "float64 z\n" "\n" "================================================================================\n" "MSG: geometry_msgs/Quaternion\n" "# This represents an orientation in free space in quaternion form.\n" "\n" "float64 x\n" "float64 y\n" "float64 z\n" "float64 w\n" "\n" "================================================================================\n" "MSG: intera_motion_msgs/WaypointOptions\n" "# Optional waypoint label\n" "string label\n" "\n" "# Ratio of max allowed joint speed : max planned joint speed (from 0.0 to 1.0)\n" "float64 max_joint_speed_ratio\n" "\n" "# Slowdown heuristic is triggered if tracking error exceeds tolerances - radians\n" "float64[] joint_tolerances\n" "\n" "# Maximum accelerations for each joint (only for joint paths) - rad/s^2.\n" "float64[] max_joint_accel\n" "\n" "\n" "###########################################################\n" "# The remaining parameters only apply to Cartesian paths\n" "\n" "# Maximum linear speed of endpoint - m/s\n" "float64 max_linear_speed\n" "\n" "# Maximum linear acceleration of endpoint - m/s^2\n" "float64 max_linear_accel\n" "\n" "# Maximum rotational speed of endpoint - rad/s\n" "float64 max_rotational_speed\n" "\n" "# Maximum rotational acceleration of endpoint - rad/s^2\n" "float64 max_rotational_accel\n" "\n" "# Used for smoothing corners for continuous motion - m\n" "# The distance from the waypoint to where the curve starts while blending from\n" "# one straight line segment to the next.\n" "# Larger distance: trajectory passes farther from the waypoint at a higher speed\n" "# Smaller distance: trajectory passes closer to the waypoint at a lower speed\n" "# Zero distance: trajectory passes through the waypoint at zero speed\n" "float64 corner_distance\n" "\n" "================================================================================\n" "MSG: intera_motion_msgs/TrajectoryOptions\n" "# Trajectory interpolation type\n" "string CARTESIAN=CARTESIAN\n" "string JOINT=JOINT\n" "string interpolation_type\n" "\n" "# True if the trajectory uses interaction control, false for position control.\n" "bool interaction_control\n" "\n" "# Interaction control parameters\n" "intera_core_msgs/InteractionControlCommand interaction_params\n" "\n" "# Allow small joint adjustments at the beginning of Cartesian trajectories.\n" "# Set to false for 'small' motions.\n" "bool nso_start_offset_allowed\n" "\n" "# Check the offset at the end of a Cartesian trajectory from the final waypoint nullspace goal.\n" "bool nso_check_end_offset\n" "\n" "# Options for the tracking controller:\n" "TrackingOptions tracking_options\n" "\n" "# Desired trajectory end time, ROS timestamp\n" "time end_time\n" "\n" "# The rate in seconds that the path is interpolated and returned back to the user\n" "# No interpolation will happen if set to zero\n" "float64 path_interpolation_step\n" "\n" "================================================================================\n" "MSG: intera_core_msgs/InteractionControlCommand\n" "# Message sets the interaction (impedance/force) control on or off\n" "# It also contains desired cartesian stiffness K, damping D, and force values\n" "\n" "Header header\n" "bool interaction_control_active\n" "\n" "## Cartesian Impedance Control Parameters\n" "# Stiffness units are (N/m) for first 3 and (Nm/rad) for second 3 values\n" "float64[] K_impedance\n" "# Force certain directions to have maximum possible impedance for a given pose\n" "bool[] max_impedance\n" "# Damping units are (Ns/m) for first 3 and (Nms/rad) for the second 3 values\n" "float64[] D_impedance\n" "# Joint Nullspace stiffness units are in (Nm/rad) (length == number of joints)\n" "float64[] K_nullspace\n" "\n" "## Parameters for force control or impedance control with force limit\n" "# If in force mode, this is the vector of desired forces/torques\n" "# to be regulated in (N) and (Nm)\n" "# If in impedance with force limit mode, this vector specifies the\n" "# magnitude of forces/torques (N and Nm) that the command will not exceed.\n" "float64[] force_command\n" "\n" "## Desired frame\n" "geometry_msgs/Pose interaction_frame\n" "string endpoint_name\n" "# True if impedance and force commands are defined in endpoint frame\n" "bool in_endpoint_frame\n" "\n" "# Set to true to disable damping during force control. Damping is used\n" "# to slow down robot motion during force control in free space.\n" "# Option included for SDK users to disable damping in force control\n" "bool disable_damping_in_force_control\n" "\n" "# Set to true to disable reference resetting. Reference resetting is\n" "# used when interaction parameters change, in order to avoid jumps/jerks.\n" "# Option included for SDK users to disable reference resetting if the\n" "# intention is to change interaction parameters.\n" "bool disable_reference_resetting\n" "\n" "## Mode Selection Parameters\n" "# The possible interaction control modes are:\n" "# Impedance mode: implements desired endpoint stiffness and damping.\n" "uint8 IMPEDANCE_MODE=1\n" "# Force mode: applies force/torque in the specified dimensions.\n" "uint8 FORCE_MODE=2\n" "# Impedance with force limit: impedance control while ensuring the commanded\n" "# forces/torques do not exceed force_command.\n" "uint8 IMPEDANCE_WITH_FORCE_LIMIT_MODE=3\n" "# Force with motion bounds: force control while ensuring the current\n" "# pose/velocities do not exceed forceMotionThreshold (currenetly defined in yaml)\n" "uint8 FORCE_WITH_MOTION_LIMIT_MODE=4\n" "\n" "# Specifies the interaction control mode for each Cartesian dimension (6)\n" "uint8[] interaction_control_mode\n" "\n" "# All 6 values in force and impedance parameter vectors have to be filled,\n" "# If a control mode is not used in a Cartesian dimension,\n" "# the corresponding parameters will be ignored.\n" "\n" "## Parameters for Constrained Zero-G Behaviors\n" "# Allow for arbitrary rotational displacements from the current orientation\n" "# for constrained zero-G. Setting 'rotations_for_constrained_zeroG = True'\n" "# will disable the rotational stiffness field which limits rotational\n" "# displacements to +/- 82.5 degree.\n" "# NOTE: it will be only enabled for a stationary reference orientation\n" "bool rotations_for_constrained_zeroG\n" "\n" "================================================================================\n" "MSG: intera_motion_msgs/TrackingOptions\n" "# Minimum trajectory tracking time rate: (default = less than one)\n" "bool use_min_time_rate\n" "float64 min_time_rate\n" "\n" "# Maximum trajectory tracking time rate: (1.0 = real-time = default)\n" "bool use_max_time_rate\n" "float64 max_time_rate\n" "\n" "# Angular error tolerance at final point on trajectory (rad)\n" "float64[] goal_joint_tolerance\n" "\n" "# Time for the controller to settle within joint tolerances at the goal (sec)\n" "bool use_settling_time_at_goal\n" "float64 settling_time_at_goal\n" ; } static const char* value(const ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.command); stream.next(m.trajectory); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct MotionCommandGoal_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::intera_motion_msgs::MotionCommandGoal_<ContainerAllocator>& v) { s << indent << "command: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.command); s << indent << "trajectory: "; s << std::endl; Printer< ::intera_motion_msgs::Trajectory_<ContainerAllocator> >::stream(s, indent + " ", v.trajectory); } }; } // namespace message_operations } // namespace ros #endif // INTERA_MOTION_MSGS_MESSAGE_MOTIONCOMMANDGOAL_H
[ "rachelmh@mit.edu" ]
rachelmh@mit.edu
94b8be357bea74b9ba1d8034654aa08232abed6a
c91601bc25d1aeacde85f540765cc01c185f6a75
/.scripts/node_modules/nodegit/src/object.cc
be1895226ae20e4784469285a88fa9c5c815fe95
[ "MIT" ]
permissive
imjorge/dotfiles-1
4cff4f7618302019fd41ef6231b711265f48d52f
bb231a2b4ac5fa4eac2955210f115551c02d7943
refs/heads/master
2021-01-16T21:56:22.599455
2015-05-16T21:37:18
2015-05-16T21:37:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,047
cc
/** * This code is auto-generated; unless you know what you're doing, do not modify! **/ #include <v8.h> #include <node.h> #include <string.h> #include "git2.h" #include "../include/functions/copy.h" #include "../include/object.h" #include "../include/oid.h" #include "../include/repo.h" using namespace v8; using namespace node; GitObject::GitObject(git_object *raw) { this->raw = raw; } GitObject::~GitObject() { git_object_free(this->raw); } void GitObject::Initialize(Handle<v8::Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->InstanceTemplate()->SetInternalFieldCount(1); tpl->SetClassName(String::NewSymbol("Object")); NODE_SET_PROTOTYPE_METHOD(tpl, "oid", Oid); NODE_SET_PROTOTYPE_METHOD(tpl, "type", Type); NODE_SET_PROTOTYPE_METHOD(tpl, "peel", Peel); constructor_template = Persistent<Function>::New(tpl->GetFunction()); target->Set(String::NewSymbol("Object"), constructor_template); } Handle<Value> GitObject::New(const Arguments& args) { HandleScope scope; if (args.Length() == 0 || !args[0]->IsExternal()) { return ThrowException(Exception::Error(String::New("git_object is required."))); } GitObject* object = new GitObject((git_object *) External::Unwrap(args[0])); object->Wrap(args.This()); return scope.Close(args.This()); } Handle<Value> GitObject::New(void *raw) { HandleScope scope; Handle<Value> argv[1] = { External::New((void *)raw) }; return scope.Close(GitObject::constructor_template->NewInstance(1, argv)); } git_object *GitObject::GetValue() { return this->raw; } /** * @return {Oid} result */ Handle<Value> GitObject::Oid(const Arguments& args) { HandleScope scope; const git_oid * result = git_object_id( ObjectWrap::Unwrap<GitObject>(args.This())->GetValue() ); Handle<Value> to; if (result != NULL) { result = (const git_oid * )git_oid_dup(result); } if (result != NULL) { to = GitOid::New((void *)result); } else { to = Null(); } return scope.Close(to); } /** * @return {Number} result */ Handle<Value> GitObject::Type(const Arguments& args) { HandleScope scope; git_otype result = git_object_type( ObjectWrap::Unwrap<GitObject>(args.This())->GetValue() ); Handle<Value> to; to = Number::New(result); return scope.Close(to); } #include "../include/functions/copy.h" /** * @param {Number} target_type * @param {Object} callback */ Handle<Value> GitObject::Peel(const Arguments& args) { HandleScope scope; if (args.Length() == 0 || !args[0]->IsInt32()) { return ThrowException(Exception::Error(String::New("Number target_type is required."))); } if (args.Length() == 1 || !args[1]->IsFunction()) { return ThrowException(Exception::Error(String::New("Callback is required and must be a Function."))); } PeelBaton* baton = new PeelBaton; baton->error_code = GIT_OK; baton->error = NULL; baton->request.data = baton; baton->objectReference = Persistent<Value>::New(args.This()); baton->object = ObjectWrap::Unwrap<GitObject>(args.This())->GetValue(); baton->target_typeReference = Persistent<Value>::New(args[0]); git_otype from_target_type; from_target_type = (git_otype) args[0]->ToInt32()->Value(); baton->target_type = from_target_type; baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); uv_queue_work(uv_default_loop(), &baton->request, PeelWork, (uv_after_work_cb)PeelAfterWork); return Undefined(); } void GitObject::PeelWork(uv_work_t *req) { PeelBaton *baton = static_cast<PeelBaton *>(req->data); int result = git_object_peel( &baton->peeled, baton->object, baton->target_type ); baton->error_code = result; if (result != GIT_OK && giterr_last() != NULL) { baton->error = git_error_dup(giterr_last()); } } void GitObject::PeelAfterWork(uv_work_t *req) { HandleScope scope; PeelBaton *baton = static_cast<PeelBaton *>(req->data); TryCatch try_catch; if (baton->error_code == GIT_OK) { Handle<Value> to; if (baton->peeled != NULL) { to = GitObject::New((void *)baton->peeled); } else { to = Null(); } Handle<Value> result = to; Handle<Value> argv[2] = { Local<Value>::New(Null()), result }; baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); } else { if (baton->error) { Handle<Value> argv[1] = { Exception::Error(String::New(baton->error->message)) }; baton->callback->Call(Context::GetCurrent()->Global(), 1, argv); if (baton->error->message) free((void *)baton->error->message); free((void *)baton->error); } else { baton->callback->Call(Context::GetCurrent()->Global(), 0, NULL); } } if (try_catch.HasCaught()) { node::FatalException(try_catch); } baton->objectReference.Dispose(); baton->target_typeReference.Dispose(); baton->callback.Dispose(); delete baton; } Persistent<Function> GitObject::constructor_template;
[ "tim@tabdeveloper.com" ]
tim@tabdeveloper.com
91797fc3a33a11f9a67976843658abd05dedfa35
c976dd74566d095ee268b852d1a1fee981e14f18
/src/bsw/io/ios.cpp
691923ce64d557ee21df46bc8c8f61572ad30353
[]
no_license
ttyborg/tombexcavator
f47a001cea0e13c401810409589de1fe44f0cb53
00fef5ed73a33009e497adfb85c271ac385676a4
refs/heads/master
2021-01-17T09:31:58.439925
2012-06-07T19:06:22
2012-06-07T19:06:22
39,796,863
0
0
null
null
null
null
UTF-8
C++
false
false
359
cpp
#include <iostream> #include "bsw/io/ios.hpp" namespace bsw { std::ostream& operator << (std::ostream& os, whence_t whence) { switch (whence) { case eFROM_START: os << "FROM_START"; break; case eFROM_CURRENT: os << "FROM_CURRENT"; break; case eFROM_END: os << "FROM_END"; break; } return os; } } // ns bsw
[ "igor.gutnik@gmail.com" ]
igor.gutnik@gmail.com