blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b0e2f650cd34efb34c1377db7926cc86a6941c42 | 6e60698f107a9a6da687a8f4fa639f3bb12467c7 | /thirdparty/IntervalTree/test/countouterintervals.cpp | ead7e045c5b69781420eab899d1602ff5319f962 | [
"MIT"
] | permissive | nikitaresh/rectangles_intersections | 710769a7512bfc47639bd2db96f68ab16e7d0841 | 3108e12ccd89e2d0d538e83689c96c1d2543fee2 | refs/heads/master | 2020-03-20T20:24:23.059300 | 2018-12-05T16:43:28 | 2018-12-05T16:43:28 | 137,685,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,387 | cpp | #include "catch.hpp"
#include "intervals.h"
TEST_CASE("Count outer intervals")
{
SECTION("Empty tree")
{
const IntervalTree tree;
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(tree.isEmpty());
REQUIRE(0 == count);
}
SECTION("Boundary interval")
{
const auto tree = IntervalTree(Test::boundaryIntervals());
auto count = tree.countOuterIntervals(Test::interval(), true);
REQUIRE(count == Test::boundaryIntervals().size());
count = tree.countOuterIntervals(Test::interval(), false);
REQUIRE(0 == count);
}
SECTION("Outer intervals")
{
const auto tree = IntervalTree(Test::outerIntervals());
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(count == Test::outerIntervals().size());
}
SECTION("Outer and boundary intervals")
{
const auto intervals = Test::compositeIntervals(Test::outerIntervals(), Test::boundaryIntervals());
const auto tree = IntervalTree(intervals);
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(count == intervals.size());
}
SECTION("Inner intervals")
{
const auto tree = IntervalTree(Test::innerIntervals());
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(0 == count);
}
SECTION("Inner and boundary intervals")
{
const auto intervals = Test::compositeIntervals(Test::innerIntervals(), Test::boundaryIntervals());
const auto tree = IntervalTree(intervals);
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(count == Test::boundaryIntervals().size());
}
SECTION("Outer and inner intervals")
{
const auto intervals = Test::compositeIntervals(Test::outerIntervals(), Test::innerIntervals());
const auto tree = IntervalTree(intervals);
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(count == Test::outerIntervals().size());
}
SECTION("Left intervals")
{
const auto tree = IntervalTree(Test::leftIntervals());
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(0 == count);
}
SECTION("Left and outer intervals")
{
const auto intervals = Test::compositeIntervals(Test::leftIntervals(), Test::outerIntervals());
const auto tree = IntervalTree(intervals);
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(count == Test::outerIntervals().size());
}
SECTION("Right intervals")
{
const auto tree = IntervalTree(Test::rightIntervals());
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(0 == count);
}
SECTION("Right and outer intervals")
{
const auto intervals = Test::compositeIntervals(Test::rightIntervals(), Test::outerIntervals());
const auto tree = IntervalTree(intervals);
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(count == Test::outerIntervals().size());
}
SECTION("Left overlapping intervals")
{
const auto tree = IntervalTree(Test::leftOverlappingIntervals());
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(0 == count);
}
SECTION("Left overlapping and outer intervals")
{
const auto intervals = Test::compositeIntervals(Test::leftOverlappingIntervals(), Test::outerIntervals());
const auto tree = IntervalTree(intervals);
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(count == Test::outerIntervals().size());
}
SECTION("Right overlapping intervals")
{
const auto tree = IntervalTree(Test::rightOverlappingIntervals());
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(0 == count);
}
SECTION("Right overlapping and outer intervals")
{
const auto intervals = Test::compositeIntervals(Test::rightOverlappingIntervals(), Test::outerIntervals());
const auto tree = IntervalTree(intervals);
const auto count = tree.countOuterIntervals(Test::interval());
REQUIRE(count == Test::outerIntervals().size());
}
}
| [
"nikitaresh@mail.ru"
] | nikitaresh@mail.ru |
7ee7312a0cdfcc6826d5a643418d9854eaed6c04 | 219bf71bde7b12219656ec333f2329109b3d0c73 | /Source/RHI/OpenRLRHI/RLVertexBufferLayout.cpp | d4e276fda4583b3ef9c6fcafc2b5cb32250fc16c | [] | no_license | blizmax/OpenRL_Baker | 958e96f88efe35e4c7c795f8a1706d1990b6c074 | 8ef3e2c60854088500aa00874447aff61650ee4b | refs/heads/master | 2022-01-13T02:05:14.378677 | 2019-03-11T08:28:24 | 2019-03-11T08:28:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 460 | cpp | #include "RLVertexBufferLayout.h"
namespace Core
{
RLVertexBufferLayout::RLVertexBufferLayout()
{
}
void RLVertexBufferLayout::SetSlotElement(uint32 index, int32 size, RLDataType dataType, Bool normalized, uint32 stride, uint32 offset) const
{
// rlGetAttribLocation(program, "positionAttribute")
rlVertexAttribBuffer(index, size, dataType, normalized, stride, offset);
rlCheckError();
}
RLVertexBufferLayout::~RLVertexBufferLayout()
{
}
} | [
"1989punk@gmail.com"
] | 1989punk@gmail.com |
226f6e49e7ded97fbaaddaaee35d17131215c53c | b0e233b9b173a866cf78f6e74a9b95c1e64eeb51 | /Code/Server/AutoLuaBind/cpp/LuaBind_GameLogic_SkillBase.cpp | 70019f9b1f787463cb4f0d73868e242abe31a6e5 | [] | no_license | xiaol-luo/Utopia | 47a6e987ebd6aaebb7759b736a4590859a6c4eb3 | 798741067114467680c6bcf9d22301f12f127f02 | refs/heads/master | 2021-07-10T13:21:24.547069 | 2019-01-14T14:03:31 | 2019-01-14T14:03:31 | 100,261,666 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,179 | cpp | #include "SolLuaBindUtils.h"
#include <sol.hpp>
#include "Logic/LogicModules/GameLogic/Scene/SceneUnitModules/SceneUnitSkills/SceneUnitSkills.h"
#include "Logic/LogicModules/GameLogic/Scene/Defines/EffectDefine.h"
#include "Logic/LogicModules/GameLogic/Scene/Defines/SceneDefine.h"
#include "Logic/LogicModules/GameLogic/Scene/Skills/SkillConfigBase.h"
#include "Logic/LogicModules/GameLogic/Scene/SceneUnit/SceneUnit.h"
#include "Logic/LogicModules/GameLogic/Scene/Config/SceneAllConfig.h"
#include "Logic/LogicModules/GameLogic/Scene/Skills/SkillBase.h"
namespace SolLuaBind
{
void LuaBind_GameLogic_SkillBase(lua_State *L)
{
struct LuaBindImpl
{
struct ForOverloadFns
{
};
struct ForPropertyField
{
};
static void DoLuaBind(lua_State *L)
{
std::string name = "SkillBase";
std::string name_space = "GameLogic";
{
sol::usertype<GameLogic::SkillBase> meta_table(
sol::constructors<
GameLogic::SkillBase(const GameLogic::SkillConfigBase *)
>(),
"__StructName__", sol::property([]() {return "SkillBase"; })
,"GetSkillId", &GameLogic::SkillBase::GetSkillId
,"SetSkillKey", &GameLogic::SkillBase::SetSkillKey
,"GetSkillKey", &GameLogic::SkillBase::GetSkillKey
,"SetSceneUnitSkills", &GameLogic::SkillBase::SetSceneUnitSkills
,"GetSceneUnitSkills", &GameLogic::SkillBase::GetSceneUnitSkills
,"GetCaster", &GameLogic::SkillBase::GetCaster
,"GetLogicMs", &GameLogic::SkillBase::GetLogicMs
,"SetLevel", &GameLogic::SkillBase::SetLevel
,"ReloadCfg", &GameLogic::SkillBase::ReloadCfg
,"SyncClient", &GameLogic::SkillBase::SyncClient
,"GetPbMsg", &GameLogic::SkillBase::GetPbMsg
, sol::base_classes, sol::bases<
std::enable_shared_from_this<GameLogic::SkillBase>
>()
);
SolLuaBindUtils::BindLuaUserType(sol::state_view(L), meta_table, name, name_space);
}
{
sol::table ns_table = SolLuaBindUtils::GetOrNewLuaNameSpaceTable(sol::state_view(L), name_space)[name];
}
}
};
LuaBindImpl::DoLuaBind(L);
}
} | [
"xiaol.luo@163.com"
] | xiaol.luo@163.com |
5e345746d4d6bf90ea914d006cb8bb979c119a51 | e9d07cf8619f043ab051bd9a584f690fdb136b95 | /modules/fit_signal/fit_signal.h | 5234d2eb592741f7294745dadf8bc22b59f32464 | [] | no_license | slazav/pico_osc | 0465defae427c88bd33de2c659d60c8367aee08a | b98e13b8ea03d07b8d00d8836c74926c0b195593 | refs/heads/master | 2023-02-09T21:58:45.238122 | 2023-02-09T12:33:00 | 2023-02-09T12:33:00 | 29,144,427 | 1 | 1 | null | 2019-12-05T16:05:55 | 2015-01-12T16:22:45 | C++ | UTF-8 | C++ | false | false | 926 | h | #include <vector>
#include <stdint.h>
/*
Fit a signal by a model:
amp * exp(-t/tau) * sin(2*pi*fre*t + ph),
it also works for a non-decaying signals with 1/tau=0,
(TODO: fix boundary conditions!)
output: a vector with 4 double values:
fre, 1/tau, amp, ph
input:
buf -- signal data array
len -- array length
sc -- amplitude scale
dt -- time step
t0 -- time of the first point, returned amplitude and phase is converted to t=0
fmin, fmax -- where to look for a frequency
*/
std::vector<double> fit_signal(const int16_t *buf, int len, double sc, double dt, double t0=0,
double fmin=0, double fmax=+HUGE_VAL);
// fix problem with 'pure signals' where F = 1/tmax and only one fft component is
// large.
std::vector<double> fit_signal_fixfre(const int16_t *buf, int len, double sc, double dt, double t0=0,
double fmin=0, double fmax=+HUGE_VAL);
| [
"slazav@altlinux.org"
] | slazav@altlinux.org |
c9b6194f6e1b936a48ed37cc85d6fa16de7d8fb7 | 3cc1092ed190a1c8a8ad51db38cf21324a29265d | /bin/cpp/include/haxe/IMap.h | 31d4a3948c3f3585ffc3a4ea9b4e036c1406591a | [] | no_license | civo/client-haxe | cab0e890103b4b27a0cbdad65a81aa36746a5d27 | 6542bef8d0ae635e7d7d82aa281efa87fdd04053 | refs/heads/master | 2023-01-08T21:10:00.029740 | 2019-11-27T21:48:54 | 2019-11-27T21:48:54 | 223,903,648 | 1 | 0 | null | 2023-01-05T01:38:54 | 2019-11-25T08:55:54 | C++ | UTF-8 | C++ | false | true | 337 | h | // Generated by Haxe 4.0.2
#ifndef INCLUDED_haxe_IMap
#define INCLUDED_haxe_IMap
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS1(haxe,IMap)
namespace haxe{
class HXCPP_CLASS_ATTRIBUTES IMap_obj {
public:
typedef hx::Object super;
HX_DO_INTERFACE_RTTI;
};
} // end namespace haxe
#endif /* INCLUDED_haxe_IMap */
| [
"lee.sylvester@gmail.com"
] | lee.sylvester@gmail.com |
1fc956a27599f55ef7a4fe04ebadda48d5feb075 | 523a1f9f9628cd1f374f2abf75c78fd7d3f2af33 | /include/queue.h | 4c4cf74864a65e73145f85ea04bf8d9b95005f1a | [
"MIT"
] | permissive | wari/sandbox | c2271fea319df56744c802f620c70ffc4d770ed8 | 13f37d2eb45571d6b34fab65cfc965b443621697 | refs/heads/master | 2020-05-09T09:26:25.613873 | 2014-02-05T05:20:12 | 2014-02-05T05:20:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 171 | h | class Queue {
struct Node {
int* data;
Node *next;
};
Node *front;
Node *back;
public:
Queue();
void put(int);
int* get();
};
| [
"wahabmw@i2r.a-star.edu.sg"
] | wahabmw@i2r.a-star.edu.sg |
09d641424b38b5fa5cce4b791a6541e92f9d58c6 | 84a96dbd96e926ebb5c658e3cb897db276c32d6c | /tensorflow/core/common_runtime/process_state.cc | 19f7a985f3e3bcc3647c6d0358738527840cc818 | [
"Apache-2.0"
] | permissive | MothCreations/gavlanWheels | bc9189092847369ad291d1c7d3f4144dd2239359 | 01d8a43b45a26afec27b971f686f79c108fe08f9 | refs/heads/master | 2022-12-06T09:27:49.458800 | 2020-10-13T21:56:40 | 2020-10-13T21:56:40 | 249,206,716 | 6 | 5 | Apache-2.0 | 2022-11-21T22:39:47 | 2020-03-22T14:57:45 | C++ | UTF-8 | C++ | false | false | 6,027 | cc | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/process_state.h"
#include <cstring>
#include <vector>
#include "absl/base/call_once.h"
#include "tensorflow/core/common_runtime/bfc_allocator.h"
#include "tensorflow/core/common_runtime/pool_allocator.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/log_memory.h"
#include "tensorflow/core/framework/tracking_allocator.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/env_var.h"
namespace tensorflow {
/*static*/ ProcessState* ProcessState::singleton() {
static ProcessState* instance = new ProcessState;
static absl::once_flag f;
absl::call_once(f, []() {
AllocatorFactoryRegistry::singleton()->process_state_ = instance;
});
return instance;
}
ProcessState::ProcessState() : numa_enabled_(false) {}
string ProcessState::MemDesc::DebugString() {
return strings::StrCat((loc == CPU ? "CPU " : "GPU "), dev_index,
", dma: ", gpu_registered, ", nic: ", nic_registered);
}
ProcessState::MemDesc ProcessState::PtrType(const void* ptr) {
if (FLAGS_brain_gpu_record_mem_types) {
auto iter = mem_desc_map_.find(ptr);
if (iter != mem_desc_map_.end()) {
return iter->second;
}
}
return MemDesc();
}
Allocator* ProcessState::GetCPUAllocator(int numa_node) {
if (!numa_enabled_ || numa_node == port::kNUMANoAffinity) numa_node = 0;
mutex_lock lock(mu_);
while (cpu_allocators_.size() <= static_cast<size_t>(numa_node)) {
// If visitors have been defined we need an Allocator built from
// a SubAllocator. Prefer BFCAllocator, but fall back to PoolAllocator
// depending on env var setting.
const bool alloc_visitors_defined =
(!cpu_alloc_visitors_.empty() || !cpu_free_visitors_.empty());
bool use_bfc_allocator = false;
Status status = ReadBoolFromEnvVar(
"TF_CPU_ALLOCATOR_USE_BFC", alloc_visitors_defined, &use_bfc_allocator);
if (!status.ok()) {
LOG(ERROR) << "GetCPUAllocator: " << status.error_message();
}
Allocator* allocator = nullptr;
SubAllocator* sub_allocator =
(numa_enabled_ || alloc_visitors_defined || use_bfc_allocator)
? new BasicCPUAllocator(
numa_enabled_ ? numa_node : port::kNUMANoAffinity,
cpu_alloc_visitors_, cpu_free_visitors_)
: nullptr;
if (use_bfc_allocator) {
// TODO(reedwm): evaluate whether 64GB by default is the best choice.
int64 cpu_mem_limit_in_mb = -1;
Status status = ReadInt64FromEnvVar("TF_CPU_BFC_MEM_LIMIT_IN_MB",
1LL << 16 /*64GB max by default*/,
&cpu_mem_limit_in_mb);
if (!status.ok()) {
LOG(ERROR) << "GetCPUAllocator: " << status.error_message();
}
int64 cpu_mem_limit = cpu_mem_limit_in_mb * (1LL << 20);
DCHECK(sub_allocator);
allocator =
new BFCAllocator(sub_allocator, cpu_mem_limit, true /*allow_growth*/,
"bfc_cpu_allocator_for_gpu" /*name*/);
VLOG(2) << "Using BFCAllocator with memory limit of "
<< cpu_mem_limit_in_mb << " MB for ProcessState CPU allocator";
} else if (sub_allocator) {
DCHECK(sub_allocator);
allocator =
new PoolAllocator(100 /*pool_size_limit*/, true /*auto_resize*/,
sub_allocator, new NoopRounder, "cpu_pool");
VLOG(2) << "Using PoolAllocator for ProcessState CPU allocator "
<< "numa_enabled_=" << numa_enabled_
<< " numa_node=" << numa_node;
} else {
DCHECK(!sub_allocator);
allocator = cpu_allocator_base();
}
if (LogMemory::IsEnabled() && !allocator->TracksAllocationSizes()) {
// Wrap the allocator to track allocation ids for better logging
// at the cost of performance.
allocator = new TrackingAllocator(allocator, true);
}
cpu_allocators_.push_back(allocator);
if (!sub_allocator) {
DCHECK(cpu_alloc_visitors_.empty() && cpu_free_visitors_.empty());
}
}
return cpu_allocators_[numa_node];
}
void ProcessState::AddCPUAllocVisitor(SubAllocator::Visitor visitor) {
VLOG(1) << "AddCPUAllocVisitor";
mutex_lock lock(mu_);
CHECK_EQ(0, cpu_allocators_.size()) // Crash OK
<< "AddCPUAllocVisitor must be called prior to first call to "
"ProcessState::GetCPUAllocator";
cpu_alloc_visitors_.push_back(std::move(visitor));
}
void ProcessState::AddCPUFreeVisitor(SubAllocator::Visitor visitor) {
mutex_lock lock(mu_);
CHECK_EQ(0, cpu_allocators_.size()) // Crash OK
<< "AddCPUFreeVisitor must be called prior to first call to "
"ProcessState::GetCPUAllocator";
cpu_free_visitors_.push_back(std::move(visitor));
}
void ProcessState::TestOnlyReset() {
mutex_lock lock(mu_);
// Don't delete this value because it's static.
Allocator* default_cpu_allocator = cpu_allocator_base();
mem_desc_map_.clear();
for (Allocator* a : cpu_allocators_) {
if (a != default_cpu_allocator) delete a;
}
cpu_allocators_.clear();
for (Allocator* a : cpu_al_) {
delete a;
}
cpu_al_.clear();
}
} // namespace tensorflow
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
6e95a1d5585eabb74ab3aaca63f00d47e4a2c815 | b9b17fcfac43774e730ecf221bc26164598010b6 | /src/ncmdline.h | 85cf03f86fa4e7414fb082793ac98677692bc5f9 | [
"BSD-3-Clause"
] | permissive | taviso/mpgravity | e2334e77e9d5e9769e05d24609e4bbed00f23b5c | f6a2a7a02014b19047e44db76ae551bd689c16ac | refs/heads/master | 2023-07-26T00:49:37.297106 | 2020-04-24T06:15:10 | 2020-04-24T06:15:10 | 251,759,803 | 13 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,521 | h | /*****************************************************************************/
/* SOURCE CONTROL VERSIONS */
/*---------------------------------------------------------------------------*/
/* */
/* Version Date Time Author / Comment (optional) */
/* */
/* $Log: ncmdline.h,v $
/* Revision 1.1 2010/07/21 17:14:57 richard_wood
/* Initial checkin of V3.0.0 source code and other resources.
/* Initial code builds V3.0.0 RC1
/*
/* Revision 1.2 2009/07/26 15:54:59 richard_wood
/* Added import / export of news server.
/* Refactored import / export of database / settings.
/* Added command line import of news server.
/* Fixed crash on trace file use.
/* Tidied up source code in a few files.
/*
/* Revision 1.1 2009/06/09 13:21:29 richard_wood
/* *** empty log message ***
/*
/* Revision 1.2 2008/09/19 14:51:33 richard_wood
/* Updated for VS 2005
/*
/* */
/*****************************************************************************/
/**********************************************************************************
Copyright (c) 2003, Albert M. Choy
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 Microplanet, 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.
**********************************************************************************/
#pragma once
class TNewsCommandLineInfo : public CCommandLineInfo
{
public:
TNewsCommandLineInfo();
~TNewsCommandLineInfo() {}
void ParseParam (LPCTSTR lpszParam, BOOL fFlag, BOOL bLast);
BOOL m_bLogStartup;
BOOL m_bSafeStart;
bool m_bNewsURL; // true if a Usenet (news: or nntp:) URL is here
CString m_strNewsURL;
bool m_bVCRFile; // true if VCR file is specified
CString m_strVCRFile;
bool m_bGSXFile;
CString m_strGSXFile;
};
| [
"taviso@gmail.com"
] | taviso@gmail.com |
de10269f4d283bacbeaf31487398b4504b54e0ae | f03cc2d3b830f6a616af40815815020ead38b992 | /FairyEngine/Source/F3DEngine/F3DTrack.h | 666fdc4efd8e605f073f7bf5e4a824cef51cedb3 | [] | no_license | yish0000/Fairy3D | 18d88d13e2a3a3e466d65db7aea06a8b111118ba | 6b84c6cb6c58a383e53a6a7f64676667c159c76b | refs/heads/master | 2021-07-01T16:37:14.887464 | 2020-11-08T14:52:01 | 2020-11-08T14:52:01 | 12,029,469 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,189 | h | /*
* ------------------------------------------------------------------------
* Name: F3DTrack.h
* Desc: 本文件定义了一个引擎所需的轨迹类。
* Author: Yish
* Date: 2010/11/12
* ----------------------------------------------------------------------
* CopyRight (C) YishSoft. 2010 All right Observed.
* ------------------------------------------------------------------------
*/
#ifndef __F3D_TRACK_H__
#define __F3D_TRACK_H__
//// HEADERS OF THIS FILE /////////////////////////////////////////////////
#include "F3DTypes.h"
///////////////////////////////////////////////////////////////////////////
enum EInterpolateType
{
ITT_LINEAR, // 线性插值(速度快)
ITT_SPLINE, // 曲线插值(速度慢,但会使方向的变化平滑)
};
/** 该类用来描述一个可移动物体的轨迹。
@remarks
@note
*/
class FAIRY_API F3DTrack : public FGeneralAlloc
{
protected:
std::vector<F3DVector3> m_Verts; // 关键顶点列表
float m_fWholeTime; // 轨迹所需的总时间
EInterpolateType m_InterType; // 插值类型
public:
F3DTrack();
F3DTrack( EInterpolateType type );
~F3DTrack();
// 加载/保存轨迹文件
bool LoadTrackFile( const char* filename );
void SaveTrackFile( const char* filename );
void AddVertex( const F3DVector3& vert );
void RemoveVertex( size_t nIndex );
void Clear(void);
size_t GetNumVerts(void) const { return m_Verts.size(); }
const F3DVector3& GetVertex( size_t nIndex ) const;
// 后去一个指定时间点的位置
F3DVector3 GetCurPos( float fTime );
// 设置轨迹所需的总时间
void SetWholeTime( float fWholeTime ) { m_fWholeTime = fWholeTime; }
float GetWholeTime(void) const { return m_fWholeTime; }
// 设置轨迹的插值类型
EInterpolateType GetInterpolateType(void) const { return m_InterType; }
void SetInterpolateType( EInterpolateType type ) { m_InterType = type; }
};
///////////////////////////////////////////////////////////////////////////
#endif //#ifndef __F3D_TRACK_H__ | [
"yish0000@foxmail.com"
] | yish0000@foxmail.com |
1b421321dc11fda00a3fb36db20be76cfb6ba651 | 8ba3820b70bf3808dc96ac393f96e859c17e69e7 | /codeforces/1341/A.cpp | 07527de9e42f8af5b1a23bea2d47eb44df21e8b0 | [] | no_license | anikxt/Competitive_Programming | d92767247c358a093d8de04933c8fda4abeb42c0 | e464bd2b480ccc4f469bdbe1609af921ef93c723 | refs/heads/master | 2023-03-24T13:56:38.442334 | 2021-02-14T18:14:00 | 2021-03-19T19:19:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 710 | cpp | //#pragma GCC optimize "trapv"
#include<bits/stdc++.h>
#define ll long long
#define fab(a,b,i) for(int i=a;i<b;i++)
#define pb push_back
#define db double
#define mp make_pair
#define endl "\n"
#define f first
#define se second
#define all(x) x.begin(),x.end()
#define MOD 1000000007
#define quick ios_base::sync_with_stdio(false);cin.tie(NULL)
using namespace std;
int main()
{ quick;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t;
cin>>t;
while(t--)
{
ll int n,a,b,c,d;
cin>>n>>a>>b>>c>>d;
ll int k=a+b,j=a-b,l=c+d,p=c-d;
string ans="YES";
if(k*n<p)
ans="NO";
if(j*n>l)
ans="NO";
cout<<ans<<endl;
}
return 0;
} | [
"nishitsharma0@gmail.com"
] | nishitsharma0@gmail.com |
d46339589bbf7fa89b60df847d29bf8e862e06ad | c80bd757f18735452eef1f0f7cd7bd305d4313c7 | /src/Dataflow/Serialization/Network/ModuleDescriptionSerialization.cc | bbf1c5a3aab7428d015fcf682a749aa9b73d22f5 | [
"MIT"
] | permissive | kenlouie/SCIRunGUIPrototype | 956449f4b4ce3ed76ccc1fa23a6656f084c3a9b1 | 062ff605839b076177c4e50f08cf36d83a6a9220 | refs/heads/master | 2020-12-25T03:11:44.510875 | 2013-10-01T05:51:39 | 2013-10-01T05:51:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,990 | cc | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Dataflow/Serialization/Network/ModuleDescriptionSerialization.h>
using namespace SCIRun::Dataflow::Networks;
ModuleLookupInfoXML::ModuleLookupInfoXML() {}
ModuleLookupInfoXML::ModuleLookupInfoXML(const ModuleLookupInfoXML& rhs) : ModuleLookupInfo(rhs) {}
ModuleLookupInfoXML::ModuleLookupInfoXML(const ModuleLookupInfo& rhs) : ModuleLookupInfo(rhs) {}
ConnectionDescriptionXML::ConnectionDescriptionXML() {}
ConnectionDescriptionXML::ConnectionDescriptionXML(const ConnectionDescriptionXML& rhs) : ConnectionDescription(rhs) {}
ConnectionDescriptionXML::ConnectionDescriptionXML(const ConnectionDescription& rhs) : ConnectionDescription(rhs) {}
| [
"dwhite@sci.utah.edu"
] | dwhite@sci.utah.edu |
b4c9883e2dfe8c12262f42960cd4e05748b90d15 | 6391f2ba00ee3273518af0a02be01c1141ad667c | /include/GameState.hpp | 8ae628ed79040938c6fd286e19fcd844ae004305 | [] | no_license | linorabolini/Dungeon | d1847f8fc368b0f09e5a79866a00aab60f85cbae | d23bec2a94b84636d4daec91f826b8fd11bd318c | refs/heads/master | 2020-01-23T21:34:01.506515 | 2017-02-02T23:26:40 | 2017-02-02T23:26:40 | 74,698,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 116 | hpp | #pragma once
struct GameState
{
int floorsCleared = 0;
int enemiesKilled = 0;
int chestsOpened = 0;
};
| [
"linorabolini@gmail.com"
] | linorabolini@gmail.com |
4355740daf6a988512d75ae7975e7b7af538f1ff | 632b94beca62f7c8af5ae1d1e8e095a352600429 | /devel/include/control_msgs/FollowJointTrajectoryAction.h | fb65b86db7ea7b7e96f1ccbdd14fd0b549592ff7 | [] | no_license | Haoran-Zhao/US_UR3 | d9eb17a7eceed75bc623be4f4db417a38f5a9f8d | a0c25e1daf613bb45dbd08075e3185cb9cd03657 | refs/heads/master | 2020-08-31T07:02:45.403001 | 2020-05-27T16:58:52 | 2020-05-27T16:58:52 | 218,629,020 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,549 | h | // Generated by gencpp from file control_msgs/FollowJointTrajectoryAction.msg
// DO NOT EDIT!
#ifndef CONTROL_MSGS_MESSAGE_FOLLOWJOINTTRAJECTORYACTION_H
#define CONTROL_MSGS_MESSAGE_FOLLOWJOINTTRAJECTORYACTION_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 <control_msgs/FollowJointTrajectoryActionGoal.h>
#include <control_msgs/FollowJointTrajectoryActionResult.h>
#include <control_msgs/FollowJointTrajectoryActionFeedback.h>
namespace control_msgs
{
template <class ContainerAllocator>
struct FollowJointTrajectoryAction_
{
typedef FollowJointTrajectoryAction_<ContainerAllocator> Type;
FollowJointTrajectoryAction_()
: action_goal()
, action_result()
, action_feedback() {
}
FollowJointTrajectoryAction_(const ContainerAllocator& _alloc)
: action_goal(_alloc)
, action_result(_alloc)
, action_feedback(_alloc) {
(void)_alloc;
}
typedef ::control_msgs::FollowJointTrajectoryActionGoal_<ContainerAllocator> _action_goal_type;
_action_goal_type action_goal;
typedef ::control_msgs::FollowJointTrajectoryActionResult_<ContainerAllocator> _action_result_type;
_action_result_type action_result;
typedef ::control_msgs::FollowJointTrajectoryActionFeedback_<ContainerAllocator> _action_feedback_type;
_action_feedback_type action_feedback;
typedef boost::shared_ptr< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> const> ConstPtr;
}; // struct FollowJointTrajectoryAction_
typedef ::control_msgs::FollowJointTrajectoryAction_<std::allocator<void> > FollowJointTrajectoryAction;
typedef boost::shared_ptr< ::control_msgs::FollowJointTrajectoryAction > FollowJointTrajectoryActionPtr;
typedef boost::shared_ptr< ::control_msgs::FollowJointTrajectoryAction const> FollowJointTrajectoryActionConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace control_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'trajectory_msgs': ['/opt/ros/kinetic/share/trajectory_msgs/cmake/../msg'], 'control_msgs': ['/home/haoran/US_UR3/devel/share/control_msgs/msg', '/home/haoran/US_UR3/src/ros_controllers/control_msgs/control_msgs/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< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> >
{
static const char* value()
{
return "bc4f9b743838566551c0390c65f1a248";
}
static const char* value(const ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xbc4f9b7438385665ULL;
static const uint64_t static_value2 = 0x51c0390c65f1a248ULL;
};
template<class ContainerAllocator>
struct DataType< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> >
{
static const char* value()
{
return "control_msgs/FollowJointTrajectoryAction";
}
static const char* value(const ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> >
{
static const char* value()
{
return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
\n\
FollowJointTrajectoryActionGoal action_goal\n\
FollowJointTrajectoryActionResult action_result\n\
FollowJointTrajectoryActionFeedback action_feedback\n\
\n\
================================================================================\n\
MSG: control_msgs/FollowJointTrajectoryActionGoal\n\
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
\n\
Header header\n\
actionlib_msgs/GoalID goal_id\n\
FollowJointTrajectoryGoal goal\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\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
\n\
================================================================================\n\
MSG: actionlib_msgs/GoalID\n\
# The stamp should store the time at which this goal was requested.\n\
# It is used by an action server when it tries to preempt all\n\
# goals that were requested before a certain time\n\
time stamp\n\
\n\
# The id provides a way to associate feedback and\n\
# result message with specific goal requests. The id\n\
# specified must be unique.\n\
string id\n\
\n\
\n\
================================================================================\n\
MSG: control_msgs/FollowJointTrajectoryGoal\n\
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
# The joint trajectory to follow\n\
trajectory_msgs/JointTrajectory trajectory\n\
\n\
# Tolerances for the trajectory. If the measured joint values fall\n\
# outside the tolerances the trajectory goal is aborted. Any\n\
# tolerances that are not specified (by being omitted or set to 0) are\n\
# set to the defaults for the action server (often taken from the\n\
# parameter server).\n\
\n\
# Tolerances applied to the joints as the trajectory is executed. If\n\
# violated, the goal aborts with error_code set to\n\
# PATH_TOLERANCE_VIOLATED.\n\
JointTolerance[] path_tolerance\n\
\n\
# To report success, the joints must be within goal_tolerance of the\n\
# final trajectory value. The goal must be achieved by time the\n\
# trajectory ends plus goal_time_tolerance. (goal_time_tolerance\n\
# allows some leeway in time, so that the trajectory goal can still\n\
# succeed even if the joints reach the goal some time after the\n\
# precise end time of the trajectory).\n\
#\n\
# If the joints are not within goal_tolerance after \"trajectory finish\n\
# time\" + goal_time_tolerance, the goal aborts with error_code set to\n\
# GOAL_TOLERANCE_VIOLATED\n\
JointTolerance[] goal_tolerance\n\
duration goal_time_tolerance\n\
\n\
\n\
================================================================================\n\
MSG: trajectory_msgs/JointTrajectory\n\
Header header\n\
string[] joint_names\n\
JointTrajectoryPoint[] points\n\
================================================================================\n\
MSG: trajectory_msgs/JointTrajectoryPoint\n\
# Each trajectory point specifies either positions[, velocities[, accelerations]]\n\
# or positions[, effort] for the trajectory to be executed.\n\
# All specified values are in the same order as the joint names in JointTrajectory.msg\n\
\n\
float64[] positions\n\
float64[] velocities\n\
float64[] accelerations\n\
float64[] effort\n\
duration time_from_start\n\
\n\
================================================================================\n\
MSG: control_msgs/JointTolerance\n\
# The tolerances specify the amount the position, velocity, and\n\
# accelerations can vary from the setpoints. For example, in the case\n\
# of trajectory control, when the actual position varies beyond\n\
# (desired position + position tolerance), the trajectory goal may\n\
# abort.\n\
# \n\
# There are two special values for tolerances:\n\
# * 0 - The tolerance is unspecified and will remain at whatever the default is\n\
# * -1 - The tolerance is \"erased\". If there was a default, the joint will be\n\
# allowed to move without restriction.\n\
\n\
string name\n\
float64 position # in radians or meters (for a revolute or prismatic joint, respectively)\n\
float64 velocity # in rad/sec or m/sec\n\
float64 acceleration # in rad/sec^2 or m/sec^2\n\
\n\
================================================================================\n\
MSG: control_msgs/FollowJointTrajectoryActionResult\n\
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
\n\
Header header\n\
actionlib_msgs/GoalStatus status\n\
FollowJointTrajectoryResult result\n\
\n\
================================================================================\n\
MSG: actionlib_msgs/GoalStatus\n\
GoalID goal_id\n\
uint8 status\n\
uint8 PENDING = 0 # The goal has yet to be processed by the action server\n\
uint8 ACTIVE = 1 # The goal is currently being processed by the action server\n\
uint8 PREEMPTED = 2 # The goal received a cancel request after it started executing\n\
# and has since completed its execution (Terminal State)\n\
uint8 SUCCEEDED = 3 # The goal was achieved successfully by the action server (Terminal State)\n\
uint8 ABORTED = 4 # The goal was aborted during execution by the action server due\n\
# to some failure (Terminal State)\n\
uint8 REJECTED = 5 # The goal was rejected by the action server without being processed,\n\
# because the goal was unattainable or invalid (Terminal State)\n\
uint8 PREEMPTING = 6 # The goal received a cancel request after it started executing\n\
# and has not yet completed execution\n\
uint8 RECALLING = 7 # The goal received a cancel request before it started executing,\n\
# but the action server has not yet confirmed that the goal is canceled\n\
uint8 RECALLED = 8 # The goal received a cancel request before it started executing\n\
# and was successfully cancelled (Terminal State)\n\
uint8 LOST = 9 # An action client can determine that a goal is LOST. This should not be\n\
# sent over the wire by an action server\n\
\n\
#Allow for the user to associate a string with GoalStatus for debugging\n\
string text\n\
\n\
\n\
================================================================================\n\
MSG: control_msgs/FollowJointTrajectoryResult\n\
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
int32 error_code\n\
int32 SUCCESSFUL = 0\n\
int32 INVALID_GOAL = -1\n\
int32 INVALID_JOINTS = -2\n\
int32 OLD_HEADER_TIMESTAMP = -3\n\
int32 PATH_TOLERANCE_VIOLATED = -4\n\
int32 GOAL_TOLERANCE_VIOLATED = -5\n\
\n\
# Human readable description of the error code. Contains complementary\n\
# information that is especially useful when execution fails, for instance:\n\
# - INVALID_GOAL: The reason for the invalid goal (e.g., the requested\n\
# trajectory is in the past).\n\
# - INVALID_JOINTS: The mismatch between the expected controller joints\n\
# and those provided in the goal.\n\
# - PATH_TOLERANCE_VIOLATED and GOAL_TOLERANCE_VIOLATED: Which joint\n\
# violated which tolerance, and by how much.\n\
string error_string\n\
\n\
\n\
================================================================================\n\
MSG: control_msgs/FollowJointTrajectoryActionFeedback\n\
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
\n\
Header header\n\
actionlib_msgs/GoalStatus status\n\
FollowJointTrajectoryFeedback feedback\n\
\n\
================================================================================\n\
MSG: control_msgs/FollowJointTrajectoryFeedback\n\
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
Header header\n\
string[] joint_names\n\
trajectory_msgs/JointTrajectoryPoint desired\n\
trajectory_msgs/JointTrajectoryPoint actual\n\
trajectory_msgs/JointTrajectoryPoint error\n\
\n\
";
}
static const char* value(const ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.action_goal);
stream.next(m.action_result);
stream.next(m.action_feedback);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct FollowJointTrajectoryAction_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::control_msgs::FollowJointTrajectoryAction_<ContainerAllocator>& v)
{
s << indent << "action_goal: ";
s << std::endl;
Printer< ::control_msgs::FollowJointTrajectoryActionGoal_<ContainerAllocator> >::stream(s, indent + " ", v.action_goal);
s << indent << "action_result: ";
s << std::endl;
Printer< ::control_msgs::FollowJointTrajectoryActionResult_<ContainerAllocator> >::stream(s, indent + " ", v.action_result);
s << indent << "action_feedback: ";
s << std::endl;
Printer< ::control_msgs::FollowJointTrajectoryActionFeedback_<ContainerAllocator> >::stream(s, indent + " ", v.action_feedback);
}
};
} // namespace message_operations
} // namespace ros
#endif // CONTROL_MSGS_MESSAGE_FOLLOWJOINTTRAJECTORYACTION_H
| [
"zhaohaorandl@gmail.com"
] | zhaohaorandl@gmail.com |
9799de56b81b66934c75c38e50c76d34ea7e6379 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /gse/include/tencentcloud/gse/v20191112/model/DeleteScalingPolicyResponse.h | 141bb3c22118c26292bf39a6888c795e3ca9be06 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 1,637 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_GSE_V20191112_MODEL_DELETESCALINGPOLICYRESPONSE_H_
#define TENCENTCLOUD_GSE_V20191112_MODEL_DELETESCALINGPOLICYRESPONSE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Gse
{
namespace V20191112
{
namespace Model
{
/**
* DeleteScalingPolicy返回参数结构体
*/
class DeleteScalingPolicyResponse : public AbstractModel
{
public:
DeleteScalingPolicyResponse();
~DeleteScalingPolicyResponse() = default;
CoreInternalOutcome Deserialize(const std::string &payload);
std::string ToJsonString() const;
private:
};
}
}
}
}
#endif // !TENCENTCLOUD_GSE_V20191112_MODEL_DELETESCALINGPOLICYRESPONSE_H_
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
1393776d3103dda6b4caeef8ab410746ee831133 | dbfb77666a87e0d9dc89f2f50db89e7173f1f0d8 | /source/cpp_utils/data/ArrayView.hpp | 714ae5194ef47b502b5c8995d539f2f16ab00f78 | [] | no_license | VladasZ/cpp_utils | b7b248933e1711c6586be2a836d56c9383c5d96c | 76e7246f6b31e8a189e5fbbb943c733792815f9e | refs/heads/master | 2021-06-10T11:14:16.895833 | 2021-03-31T19:50:32 | 2021-03-31T19:50:32 | 157,543,516 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,057 | hpp | //
// ArrayView.hpp
// cpp_utils
//
// Created by Vladas Zakrevskis on 03/05/20.
// Copyright © 2020 VladasZ. All rights reserved.
//
#pragma once
#include <stdlib.h>
namespace cu {
template<class T>
class ArrayView {
private:
const T* const _data;
const size_t _size;
public:
ArrayView() : _data(nullptr), _size(0) { }
explicit ArrayView(const T* data, size_t size) : _data(data), _size(size) { }
template<class Container, class Value = typename Container::value_type>
constexpr ArrayView(const Container& container)
: _data(reinterpret_cast<const T*>(container.data())),
_size(container.size() * (sizeof(Value) / sizeof(T))) { }
bool empty() const { return _size == 0; }
size_t size() const { return _size; }
const T* data() const { return _data; }
const T* begin() const { return _data; }
const T* end() const { return _data + _size; }
const T& operator[](int i) const { return _data[i]; }
};
}
| [
"146100@gmail.com"
] | 146100@gmail.com |
d99d743af97c21e8fee84e101560d3543ceefa62 | 7e96610cc01da9082e6c00c2f8304da78fee5af0 | /src/server/game/Handlers/CollectionsHandler.cpp | 0679ef9b90396dd4c6e0b048e0fdc5f75c02b548 | [] | no_license | ralphhorizon/bfacore-1 | f945d24bafcb84f12d875c17aa8e948bddcb46ed | 8085d551669a164aa7fbade55081058451cb8024 | refs/heads/master | 2023-01-06T23:21:35.959674 | 2020-10-24T20:17:16 | 2020-10-24T20:17:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,707 | cpp | /*
* Copyright (C) 2020 BfaCore
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "WorldSession.h"
#include "CollectionMgr.h"
#include "CollectionPackets.h"
void WorldSession::HandleCollectionItemSetFavorite(WorldPackets::Collections::CollectionItemSetFavorite& collectionItemSetFavorite)
{
switch (collectionItemSetFavorite.Type)
{
case WorldPackets::Collections::TOYBOX:
GetCollectionMgr()->ToySetFavorite(collectionItemSetFavorite.ID, collectionItemSetFavorite.IsFavorite);
break;
case WorldPackets::Collections::APPEARANCE:
{
bool hasAppearance, isTemporary;
std::tie(hasAppearance, isTemporary) = GetCollectionMgr()->HasItemAppearance(collectionItemSetFavorite.ID);
if (!hasAppearance || isTemporary)
return;
GetCollectionMgr()->SetAppearanceIsFavorite(collectionItemSetFavorite.ID, collectionItemSetFavorite.IsFavorite);
break;
}
case WorldPackets::Collections::TRANSMOG_SET:
break;
default:
break;
}
}
| [
"zemetskia@gmail.com"
] | zemetskia@gmail.com |
ab051ff4bec4499901de3b8cbb3e1fab6bac12e3 | 9e99984a3e8a5582ce2f32beb8e7bbcaf6f71fb3 | /src/points.h | 1bfabf8bcfded8e024c6c109377217c65246c1cb | [] | no_license | alirezagoli/dots-game | 1176985b0cc7ff88478a1b5b3218c25177006fc0 | 5899c7dc7a3b0d208e17210f51a9cac4528ed3e8 | refs/heads/main | 2023-02-09T09:17:21.247788 | 2021-01-02T09:57:48 | 2021-01-02T09:57:48 | 326,098,931 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,096 | h | #ifndef POINTS_H
#define POINTS_H
#include <QGraphicsScene>
#include<QGraphicsEllipseItem>
#include<QList>
#include<QMessageBox>
#include<QBrush>
#include"show_winner.h"
enum playerTurn{player1,player2};
struct PointStatus
{
PointStatus *up;
PointStatus *down;
PointStatus *right;
PointStatus *left;
};
class points : public QGraphicsScene
{
Q_OBJECT
public:
points(QObject *parent = 0, int Row_size=11, int Col_size=11);
private:
PointStatus **PS;
playerTurn PT;
QList<QGraphicsItem *>items;
int RowSize;
int ColSize;
int RectCounter;
int Player1Score;
int Player2Score;
PointStatus temp;
private:
void drawline();
void ChangePointStatus();
bool CheckRect();
void Updating_Score_RectCount();
void ChangePlayerTurn();
protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
signals:
void UpdatingScoreBoard1(int);
void UpdatingScoreBoard2(int);
void Winner(QString);
void exitmainwindows();
void PlayerTurn(QString);
public slots:
};
#endif // POINTS_H
| [
"alirezagoli.mail@gmail.com"
] | alirezagoli.mail@gmail.com |
41cfc04ba182c6f4a1c9e2b53e274f234496422d | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /chrome/browser/ui/search/instant_theme_browsertest.cc | 9a6115bbe46b4d0a90a5e8fc84e48395d363689a | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 12,619 | 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 "base/macros.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search/instant_service.h"
#include "chrome/browser/search/instant_service_factory.h"
#include "chrome/browser/search/instant_service_observer.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/search/instant_test_base.h"
#include "chrome/browser/ui/search/instant_test_utils.h"
#include "chrome/browser/ui/search/local_ntp_test_utils.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/webui/theme_source.h"
#include "chrome/common/search/instant_types.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/extension_registry.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
class TestThemeInfoObserver : public InstantServiceObserver {
public:
explicit TestThemeInfoObserver(InstantService* service) : service_(service) {
service_->AddObserver(this);
}
~TestThemeInfoObserver() override { service_->RemoveObserver(this); }
void WaitForThemeApplied(bool theme_installed) {
DCHECK(!quit_closure_);
theme_installed_ = theme_installed;
if (!theme_info_.using_default_theme == theme_installed) {
return;
}
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitClosure();
run_loop.Run();
}
bool IsUsingDefaultTheme() { return theme_info_.using_default_theme; }
private:
void ThemeInfoChanged(const ThemeBackgroundInfo& theme_info) override {
theme_info_ = theme_info;
if (quit_closure_ && !theme_info_.using_default_theme == theme_installed_) {
std::move(quit_closure_).Run();
quit_closure_.Reset();
}
}
void MostVisitedItemsChanged(const std::vector<InstantMostVisitedItem>&,
bool is_custom_links) override {}
InstantService* const service_;
ThemeBackgroundInfo theme_info_;
bool theme_installed_;
base::OnceClosure quit_closure_;
};
class InstantThemeTest : public extensions::ExtensionBrowserTest,
public InstantTestBase {
public:
InstantThemeTest() {}
protected:
void SetUpInProcessBrowserTestFixture() override {
ASSERT_TRUE(https_test_server().Start());
GURL base_url = https_test_server().GetURL("/instant_extended.html");
GURL ntp_url = https_test_server().GetURL("/instant_extended_ntp.html");
InstantTestBase::Init(base_url, ntp_url, false);
}
void SetUpOnMainThread() override {
extensions::ExtensionBrowserTest::SetUpOnMainThread();
content::URLDataSource::Add(profile(),
std::make_unique<ThemeSource>(profile()));
}
void InstallThemeAndVerify(const std::string& theme_dir,
const std::string& theme_name) {
bool had_previous_theme =
!!ThemeServiceFactory::GetThemeForProfile(profile());
const base::FilePath theme_path = test_data_dir_.AppendASCII(theme_dir);
// Themes install asynchronously so we must check the number of enabled
// extensions after theme install completes.
size_t num_before = extensions::ExtensionRegistry::Get(profile())
->enabled_extensions()
.size();
content::WindowedNotificationObserver theme_change_observer(
chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
content::Source<ThemeService>(
ThemeServiceFactory::GetForProfile(profile())));
ASSERT_TRUE(InstallExtensionWithUIAutoConfirm(
theme_path, 1, extensions::ExtensionBrowserTest::browser()));
theme_change_observer.Wait();
size_t num_after = extensions::ExtensionRegistry::Get(profile())
->enabled_extensions()
.size();
// If a theme was already installed, we're just swapping one for another, so
// no change in extension count.
int expected_change = had_previous_theme ? 0 : 1;
EXPECT_EQ(num_before + expected_change, num_after);
const extensions::Extension* new_theme =
ThemeServiceFactory::GetThemeForProfile(profile());
ASSERT_NE(nullptr, new_theme);
ASSERT_EQ(new_theme->name(), theme_name);
}
// Loads a named image from |image_url| in the given |tab|. |loaded|
// returns whether the image was able to load without error.
// The method returns true if the JavaScript executed cleanly.
bool LoadImage(content::WebContents* tab,
const GURL& image_url,
bool* loaded) {
std::string js_chrome =
"var img = document.createElement('img');"
"img.onerror = function() { domAutomationController.send(false); };"
"img.onload = function() { domAutomationController.send(true); };"
"img.src = '" +
image_url.spec() + "';";
return content::ExecuteScriptAndExtractBool(tab, js_chrome, loaded);
}
private:
DISALLOW_COPY_AND_ASSIGN(InstantThemeTest);
};
IN_PROC_BROWSER_TEST_F(InstantThemeTest, ThemeBackgroundAccess) {
ASSERT_NO_FATAL_FAILURE(InstallThemeAndVerify("theme", "camo theme"));
ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
ui_test_utils::NavigateToURLWithDisposition(
browser(), GURL(chrome::kChromeUINewTabURL),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB |
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
// The "Instant" New Tab should have access to chrome-search: scheme but not
// chrome: scheme.
const GURL chrome_url("chrome://theme/IDR_THEME_NTP_BACKGROUND");
const GURL search_url("chrome-search://theme/IDR_THEME_NTP_BACKGROUND");
content::WebContents* tab =
browser()->tab_strip_model()->GetActiveWebContents();
bool loaded = false;
ASSERT_TRUE(LoadImage(tab, chrome_url, &loaded));
EXPECT_FALSE(loaded) << chrome_url;
ASSERT_TRUE(LoadImage(tab, search_url, &loaded));
EXPECT_TRUE(loaded) << search_url;
}
IN_PROC_BROWSER_TEST_F(InstantThemeTest, ThemeAppliedToExistingTab) {
// On the existing tab.
ASSERT_EQ(1, browser()->tab_strip_model()->count());
ASSERT_EQ(0, browser()->tab_strip_model()->active_index());
const std::string helper_js = "document.body.style.cssText";
TestThemeInfoObserver observer(
InstantServiceFactory::GetForProfile(browser()->profile()));
// Open new tab.
content::WebContents* active_tab =
local_ntp_test_utils::OpenNewTab(browser(), GURL("about:blank"));
local_ntp_test_utils::NavigateToNTPAndWaitUntilLoaded(browser());
ASSERT_EQ(2, browser()->tab_strip_model()->count());
ASSERT_EQ(1, browser()->tab_strip_model()->active_index());
observer.WaitForThemeApplied(false);
// Get the default (no theme) css setting
std::string original_css_text = "";
EXPECT_TRUE(instant_test_utils::GetStringFromJS(active_tab, helper_js,
&original_css_text));
// Open a new tab and install a theme on the new tab.
active_tab = local_ntp_test_utils::OpenNewTab(browser(), GURL("about:blank"));
local_ntp_test_utils::NavigateToNTPAndWaitUntilLoaded(browser());
ASSERT_EQ(3, browser()->tab_strip_model()->count());
ASSERT_EQ(2, browser()->tab_strip_model()->active_index());
ASSERT_NO_FATAL_FAILURE(InstallThemeAndVerify("theme", "camo theme"));
observer.WaitForThemeApplied(true);
// Get the current tab's theme CSS setting.
std::string css_text = "";
EXPECT_TRUE(
instant_test_utils::GetStringFromJS(active_tab, helper_js, &css_text));
// Switch to the previous tab.
browser()->tab_strip_model()->ActivateTabAt(1);
ASSERT_EQ(1, browser()->tab_strip_model()->active_index());
observer.WaitForThemeApplied(true);
// Get the previous tab's theme CSS setting.
std::string previous_tab_css_text = "";
EXPECT_TRUE(instant_test_utils::GetStringFromJS(active_tab, helper_js,
&previous_tab_css_text));
// The previous tab should also apply the new theme.
EXPECT_NE(original_css_text, css_text);
EXPECT_EQ(previous_tab_css_text, css_text);
}
IN_PROC_BROWSER_TEST_F(InstantThemeTest, ThemeAppliedToNewTab) {
// On the existing tab.
ASSERT_EQ(1, browser()->tab_strip_model()->count());
ASSERT_EQ(0, browser()->tab_strip_model()->active_index());
const std::string helper_js = "document.body.style.cssText";
TestThemeInfoObserver observer(
InstantServiceFactory::GetForProfile(browser()->profile()));
// Open new tab.
content::WebContents* active_tab =
local_ntp_test_utils::OpenNewTab(browser(), GURL("about:blank"));
local_ntp_test_utils::NavigateToNTPAndWaitUntilLoaded(browser());
observer.WaitForThemeApplied(false);
ASSERT_EQ(2, browser()->tab_strip_model()->count());
ASSERT_EQ(1, browser()->tab_strip_model()->active_index());
// Get the default (no theme) css setting
std::string original_css_text = "";
EXPECT_TRUE(instant_test_utils::GetStringFromJS(active_tab, helper_js,
&original_css_text));
// Install a theme on this tab.
ASSERT_NO_FATAL_FAILURE(InstallThemeAndVerify("theme", "camo theme"));
observer.WaitForThemeApplied(true);
// Get the current tab's theme CSS setting.
std::string css_text = "";
EXPECT_TRUE(
instant_test_utils::GetStringFromJS(active_tab, helper_js, &css_text));
// Open a new tab.
active_tab = local_ntp_test_utils::OpenNewTab(browser(), GURL("about:blank"));
local_ntp_test_utils::NavigateToNTPAndWaitUntilLoaded(browser());
observer.WaitForThemeApplied(true);
ASSERT_EQ(3, browser()->tab_strip_model()->count());
ASSERT_EQ(2, browser()->tab_strip_model()->active_index());
// Get the new tab's theme CSS setting.
std::string new_tab_css_text = "";
EXPECT_TRUE(instant_test_utils::GetStringFromJS(active_tab, helper_js,
&new_tab_css_text));
// The new tab should change the original theme and also apply the new theme.
EXPECT_NE(original_css_text, new_tab_css_text);
EXPECT_EQ(css_text, new_tab_css_text);
}
IN_PROC_BROWSER_TEST_F(InstantThemeTest, ThemeChangedWhenApplyingNewTheme) {
// On the existing tab.
ASSERT_EQ(1, browser()->tab_strip_model()->count());
ASSERT_EQ(0, browser()->tab_strip_model()->active_index());
const std::string helper_js = "document.body.style.cssText";
TestThemeInfoObserver observer(
InstantServiceFactory::GetForProfile(browser()->profile()));
// Open new tab.
content::WebContents* active_tab =
local_ntp_test_utils::OpenNewTab(browser(), GURL("about:blank"));
local_ntp_test_utils::NavigateToNTPAndWaitUntilLoaded(browser());
observer.WaitForThemeApplied(false);
ASSERT_EQ(2, browser()->tab_strip_model()->count());
ASSERT_EQ(1, browser()->tab_strip_model()->active_index());
// Get the default (no theme) css setting
std::string original_css_text = "";
EXPECT_TRUE(instant_test_utils::GetStringFromJS(active_tab, helper_js,
&original_css_text));
// install a theme on this tab.
ASSERT_NO_FATAL_FAILURE(InstallThemeAndVerify("theme", "camo theme"));
observer.WaitForThemeApplied(true);
// Get the current tab's theme CSS setting.
std::string css_text = "";
EXPECT_TRUE(
instant_test_utils::GetStringFromJS(active_tab, helper_js, &css_text));
// Install a different theme.
ASSERT_NO_FATAL_FAILURE(InstallThemeAndVerify("theme2", "snowflake theme"));
observer.WaitForThemeApplied(true);
// Get the current tab's theme CSS setting.
std::string new_css_text = "";
EXPECT_TRUE(instant_test_utils::GetStringFromJS(active_tab, helper_js,
&new_css_text));
// Confirm that the theme will take effect on the current tab when installing
// a new theme.
EXPECT_NE(original_css_text, css_text);
EXPECT_NE(css_text, new_css_text);
EXPECT_NE(original_css_text, new_css_text);
}
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
1443fcde15aabbacf587f07365df5ea6cbd1e7f1 | 833b0ad8f71cd1a2cd0a0f761edb059a86a79e55 | /BOJ/1000~/2455.cpp | 322b919221e0731815fac060b7aa4aed831bfe76 | [] | no_license | kin16742/Problem-Solving | 339c0be925eeaab82c2715bbcb571d32ffd00b8c | f549bdf05f16d3179fcc7a177378241b405db56e | refs/heads/master | 2022-12-28T14:29:58.613114 | 2020-10-07T12:24:47 | 2020-10-07T12:24:47 | 185,807,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 330 | cpp | #include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int main() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
int a, b, result = 0, people = 0;
for (int i = 0; i < 4; i++) {
cin >> a >> b;
people = people - a + b;
result = max(result, people);
}
cout << result << '\n';
return 0;
}
| [
"kin16742@naver.com"
] | kin16742@naver.com |
23be59e8658cc959eace12dbcd456402344c6c0f | 7ea45377de05a91d447687c53e1a836cfaec4b11 | /forces_code/con221/d.cpp | f1280decfc9b415ae84c440244ba9a03b04779e9 | [] | no_license | saikrishna17394/Code | d2b71efe5e3e932824339149008c3ea33dff6acb | 1213f951233a502ae6ecf2df337f340d8d65d498 | refs/heads/master | 2020-05-19T14:16:49.037709 | 2017-01-26T17:17:13 | 2017-01-26T17:17:13 | 24,478,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 770 | cpp | #include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <cstring>
#include <map>
using namespace std;
#define inf 99999999
typedef long long int lli;
typedef pair<int,int> ii;
char s[5010][5010];
int dp[5000][5000],n,m,ans,A[5000];
int main() {
// cin>>n>>m;
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++)
scanf("%s",s[i]);
for(int i=0;i<n;i++)
dp[i][m-1]=s[i][m-1]-'0';
for(int i=0;i<n;i++) {
for(int j=m-2;j>=0;j--) {
if(s[i][j]=='0')
dp[i][j]=0;
else
dp[i][j]=1+dp[i][j+1];
}
}
ans=0;
for(int j=0;j<m;j++) {
for(int i=0;i<n;i++) {
A[i]=dp[i][j];
}
sort(A,A+n);
for(int i=n-1;i>=0;i--) {
ans=max(ans,A[i]*(n-i));
}
}
// cout<<ans<<endl;
printf("%d\n", ans);
return 0;
} | [
"saikrishna17394@gmail.com"
] | saikrishna17394@gmail.com |
b85412dd32248222bc252ad00d9625e126bedd46 | 65cdc3ced737400cef283915d70d87fe42b70632 | /src/cGame.cpp | 19c8f9c20e3ba242d1afef1a8bc4b25e4a570a35 | [] | no_license | alexgg-developer/sdlbaseforgame | 1f2f5cc70557412ab30d58b5ea9d0994e2b0e0df | 1e16c9d7aa464d95d07d5483adabe949331f64f0 | refs/heads/master | 2020-03-30T04:35:32.781620 | 2014-05-08T21:25:10 | 2014-05-08T21:25:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,343 | cpp | #include "cGame.hpp"
#include "cTexture.hpp"
#include "vec3.hpp"
#include "cAnimation2D.hpp"
#include "cText.hpp"
#include "TypesDefined.hpp"
#include "SDL_ttf.h"
#include "SDL_mixer.h"
#include "cMusic.hpp"
#include "cSound.hpp"
#include <sstream>
Game::Game()
{}
int Game::init()
{
int error = initSDL();
if(error == 0) error = initGLEW();
if(error == 0) error = initGL();
return error;
}
int Game::initSDL()
{
int error = 0;
if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) < 0 )
{
std::cout << "SDL could not initialize! SDL_Error: " << SDL_GetError() << std::endl;
error = 1;
}
error = mWindow.init();
if(error == 0) {
if( TTF_Init() == -1 ) {
std::cout << "SDL_ttf could not initialize! SDL_ttf Error: " << TTF_GetError() << std::endl;
error = 4;
}
if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) {
std::cout << "SDL_mixer could not initialize! SDL_mixer Error: " << Mix_GetError();
error = 6;
}
}
return error;
}
int Game::initGLEW()
{
int error = 0;
glewExperimental = GL_TRUE;
GLenum glewError = glewInit();
if( glewError != GLEW_OK ) {
std::cout << "Error initializing GLEW! " << glewGetErrorString( glewError ) << std::endl;
error = 10;
}
return error;
}
int Game::initGL()
{
int error = 0;
if(!mRenderer.initGL() || !mRenderer.initApp()) {
error = 20;
}
return error;
}
int Game::quit()
{
mWindow.free();
mRenderer.free();
Mix_Quit();
TTF_Quit();
IMG_Quit();
SDL_Quit();
return 0;
}
int Game::main()
{
int error = init();
if(!error) {
uint frame = 0;
//mWindow.switchFullScreen();
mTimer.start();
while(!mInput.check(Input::KESC)) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if(event.type == SDL_WINDOWEVENT) {
mWindow.handleEvent(event);
if(mWindow.mMinimized) {
mTimer.pause();
}
else {
mTimer.resume();
}
}
else {
mInput.readWithScanCode(event);
}
}
if(!mWindow.mMinimized) {
glClearColor( 0.f, 0.f, 0.f, 1.f );
glClear( GL_COLOR_BUFFER_BIT );
mRenderer.render();
SDL_GL_SwapWindow( mWindow.mWindow );
}
}
error = quit();
}
else quit();
return error;
}
| [
"alexgg.developer@gmail.com"
] | alexgg.developer@gmail.com |
1508f3e698bacd4793a59f3acaa5091a638d2429 | 08234a09fbb5efc56ac886c1dcb0d6e68f680735 | /benchmarks/benchmark-tsv.cpp | 56ae150021d6849de55867bcb99429513995449b | [] | no_license | sramas15/snapr | d861f3a7d3329aaa296c6a73ec2498a5d1eaa004 | b873101d87d1081cbfec28ceffdaf33411da5773 | refs/heads/master | 2021-01-14T12:47:14.937481 | 2015-03-11T21:46:41 | 2015-03-11T21:46:41 | 25,495,610 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 466 | cpp | #include <stdio.h>
#include "Snap.h"
int main(int argc, char* argv[]) {
TFIn LoadF("attr/save-vec.bin");
double start = omp_get_wtime();
PNSparseNet Net = TNSparseNet::Load(LoadF);
double end = omp_get_wtime();
printf("Time to read from binary: %f\n", (end-start));
start = omp_get_wtime();
FILE *fp = fopen("attr/output-vec.tsv", "w");
Net->ConvertToTSV(fp, 1000);
end = omp_get_wtime();
printf("Time to convert to TSV: %f\n", (end-start));
}
| [
"ramasshe@cs.stanford.edu"
] | ramasshe@cs.stanford.edu |
890333a478a749b189477819261d9655c22a50dc | e5645099723739972ac8965819a6eb15e3d6d6b0 | /URI_Online_Judge/1136uri.cpp | cf199c1545eeac1f0c2bd6e953c1d3086f2a19bb | [] | no_license | arleyribeiro/Maratona | a3ab602bf025e4565a53af8c724f266fd7d0c989 | f60ae7f07d74e33683ea1b48e72770e3707e1874 | refs/heads/master | 2016-08-12T03:43:59.984403 | 2016-04-23T18:09:42 | 2016-04-23T18:09:42 | 55,017,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 495 | cpp | #include <bits/stdc++.h>
#define TAM 92
int main() {
int n=0,b=0,d;
while(scanf("%d %d",&n,&b)==2, n+b) {
int v[TAM]={0};
int bo[TAM]={0};
for(int i=0;i<b;i++) {
scanf("%d",&bo[i]); }
for(int i=0;i<b;i++){
for(int j=0;j<b;j++) {
d=abs(bo[i]-bo[j]);
if(!v[d]) {
v[d]=1;
}
}
}
int f=1;
for(int i=0;i<=n;i++){
if(!v[i]) {
f=0;
printf("N\n");
break;
}
}
if(f)
printf("Y\n");
}
return 0;
}
| [
"arley.sribeiro@gmail.com"
] | arley.sribeiro@gmail.com |
44d5470f9a69c2352894cc5fcee5d324a1f88358 | eb580526d1c04da0a1f3ed4146b9b68609cef3ea | /D/630.cpp | 9452914d5b118ab04d1f7a282befd7240a82324f | [] | no_license | bhaveshgawri/codeforces | bc34e7b688ee1e7ddc7efbdd758839454ba40524 | 22b8b7e0f3432051ddc1132b6bb84e0b25781347 | refs/heads/master | 2021-01-12T03:32:58.452769 | 2018-01-13T09:01:14 | 2018-01-13T09:01:14 | 78,229,124 | 0 | 1 | null | 2017-10-28T17:06:10 | 2017-01-06T18:31:40 | C++ | UTF-8 | C++ | false | false | 113 | cpp | #include <iostream>
int main(){
unsigned long long int n;
std::cin>>n;
std::cout<<3*n*n+3*n+1;
} | [
"4bhaveshgawri@gmail.com"
] | 4bhaveshgawri@gmail.com |
fb4b9cce15a058d278f4c1621d358aba606810cc | 2f0fa24dac268978f9fb24c9369d5127b898dfe8 | /Classes/SlitherMap.cpp | 95273dfe3dda40c9927ee69982ab5aa9da4e8c6e | [] | no_license | tomcat2088/slitherApp | fc2f7dea3a2719514afc20f50f884ab283eaf136 | b501e32505d265bfc6c26f5163124128e4a1cfb7 | refs/heads/master | 2016-09-13T09:33:34.559016 | 2016-05-31T15:58:35 | 2016-05-31T15:58:35 | 56,503,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 109 | cpp | //
// SlitherMap.cpp
// slitherApp
//
// Created by wangyang on 16/4/21.
//
//
#include "SlitherMap.hpp"
| [
"tomcat1991@126.com"
] | tomcat1991@126.com |
db6c8e41dfb571b9a639583604b5a6d126af5a10 | e47f3bc67c0dbfa194e7ec57044a8e16f2410200 | /ReservasHotel/sources/habitacion.hpp | 8d915ef2264ed7755ae14d339db7988abf17d420 | [
"MIT"
] | permissive | rocammo/object-oriented-programming-i | 5afee2b05b7c6495562512b7dd0f53e43a71e69b | e1c7b4c060e843d9358b501ab64a4d83d8bf2f89 | refs/heads/master | 2020-04-28T01:44:58.695737 | 2019-03-10T21:04:29 | 2019-03-10T21:04:29 | 174,869,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | hpp | /**
* habitacion.hpp
*
* @author: Rodrigo Casamayor <alu.89657@usj.es>
* @date: 14 ene. 2019
*/
#pragma once
class Habitacion {
private:
int plazas;
bool ocupada;
private:
long idHabitacion;
int numHabitacion;
public:
Habitacion();
int getPlazas() const;
void setPlazas(int plazas);
bool isOcupada() const;
void setOcupada(bool ocupada);
long getIdHabitacion() const;
void setIdHabitacion(int idHabitacion);
int getNumHabitacion() const;
void setNumHabitacion(int numHabitacion);
};
| [
"rodrigo.casamayor@gmail.com"
] | rodrigo.casamayor@gmail.com |
b608a829a99668b69478286f3cd72aa6fce9343f | aac5c40093e690689091844dd0bfe497a343a3cb | /EscalonadorEstruct.cpp | 910ce457bc3f02bb3c3199b6e9e9ce1e0c55d704 | [] | no_license | jlopezsa/escalonadorJulianTesteEscaClassMaq | 4d69d6a15b3ef6684a0dc8826d633ae488612d63 | e8df6770c128e91d2bf3469e7c13908946641f9e | refs/heads/master | 2020-09-21T05:54:18.320412 | 2019-11-28T17:32:29 | 2019-11-28T17:32:29 | 224,701,124 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,573 | cpp | #include <iostream>
#include <stdio.h>
#include <iomanip>
using namespace std;
#include "EscalonadorEstruct.h"
#include "Lista.cpp"
#include "Timer.cpp"
//template<typename TYPEFUNC,typename TASKTYPE,typename OBJECTTYPE>
EscalonadorEstruct::EscalonadorEstruct()
{
schedulerStates = 0;
};
//
//template<typename TYPEFUNC,typename TASKTYPE,typename OBJECTTYPE>
EscalonadorEstruct::~EscalonadorEstruct(){};
//
// Inicializa as entradas de todas as tarefas com 0
//template<typename TYPEFUNC,typename TASKTYPE,typename OBJECTTYPE>
void EscalonadorEstruct::init_Task_TimersStruct()
{
taskToSchedule.priorityID = 0;
taskToSchedule.ptrObject = NULL;
taskToSchedule.task = NULL;
taskToSchedule.ready = 0;
taskToSchedule.delay = 0;
taskToSchedule.period = 0;
taskToSchedule.enabled = 0;
taskToSchedule.io_status = 0;
//
runningTask.priorityID = 0;
runningTask.ptrObject = NULL;
runningTask.task = NULL;
runningTask.ready = 0;
runningTask.delay = 0;
runningTask.period = 0;
runningTask.enabled = 0;
runningTask.io_status = 0;
};
//
//
//
int EscalonadorEstruct::addTaskReadyEstruct(void (MaquinaRefri::*task)(void), MaquinaRefri *newObject, int time, int priority)
{
/* Verifica se a prioridade é válida */
/* Verifica se sobre-escreve uma tarefa escalonada */
/* Escalona a tarefa */
taskToSchedule.priorityID = priority;
taskToSchedule.ptrObject = newObject;
taskToSchedule.task = task;
taskToSchedule.ready = 0;
taskToSchedule.delay = time;
taskToSchedule.period = time;
taskToSchedule.enabled = 1;
readyEstruct.insertionSort(taskToSchedule);
return 1;
}
//
//
//
int EscalonadorEstruct::removeTask(void (MaquinaRefri::*task)(void), MaquinaRefri *newObject)
{
readyEstruct.removeFirst();
return 1;
}
//
//
//
void EscalonadorEstruct::Run_RTC_SchedulerEstruct()
{ // Sempre executando
int i;
//GBL_run_scheduler = 1;
while (1)
{ // Laço infinito; verifica cada tarefa
if ((runningTask.task != NULL) &&
// Verifica se habilitada
(runningTask.enabled == 1) &&
// Verifica se está pronta para executar
(runningTask.ready == 1))
{ // se (task!=NULL & enable==1 & ready==1)
cout << "\n\n\t\tFLAG TEST: into RUN Scheduler <" << setfill('-') << setw(50) << "Execut function" << endl;
//(pT->*GBL_task_table[i].task)(); // Executa a tarefa
(runningTask.ptrObject->*runningTask.task)(); // <<<<<<<< Executa a tarefa
runningTask.ready = 0;
break;
} // if
tick_timer_intrStruct();
objTimer.start(1);
} // while 1
}
//
//
//
#pragma INTERRUPT tick_timer_intr
void EscalonadorEstruct::tick_timer_intrStruct(void)
{
//cout << "FLAG TEST: into tick_timer_intr 0000000" << endl;
//static char i;
int i;
//cout << "\t\tDelay task 0: " << setfill(' ') << setw(2) << runningTask.delay << endl;
//cout << "FLAG TEST: into tick_timer_intr for " << i << endl;
if ((runningTask.task != NULL) && //Se for escalonada
(runningTask.enabled == 1) &&
(runningTask.delay != 0))
{ // se (task!=NULL & enable==1 & delay!=0)
//cout << "FLAG TEST: into tick_timer_intr if 1 delay: " << GBL_task_table[i].delay << endl;
runningTask.delay--; // delay Decrementa
if (runningTask.delay == 0)
{
//cout << "FLAG TEST: into tick_timer_intr 2" << endl;
runningTask.ready = 1; // ready = 1
runningTask.delay = runningTask.period;
} // if delay == 0
} // if
}
//
//
//
void EscalonadorEstruct::schedulerStatesLogic()
{
int toStart;
switch (schedulerStates)
{
case 0: // created
//cout << "CREATED: Aperte tecla para iniciar: ";
//cin >> toStart;
schedulerStates = 2;
break;
case 1: // ready
//cout << "READY: aperte tecla para continuar: ";
//if (readyEstruct.readFirst().priorityID >= runningTask.priorityID) // if priReady > priRunning
schedulerStates = 2;
//cin >> toStart;
break;
case 2: // running
//cout << "RUNNING 1: state\n";
runningTask = readyEstruct.readFirst();
readyEstruct.removeFirst();
printf("\e[H\e[2J");
Run_RTC_SchedulerEstruct();
if (runningTask.ready == 0)// && runningTask.io_status == 0)
schedulerStates = 4;
// executing task
// while priRunning > priReady || delay > 0
// delay --
// if priRunning < pryReady && delay > 0
// schedulerStates = 1
// if delay == 0
// schedulerStates = 4
// if ???? para ir no waiting
break;
case 3: // waiting
break;
case 4: // terminated
cout << "TERMINATED: \n";
terminatedTask = runningTask;
schedulerStates = 2;
break;
default:
break;
}
}
/*
void EscalonadorEstruct::Run_RTC_Scheduler()
{ // Sempre executando
int i;
//GBL_run_scheduler = 1;
while (1)
{ // Laço infinito; verifica cada tarefa
for (i = 0; i < MAX_TASKS; i++)
{ // Se essa for uma tarefa escalonada valida
if ((GBL_task_table[i].task != NULL) &&
// Verifica se habilitada
(GBL_task_table[i].enabled == 1) &&
// Verifica se está pronta para executar
(GBL_task_table[i].ready == 1))
{ // se (task!=NULL & enable==1 & ready==1)
cout << "\n\n\t\tFLAG TEST: into RUN Scheduler <" << setfill('-') << setw(50) << "Execut function" << endl;
//(pT->*GBL_task_table[i].task)(); // Executa a tarefa
(GBL_task_table[i].ptrObject->*GBL_task_table[i].task)(); // Executa a tarefa
GBL_task_table[i].ready = 0;
break;
} // if
} // for i
tick_timer_intr();
objTimer.start(1);
} // while 1
}
*/
//
/*
void Escalonador::addTask(void (*task)(void), int time, int priority)
int EscalonadorEstruct::addTask(void (MaquinaRefri::*task)(void), MaquinaRefri *newObject, int time, int priority)
{
}
*/
//
//
//
//
//
//template<typename TYPEFUNC,typename TASKTYPE,typename OBJECTTYPE>
/*
void EscalonadorEstruct::Enable_Task(int task_number)
{
GBL_task_table[task_number].enabled = 1;
}
*/
//
//
//
//template<typename TYPEFUNC,typename TASKTYPE,typename OBJECTTYPE>
/*
void EscalonadorEstruct::Disable_Task(int task_number)
{
GBL_task_table[task_number].enabled = 0;
}
*/
//
//
/*declara uma função que será uma rotina de serviço
de interrupção (ISR - Interrupt Service Routine) de prioridade alta*/
//template<typename TYPEFUNC,typename TASKTYPE,typename OBJECTTYPE>
/*
#pragma INTERRUPT tick_timer_intr
void EscalonadorEstruct::tick_timer_intr(void)
{
//cout << "FLAG TEST: into tick_timer_intr 0000000" << endl;
//static char i;
int i;
cout << "\t\tDelay task 0: " << setfill(' ') << setw(2) << GBL_task_table[0].delay;
cout << "\tDelay task 1: " << setfill(' ') << setw(2) << GBL_task_table[1].delay;
cout << "\tDelay task 2: " << GBL_task_table[2].delay << endl;
//cout << endl;
for (i = 0; i < MAX_TASKS; i++)
{
//cout << "FLAG TEST: into tick_timer_intr for " << i << endl;
if ((GBL_task_table[i].task != NULL) && //Se for escalonada
(GBL_task_table[i].enabled == 1) &&
(GBL_task_table[i].delay != 0))
{ // se (task!=NULL & enable==1 & delay!=0)
//cout << "FLAG TEST: into tick_timer_intr if 1 delay: " << GBL_task_table[i].delay << endl;
GBL_task_table[i].delay--; // delay Decrementa
if (GBL_task_table[i].delay == 0)
{
//cout << "FLAG TEST: into tick_timer_intr 2" << endl;
GBL_task_table[i].ready = 1; // ready = 1
GBL_task_table[i].delay = GBL_task_table[i].period;
} // if delay == 0
} // if
} // for
}
*/
//
//
//
//template<typename TYPEFUNC,typename TASKTYPE,typename OBJECTTYPE>
void EscalonadorEstruct::Request_Task_Run()
{
taskToSchedule.ready = 1;
}
//
//
//
// | [
"jlopezsa@gmail.com"
] | jlopezsa@gmail.com |
97289ac790d13a19f7ab578edcd3386a255569c8 | 48da32f6a426262cc2c8107f7e31c9d62ffb619b | /main.cpp | 24f64717060034bc945a928102953587ae3c8316 | [] | no_license | Garcia6l20/qtsignalgraph | afbeddcaa2a1dab3d0188aabf82e2c14601c3fcd | 3cd065a1bde9255f6a0dce733d69e858cf049557 | refs/heads/master | 2020-09-30T00:36:45.914262 | 2019-12-17T18:38:38 | 2019-12-17T18:38:38 | 227,157,779 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | cpp | // Copyright (c) 2019 Schneider-Electric. All rights reserved.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}
| [
"garcia.6l20@gmail.com"
] | garcia.6l20@gmail.com |
306fa7907dcf8dad4a707e085706d9f3ada99843 | b5c338541fb8102293d4f93d1ba18d86e0a6dec9 | /main/src/Math/Matrix.h | 0b7ff6dd78b87b84a17aac16d9c8df26b1bba602 | [] | no_license | robinvierich/engine | e894870e2559b9b862cdfc92975cc022681b3816 | e5cccdbac1e4d824b4047251286533f67950163d | refs/heads/master | 2021-01-10T04:23:57.133209 | 2017-11-06T00:58:05 | 2017-11-06T00:58:05 | 49,519,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 604 | h | #pragma once
#include "Math/Vector.h"
class Matrix4
{
private:
Vector4 m_columns[4];
const static Matrix4 s_identity;
public:
static const Matrix4& Identity() { return s_identity; }
static Matrix4 Matrix4::CreateProjectionMatrix(const float fov, const float farPlane, const float nearPlane);
Matrix4()
: m_columns{}
{
}
Matrix4(Vector4& col0, Vector4& col1, Vector4& col2, Vector4& col3)
: m_columns{ col0, col1, col2, col3 }
{
}
const inline float& operator[](uint32 i) const
{
return m_columns[i / 4][i % 4];
}
};
| [
"robinvierich@gmail.com"
] | robinvierich@gmail.com |
266d94774bcb32a0b78bb999ebfffa8fe0ea2b6b | baa9fffc817a2a993d4ecc774d3f277783308c20 | /test/gtest/common/googletest/gtest-matchers.h | f28d10eafabad8fc44fa11875d0ff72d9e24aed6 | [
"BSD-3-Clause"
] | permissive | openucx/ucx | 9a0f2205295afbdf3cff14b5d24af781b123f5ea | 73a48700badb7cbace64d94b82f408e2a26fca32 | refs/heads/master | 2023-09-01T16:51:26.913950 | 2023-09-01T13:02:25 | 2023-09-01T13:02:25 | 25,379,390 | 966 | 420 | NOASSERTION | 2023-09-14T12:29:35 | 2014-10-17T22:17:24 | C | UTF-8 | C++ | false | false | 27,021 | h | // Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// The Google C++ Testing and Mocking Framework (Google Test)
//
// This file implements just enough of the matcher interface to allow
// EXPECT_DEATH and friends to accept a matcher argument.
// IWYU pragma: private, include "testing/base/public/gunit.h"
// IWYU pragma: friend third_party/googletest/googlemock/.*
// IWYU pragma: friend third_party/googletest/googletest/.*
#ifndef GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
#define GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
#include <memory>
#include <ostream>
#include <string>
#include <type_traits>
#include "gtest-printers.h"
#include "internal/gtest-internal.h"
#include "internal/gtest-port.h"
// MSVC warning C5046 is new as of VS2017 version 15.8.
#if defined(_MSC_VER) && _MSC_VER >= 1915
#define GTEST_MAYBE_5046_ 5046
#else
#define GTEST_MAYBE_5046_
#endif
GTEST_DISABLE_MSC_WARNINGS_PUSH_(
4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
clients of class B */
/* Symbol involving type with internal linkage not defined */)
namespace testing {
// To implement a matcher Foo for type T, define:
// 1. a class FooMatcherImpl that implements the
// MatcherInterface<T> interface, and
// 2. a factory function that creates a Matcher<T> object from a
// FooMatcherImpl*.
//
// The two-level delegation design makes it possible to allow a user
// to write "v" instead of "Eq(v)" where a Matcher is expected, which
// is impossible if we pass matchers by pointers. It also eases
// ownership management as Matcher objects can now be copied like
// plain values.
// MatchResultListener is an abstract class. Its << operator can be
// used by a matcher to explain why a value matches or doesn't match.
//
class MatchResultListener {
public:
// Creates a listener object with the given underlying ostream. The
// listener does not own the ostream, and does not dereference it
// in the constructor or destructor.
explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
virtual ~MatchResultListener() = 0; // Makes this class abstract.
// Streams x to the underlying ostream; does nothing if the ostream
// is NULL.
template <typename T>
MatchResultListener& operator<<(const T& x) {
if (stream_ != nullptr) *stream_ << x;
return *this;
}
// Returns the underlying ostream.
::std::ostream* stream() { return stream_; }
// Returns true if and only if the listener is interested in an explanation
// of the match result. A matcher's MatchAndExplain() method can use
// this information to avoid generating the explanation when no one
// intends to hear it.
bool IsInterested() const { return stream_ != nullptr; }
private:
::std::ostream* const stream_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
};
inline MatchResultListener::~MatchResultListener() {
}
// An instance of a subclass of this knows how to describe itself as a
// matcher.
class MatcherDescriberInterface {
public:
virtual ~MatcherDescriberInterface() {}
// Describes this matcher to an ostream. The function should print
// a verb phrase that describes the property a value matching this
// matcher should have. The subject of the verb phrase is the value
// being matched. For example, the DescribeTo() method of the Gt(7)
// matcher prints "is greater than 7".
virtual void DescribeTo(::std::ostream* os) const = 0;
// Describes the negation of this matcher to an ostream. For
// example, if the description of this matcher is "is greater than
// 7", the negated description could be "is not greater than 7".
// You are not required to override this when implementing
// MatcherInterface, but it is highly advised so that your matcher
// can produce good error messages.
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "not (";
DescribeTo(os);
*os << ")";
}
};
// The implementation of a matcher.
template <typename T>
class MatcherInterface : public MatcherDescriberInterface {
public:
// Returns true if and only if the matcher matches x; also explains the
// match result to 'listener' if necessary (see the next paragraph), in
// the form of a non-restrictive relative clause ("which ...",
// "whose ...", etc) that describes x. For example, the
// MatchAndExplain() method of the Pointee(...) matcher should
// generate an explanation like "which points to ...".
//
// Implementations of MatchAndExplain() should add an explanation of
// the match result *if and only if* they can provide additional
// information that's not already present (or not obvious) in the
// print-out of x and the matcher's description. Whether the match
// succeeds is not a factor in deciding whether an explanation is
// needed, as sometimes the caller needs to print a failure message
// when the match succeeds (e.g. when the matcher is used inside
// Not()).
//
// For example, a "has at least 10 elements" matcher should explain
// what the actual element count is, regardless of the match result,
// as it is useful information to the reader; on the other hand, an
// "is empty" matcher probably only needs to explain what the actual
// size is when the match fails, as it's redundant to say that the
// size is 0 when the value is already known to be empty.
//
// You should override this method when defining a new matcher.
//
// It's the responsibility of the caller (Google Test) to guarantee
// that 'listener' is not NULL. This helps to simplify a matcher's
// implementation when it doesn't care about the performance, as it
// can talk to 'listener' without checking its validity first.
// However, in order to implement dummy listeners efficiently,
// listener->stream() may be NULL.
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
// Inherits these methods from MatcherDescriberInterface:
// virtual void DescribeTo(::std::ostream* os) const = 0;
// virtual void DescribeNegationTo(::std::ostream* os) const;
};
namespace internal {
// Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
template <typename T>
class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
public:
explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
: impl_(impl) {}
~MatcherInterfaceAdapter() override { delete impl_; }
void DescribeTo(::std::ostream* os) const override { impl_->DescribeTo(os); }
void DescribeNegationTo(::std::ostream* os) const override {
impl_->DescribeNegationTo(os);
}
bool MatchAndExplain(const T& x,
MatchResultListener* listener) const override {
return impl_->MatchAndExplain(x, listener);
}
private:
const MatcherInterface<T>* const impl_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
};
struct AnyEq {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a == b; }
};
struct AnyNe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a != b; }
};
struct AnyLt {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a < b; }
};
struct AnyGt {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a > b; }
};
struct AnyLe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a <= b; }
};
struct AnyGe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a >= b; }
};
// A match result listener that ignores the explanation.
class DummyMatchResultListener : public MatchResultListener {
public:
DummyMatchResultListener() : MatchResultListener(nullptr) {}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
};
// A match result listener that forwards the explanation to a given
// ostream. The difference between this and MatchResultListener is
// that the former is concrete.
class StreamMatchResultListener : public MatchResultListener {
public:
explicit StreamMatchResultListener(::std::ostream* os)
: MatchResultListener(os) {}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
};
// An internal class for implementing Matcher<T>, which will derive
// from it. We put functionalities common to all Matcher<T>
// specializations here to avoid code duplication.
template <typename T>
class MatcherBase {
public:
// Returns true if and only if the matcher matches x; also explains the
// match result to 'listener'.
bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
return impl_->MatchAndExplain(x, listener);
}
// Returns true if and only if this matcher matches x.
bool Matches(const T& x) const {
DummyMatchResultListener dummy;
return MatchAndExplain(x, &dummy);
}
// Describes this matcher to an ostream.
void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
// Describes the negation of this matcher to an ostream.
void DescribeNegationTo(::std::ostream* os) const {
impl_->DescribeNegationTo(os);
}
// Explains why x matches, or doesn't match, the matcher.
void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
StreamMatchResultListener listener(os);
MatchAndExplain(x, &listener);
}
// Returns the describer for this matcher object; retains ownership
// of the describer, which is only guaranteed to be alive when
// this matcher object is alive.
const MatcherDescriberInterface* GetDescriber() const {
return impl_.get();
}
protected:
MatcherBase() {}
// Constructs a matcher from its implementation.
explicit MatcherBase(const MatcherInterface<const T&>* impl) : impl_(impl) {}
template <typename U>
explicit MatcherBase(
const MatcherInterface<U>* impl,
typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
nullptr)
: impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
MatcherBase(const MatcherBase&) = default;
MatcherBase& operator=(const MatcherBase&) = default;
MatcherBase(MatcherBase&&) = default;
MatcherBase& operator=(MatcherBase&&) = default;
virtual ~MatcherBase() {}
private:
std::shared_ptr<const MatcherInterface<const T&>> impl_;
};
} // namespace internal
// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
// object that can check whether a value of type T matches. The
// implementation of Matcher<T> is just a std::shared_ptr to const
// MatcherInterface<T>. Don't inherit from Matcher!
template <typename T>
class Matcher : public internal::MatcherBase<T> {
public:
// Constructs a null matcher. Needed for storing Matcher objects in STL
// containers. A default-constructed matcher is not yet initialized. You
// cannot use it until a valid value has been assigned to it.
explicit Matcher() {} // NOLINT
// Constructs a matcher from its implementation.
explicit Matcher(const MatcherInterface<const T&>* impl)
: internal::MatcherBase<T>(impl) {}
template <typename U>
explicit Matcher(
const MatcherInterface<U>* impl,
typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
nullptr)
: internal::MatcherBase<T>(impl) {}
// Implicit constructor here allows people to write
// EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
Matcher(T value); // NOLINT
};
// The following two specializations allow the user to write str
// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
// matcher is expected.
template <>
class GTEST_API_ Matcher<const std::string&>
: public internal::MatcherBase<const std::string&> {
public:
Matcher() {}
explicit Matcher(const MatcherInterface<const std::string&>* impl)
: internal::MatcherBase<const std::string&>(impl) {}
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object.
Matcher(const std::string& s); // NOLINT
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
};
template <>
class GTEST_API_ Matcher<std::string>
: public internal::MatcherBase<std::string> {
public:
Matcher() {}
explicit Matcher(const MatcherInterface<const std::string&>* impl)
: internal::MatcherBase<std::string>(impl) {}
explicit Matcher(const MatcherInterface<std::string>* impl)
: internal::MatcherBase<std::string>(impl) {}
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a string object.
Matcher(const std::string& s); // NOLINT
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
};
#if GTEST_HAS_ABSL
// The following two specializations allow the user to write str
// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
// matcher is expected.
template <>
class GTEST_API_ Matcher<const absl::string_view&>
: public internal::MatcherBase<const absl::string_view&> {
public:
Matcher() {}
explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
: internal::MatcherBase<const absl::string_view&>(impl) {}
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object.
Matcher(const std::string& s); // NOLINT
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
// Allows the user to pass absl::string_views directly.
Matcher(absl::string_view s); // NOLINT
};
template <>
class GTEST_API_ Matcher<absl::string_view>
: public internal::MatcherBase<absl::string_view> {
public:
Matcher() {}
explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
: internal::MatcherBase<absl::string_view>(impl) {}
explicit Matcher(const MatcherInterface<absl::string_view>* impl)
: internal::MatcherBase<absl::string_view>(impl) {}
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object.
Matcher(const std::string& s); // NOLINT
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
// Allows the user to pass absl::string_views directly.
Matcher(absl::string_view s); // NOLINT
};
#endif // GTEST_HAS_ABSL
// Prints a matcher in a human-readable format.
template <typename T>
std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
matcher.DescribeTo(&os);
return os;
}
// The PolymorphicMatcher class template makes it easy to implement a
// polymorphic matcher (i.e. a matcher that can match values of more
// than one type, e.g. Eq(n) and NotNull()).
//
// To define a polymorphic matcher, a user should provide an Impl
// class that has a DescribeTo() method and a DescribeNegationTo()
// method, and define a member function (or member function template)
//
// bool MatchAndExplain(const Value& value,
// MatchResultListener* listener) const;
//
// See the definition of NotNull() for a complete example.
template <class Impl>
class PolymorphicMatcher {
public:
explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
// Returns a mutable reference to the underlying matcher
// implementation object.
Impl& mutable_impl() { return impl_; }
// Returns an immutable reference to the underlying matcher
// implementation object.
const Impl& impl() const { return impl_; }
template <typename T>
operator Matcher<T>() const {
return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
}
private:
template <typename T>
class MonomorphicImpl : public MatcherInterface<T> {
public:
explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); }
virtual void DescribeNegationTo(::std::ostream* os) const {
impl_.DescribeNegationTo(os);
}
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
return impl_.MatchAndExplain(x, listener);
}
private:
const Impl impl_;
};
Impl impl_;
};
// Creates a matcher from its implementation.
// DEPRECATED: Especially in the generic code, prefer:
// Matcher<T>(new MyMatcherImpl<const T&>(...));
//
// MakeMatcher may create a Matcher that accepts its argument by value, which
// leads to unnecessary copies & lack of support for non-copyable types.
template <typename T>
inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
return Matcher<T>(impl);
}
// Creates a polymorphic matcher from its implementation. This is
// easier to use than the PolymorphicMatcher<Impl> constructor as it
// doesn't require you to explicitly write the template argument, e.g.
//
// MakePolymorphicMatcher(foo);
// vs
// PolymorphicMatcher<TypeOfFoo>(foo);
template <class Impl>
inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
return PolymorphicMatcher<Impl>(impl);
}
namespace internal {
// Implements a matcher that compares a given value with a
// pre-supplied value using one of the ==, <=, <, etc, operators. The
// two values being compared don't have to have the same type.
//
// The matcher defined here is polymorphic (for example, Eq(5) can be
// used to match an int, a short, a double, etc). Therefore we use
// a template type conversion operator in the implementation.
//
// The following template definition assumes that the Rhs parameter is
// a "bare" type (i.e. neither 'const T' nor 'T&').
template <typename D, typename Rhs, typename Op>
class ComparisonBase {
public:
explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
template <typename Lhs>
operator Matcher<Lhs>() const {
return Matcher<Lhs>(new Impl<const Lhs&>(rhs_));
}
private:
template <typename T>
static const T& Unwrap(const T& v) { return v; }
template <typename T>
static const T& Unwrap(std::reference_wrapper<T> v) { return v; }
template <typename Lhs, typename = Rhs>
class Impl : public MatcherInterface<Lhs> {
public:
explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
bool MatchAndExplain(Lhs lhs,
MatchResultListener* /* listener */) const override {
return Op()(lhs, Unwrap(rhs_));
}
void DescribeTo(::std::ostream* os) const override {
*os << D::Desc() << " ";
UniversalPrint(Unwrap(rhs_), os);
}
void DescribeNegationTo(::std::ostream* os) const override {
*os << D::NegatedDesc() << " ";
UniversalPrint(Unwrap(rhs_), os);
}
private:
Rhs rhs_;
};
Rhs rhs_;
};
template <typename Rhs>
class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
public:
explicit EqMatcher(const Rhs& rhs)
: ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
static const char* Desc() { return "is equal to"; }
static const char* NegatedDesc() { return "isn't equal to"; }
};
template <typename Rhs>
class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
public:
explicit NeMatcher(const Rhs& rhs)
: ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
static const char* Desc() { return "isn't equal to"; }
static const char* NegatedDesc() { return "is equal to"; }
};
template <typename Rhs>
class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
public:
explicit LtMatcher(const Rhs& rhs)
: ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
static const char* Desc() { return "is <"; }
static const char* NegatedDesc() { return "isn't <"; }
};
template <typename Rhs>
class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
public:
explicit GtMatcher(const Rhs& rhs)
: ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
static const char* Desc() { return "is >"; }
static const char* NegatedDesc() { return "isn't >"; }
};
template <typename Rhs>
class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
public:
explicit LeMatcher(const Rhs& rhs)
: ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
static const char* Desc() { return "is <="; }
static const char* NegatedDesc() { return "isn't <="; }
};
template <typename Rhs>
class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
public:
explicit GeMatcher(const Rhs& rhs)
: ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
static const char* Desc() { return "is >="; }
static const char* NegatedDesc() { return "isn't >="; }
};
// Implements polymorphic matchers MatchesRegex(regex) and
// ContainsRegex(regex), which can be used as a Matcher<T> as long as
// T can be converted to a string.
class MatchesRegexMatcher {
public:
MatchesRegexMatcher(const RE* regex, bool full_match)
: regex_(regex), full_match_(full_match) {}
#if GTEST_HAS_ABSL
bool MatchAndExplain(const absl::string_view& s,
MatchResultListener* listener) const {
return MatchAndExplain(std::string(s), listener);
}
#endif // GTEST_HAS_ABSL
// Accepts pointer types, particularly:
// const char*
// char*
// const wchar_t*
// wchar_t*
template <typename CharType>
bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
return s != nullptr && MatchAndExplain(std::string(s), listener);
}
// Matches anything that can convert to std::string.
//
// This is a template, not just a plain function with const std::string&,
// because absl::string_view has some interfering non-explicit constructors.
template <class MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const {
const std::string& s2(s);
return full_match_ ? RE::FullMatch(s2, *regex_)
: RE::PartialMatch(s2, *regex_);
}
void DescribeTo(::std::ostream* os) const {
*os << (full_match_ ? "matches" : "contains") << " regular expression ";
UniversalPrinter<std::string>::Print(regex_->pattern(), os);
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "doesn't " << (full_match_ ? "match" : "contain")
<< " regular expression ";
UniversalPrinter<std::string>::Print(regex_->pattern(), os);
}
private:
const std::shared_ptr<const RE> regex_;
const bool full_match_;
};
} // namespace internal
// Matches a string that fully matches regular expression 'regex'.
// The matcher takes ownership of 'regex'.
inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
const internal::RE* regex) {
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
}
inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
const std::string& regex) {
return MatchesRegex(new internal::RE(regex));
}
// Matches a string that contains regular expression 'regex'.
// The matcher takes ownership of 'regex'.
inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
const internal::RE* regex) {
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
}
inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
const std::string& regex) {
return ContainsRegex(new internal::RE(regex));
}
// Creates a polymorphic matcher that matches anything equal to x.
// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
// wouldn't compile.
template <typename T>
inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
// Constructs a Matcher<T> from a 'value' of type T. The constructed
// matcher matches any value that's equal to 'value'.
template <typename T>
Matcher<T>::Matcher(T value) { *this = Eq(value); }
// Creates a monomorphic matcher that matches anything with type Lhs
// and equal to rhs. A user may need to use this instead of Eq(...)
// in order to resolve an overloading ambiguity.
//
// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
// or Matcher<T>(x), but more readable than the latter.
//
// We could define similar monomorphic matchers for other comparison
// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
// it yet as those are used much less than Eq() in practice. A user
// can always write Matcher<T>(Lt(5)) to be explicit about the type,
// for example.
template <typename Lhs, typename Rhs>
inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
// Creates a polymorphic matcher that matches anything >= x.
template <typename Rhs>
inline internal::GeMatcher<Rhs> Ge(Rhs x) {
return internal::GeMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches anything > x.
template <typename Rhs>
inline internal::GtMatcher<Rhs> Gt(Rhs x) {
return internal::GtMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches anything <= x.
template <typename Rhs>
inline internal::LeMatcher<Rhs> Le(Rhs x) {
return internal::LeMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches anything < x.
template <typename Rhs>
inline internal::LtMatcher<Rhs> Lt(Rhs x) {
return internal::LtMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches anything != x.
template <typename Rhs>
inline internal::NeMatcher<Rhs> Ne(Rhs x) {
return internal::NeMatcher<Rhs>(x);
}
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
#endif // GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
| [
"lgenkin@nvidia.com"
] | lgenkin@nvidia.com |
18bfb159b1f6190a516119da4d34b3468af048d6 | b54847ee4898fb3272a38daabf60d1a02646dd05 | /exams/exam_part2/Button.h | b87b74fd22cde26e886581b871293249c483d61c | [] | no_license | IvanFilipov/FMI-OOP | 4d7b97e92b14949d6edf269bedef95d0b86ed97d | 92a8c5a8cf1e73f3da640928c46965affba7e57e | refs/heads/master | 2023-04-21T10:13:18.911124 | 2018-06-05T10:57:08 | 2018-06-05T10:57:08 | 52,727,858 | 19 | 9 | null | 2023-04-06T23:14:31 | 2016-02-28T15:27:39 | C++ | UTF-8 | C++ | false | false | 231 | h | #pragma once
#include "Element.h"
class Button : public Element{
public:
Button(const char*);
Button(const Button&);
Button& operator= (const Button&);
virtual const char* convertToHtml();
virtual Element* clone();
};
| [
"vanaka1189@gmail.com"
] | vanaka1189@gmail.com |
25ed7c4738159902023acc11edec4cb66ebad103 | db04ecf258aef8a187823b8e47f4a1ae908e5897 | /Cplus/LastMomentBeforeAllAntsFallOutofaPlank.cpp | 03a60ce5fb3324f2e9ee69a7d4c4f3bf5e1c5e94 | [
"MIT"
] | permissive | JumHorn/leetcode | 9612a26e531ceae7f25e2a749600632da6882075 | abf145686dcfac860b0f6b26a04e3edd133b238c | refs/heads/master | 2023-08-03T21:12:13.945602 | 2023-07-30T07:00:50 | 2023-07-30T07:00:50 | 74,735,489 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 405 | cpp | #include <algorithm>
#include <vector>
using namespace std;
class Solution
{
public:
int getLastMoment(int n, vector<int> &left, vector<int> &right)
{
int res = 0, l = 0, r = 0;
if (!left.empty())
{
l = *max_element(left.begin(), left.end());
res = max(res, l);
}
if (!right.empty())
{
r = *min_element(right.begin(), right.end());
res = max(res, n - r);
}
return res;
}
}; | [
"JumHorn@gmail.com"
] | JumHorn@gmail.com |
fd8e8d9f0a038c6bbbf3f6209580f9a5b1431a84 | 7e791eccdc4d41ba225a90b3918ba48e356fdd78 | /chromium/src/mojo/edk/test/multiprocess_test_helper.cc | 0490119abbc227a32bdedcccd05c685379e7b834 | [
"BSD-3-Clause"
] | permissive | WiViClass/cef-3.2623 | 4e22b763a75e90d10ebf9aa3ea9a48a3d9ccd885 | 17fe881e9e481ef368d9f26e903e00a6b7bdc018 | refs/heads/master | 2021-01-25T04:38:14.941623 | 2017-06-09T07:37:43 | 2017-06-09T07:37:43 | 93,824,379 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,037 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "mojo/edk/test/multiprocess_test_helper.h"
#include <utility>
#include "base/command_line.h"
#include "base/logging.h"
#include "base/process/kill.h"
#include "base/process/process_handle.h"
#include "build/build_config.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/platform_channel_pair.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
namespace mojo {
namespace edk {
namespace test {
const char kBrokerHandleSwitch[] = "broker-handle";
MultiprocessTestHelper::MultiprocessTestHelper() {
platform_channel_pair_.reset(new PlatformChannelPair());
server_platform_handle = platform_channel_pair_->PassServerHandle();
broker_platform_channel_pair_.reset(new PlatformChannelPair());
}
MultiprocessTestHelper::~MultiprocessTestHelper() {
CHECK(!test_child_.IsValid());
server_platform_handle.reset();
platform_channel_pair_.reset();
}
void MultiprocessTestHelper::StartChild(const std::string& test_child_name) {
StartChildWithExtraSwitch(test_child_name, std::string(), std::string());
}
void MultiprocessTestHelper::StartChildWithExtraSwitch(
const std::string& test_child_name,
const std::string& switch_string,
const std::string& switch_value) {
CHECK(platform_channel_pair_);
CHECK(!test_child_name.empty());
CHECK(!test_child_.IsValid());
std::string test_child_main = test_child_name + "TestChildMain";
base::CommandLine command_line(
base::GetMultiProcessTestChildBaseCommandLine());
HandlePassingInformation handle_passing_info;
platform_channel_pair_->PrepareToPassClientHandleToChildProcess(
&command_line, &handle_passing_info);
std::string broker_handle = broker_platform_channel_pair_->
PrepareToPassClientHandleToChildProcessAsString(&handle_passing_info);
command_line.AppendSwitchASCII(kBrokerHandleSwitch, broker_handle);
if (!switch_string.empty()) {
CHECK(!command_line.HasSwitch(switch_string));
if (!switch_value.empty())
command_line.AppendSwitchASCII(switch_string, switch_value);
else
command_line.AppendSwitch(switch_string);
}
base::LaunchOptions options;
#if defined(OS_POSIX)
options.fds_to_remap = &handle_passing_info;
#elif defined(OS_WIN)
options.start_hidden = true;
if (base::win::GetVersion() >= base::win::VERSION_VISTA)
options.handles_to_inherit = &handle_passing_info;
else
options.inherit_handles = true;
#else
#error "Not supported yet."
#endif
test_child_ =
base::SpawnMultiProcessTestChild(test_child_main, command_line, options);
platform_channel_pair_->ChildProcessLaunched();
broker_platform_channel_pair_->ChildProcessLaunched();
ChildProcessLaunched(test_child_.Handle(),
broker_platform_channel_pair_->PassServerHandle());
CHECK(test_child_.IsValid());
}
int MultiprocessTestHelper::WaitForChildShutdown() {
CHECK(test_child_.IsValid());
int rv = -1;
CHECK(
test_child_.WaitForExitWithTimeout(TestTimeouts::action_timeout(), &rv));
test_child_.Close();
return rv;
}
bool MultiprocessTestHelper::WaitForChildTestShutdown() {
return WaitForChildShutdown() == 0;
}
// static
void MultiprocessTestHelper::ChildSetup() {
CHECK(base::CommandLine::InitializedForCurrentProcess());
client_platform_handle =
PlatformChannelPair::PassClientHandleFromParentProcess(
*base::CommandLine::ForCurrentProcess());
std::string broker_handle_str =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
kBrokerHandleSwitch);
ScopedPlatformHandle broker_handle =
PlatformChannelPair::PassClientHandleFromParentProcessFromString(
broker_handle_str);
SetParentPipeHandle(std::move(broker_handle));
}
// static
ScopedPlatformHandle MultiprocessTestHelper::client_platform_handle;
} // namespace test
} // namespace edk
} // namespace mojo
| [
"1480868058@qq.com"
] | 1480868058@qq.com |
a696952ddc3578d4c85a555ef1a6a9074aa120f5 | 8c910789637e15021cc169fe3c6ab8f29487daf1 | /Linux_ex_box/build-Linux_ex_box-Desktop_Qt_5_1_0_GCC_64bit-Debug/ui_mymainwindow.h | 841a5896cabe8a5e61f3d06cb8fd46f9ea49d5cc | [] | no_license | Dufferent/Qt-Work | 498c6b9251cbb43fdcaeec273ce0878722a0d40b | 245481420d7a511511fc8906a4955f4727806446 | refs/heads/master | 2023-01-11T00:54:01.533118 | 2020-10-29T08:53:22 | 2020-10-29T08:53:22 | 287,864,157 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,535 | h | /********************************************************************************
** Form generated from reading UI file 'mymainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.1.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MYMAINWINDOW_H
#define UI_MYMAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MyMainWindow
{
public:
QWidget *centralWidget;
void setupUi(QMainWindow *MyMainWindow)
{
if (MyMainWindow->objectName().isEmpty())
MyMainWindow->setObjectName(QStringLiteral("MyMainWindow"));
MyMainWindow->resize(1024, 600);
centralWidget = new QWidget(MyMainWindow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
MyMainWindow->setCentralWidget(centralWidget);
retranslateUi(MyMainWindow);
QMetaObject::connectSlotsByName(MyMainWindow);
} // setupUi
void retranslateUi(QMainWindow *MyMainWindow)
{
MyMainWindow->setWindowTitle(QApplication::translate("MyMainWindow", "MyMainWindow", 0));
} // retranslateUi
};
namespace Ui {
class MyMainWindow: public Ui_MyMainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MYMAINWINDOW_H
| [
"2269969490@qq.com"
] | 2269969490@qq.com |
70126879b03599750b7c5c708cfc0def2003f2dd | 04b886bcb4eae8b4cd656b2917a82a13067ca2b7 | /src/cpp/oclint/oclint-rules/test/custom2/CommaMissingInIntArrayInitRuleTest.cpp | 374b3dd1ebf54f51e850a54bcb5bcd208e3e3eaa | [
"BSD-3-Clause"
] | permissive | terryhu08/MachingLearning | 4d01ba9c72e931a82db0992ea58ad1bd425f1544 | 45ccc79ee906e072bb40552c211579e2c677f459 | refs/heads/master | 2021-09-16T01:38:10.364942 | 2018-06-14T13:45:39 | 2018-06-14T13:45:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 773 | cpp | #include "TestRuleOnCode.h"
#include "rules/custom2/CommaMissingInIntArrayInitRule.cpp"
TEST(CommaMissingInIntArrayInitRuleTest, PropertyTest)
{
CommaMissingInIntArrayInitRule rule;
EXPECT_EQ(3, rule.priority());
EXPECT_EQ("comma missing in int array init", rule.name());
EXPECT_EQ("custom2", rule.category());
}
TEST(CommaMissingInIntArrayInitRuleTest, NoViolationInstance)
{
testRuleOnCXXCode(new CommaMissingInIntArrayInitRule(),
"void m(){int a[3]={1,2,3};}");
}
TEST(CommaMissingInIntArrayInitRuleTest, Test1)
{
testRuleOnCXXCode(new CommaMissingInIntArrayInitRule(),
"void m(){\n"
"int a[3]={1,2 -3};}",0, 2, 1, 2, 17, "It is possible that ',' comma is missing at the end of the string.");
}
| [
"dhfang812@163.com"
] | dhfang812@163.com |
3b23f675a82d35706ba8b2400b39b40fee517ab6 | 2112057af069a78e75adfd244a3f5b224fbab321 | /branches/ref1/src-root/src/common/world/client_zone.cpp | 0f6076b8fb3308af47100ffb40c7b2d1bfa35067 | [] | no_license | blockspacer/ireon | 120bde79e39fb107c961697985a1fe4cb309bd81 | a89fa30b369a0b21661c992da2c4ec1087aac312 | refs/heads/master | 2023-04-15T00:22:02.905112 | 2010-01-07T20:31:07 | 2010-01-07T20:31:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,274 | cpp | /**
* @file client_zone.cpp
* Client-side zone class
*/
/* Copyright (C) 2005 ireon.org developers council
* $Id$
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include "stdafx.h"
#include "world/client_zone.h"
#include "world/client_static.h"
#include "resource/resource_manager.h"
CClientZone::CClientZone()
{
};
CClientZone::~CClientZone()
{
};
bool CClientZone::load(const String& resourceName)
{
CLog::instance()->log(CLog::msgFlagResources,CLog::msgLvlInfo,"Loading zone from '%s'.\n",resourceName.c_str());
DataPtr dPtr = CResourceManager::instance()->load(resourceName);
if( !dPtr )
{
CLog::instance()->log(CLog::msgLvlError,"Error loading zone: resource not found.\n",resourceName.c_str());
return false;
}
TiXmlDocument doc;
std::stringstream buf;
buf.write(dPtr->data(),dPtr->size());
buf >> doc;
if (doc.Error())
{
CLog::instance()->log(CLog::msgFlagResources, CLog::msgLvlError, _("Error loading zone: XML parser returned an error: %s\n"), doc.ErrorDesc());
return false;
}
TiXmlNode* root = doc.FirstChild();
while( root && root->Type() == TiXmlNode::DECLARATION )
root = root->NextSibling();
if( !root || root->Type() != TiXmlNode::ELEMENT || strcmp(root->ToElement()->Value(),"Zone") )
{
CLog::instance()->log(CLog::msgFlagResources, CLog::msgLvlError, _("Error loading zone: resource isn't zone. %s\n"),root->Value());
return false;
};
TiXmlNode* option;
for( option = root->FirstChild(); option; option = option->NextSibling() )
if( !processOption(option) )
{
CLog::instance()->log(CLog::msgFlagResources, CLog::msgLvlError, _("Error loading zone: error in file near '%s'.\n"),option->Value());
return false;
};
return true;
};
bool CClientZone::processOption(TiXmlNode* option)
{
if( !option )
return false;
if( !option->Type() == TiXmlNode::ELEMENT )
return true;
const char* name = option->Value();
if( !strcmp(name,"Static") )
{
if( !processStatic(option) )
return false;
}
else
{
return false;
}
return true;
};
bool CClientZone::processStatic(TiXmlNode *node)
{
TiXmlAttribute* attr = node->ToElement()->FirstAttribute();
StaticPtr st;
while( attr )
{
if( !attr || !attr->Name() || !attr->Value() )
return false;
if( !st )
{
if( !strcmp(attr->Name(),"Name") )
{
StaticPrototypePtr prot = I_WORLD->getStaticPrototype(attr->Value());
if( prot )
st.reset( new CClientStaticObject(prot) );
} else if( !strcmp(attr->Name(),"Id") )
{
StaticPrototypePtr prot = I_WORLD->getStaticPrototype(StringConverter::parseLong(attr->Value()));
if( prot )
st.reset( new CClientStaticObject(prot) );
}
} else
{
if( !strcmp(attr->Name(),"Position") )
{
StringVector vec = StringConverter::parseStringVector(attr->Value());
if( vec.size() < 3 )
return false;
Vector3 pos;
pos.x = StringConverter::parseReal(vec[0]);
pos.y = StringConverter::parseReal(vec[1]);
pos.z = StringConverter::parseReal(vec[2]);
st->setPosition(pos);
} else if( !strcmp(attr->Name(),"Rotation") )
{
Radian rot;
rot = Radian(StringConverter::parseReal(attr->Value()));
st->setRotation(rot);
}
}
attr = attr->Next();
}
if( st)
{
m_statics.push_back(st);
I_WORLD->addStatic(st);
}
return true;
};
void CClientZone::unload()
{
for( std::vector<StaticPtr>::iterator it = m_statics.begin(); it != m_statics.end(); ++it )
I_WORLD->removeStatic(*it);
}; | [
"psavichev@gmail.com"
] | psavichev@gmail.com |
9c01007ded74b8ef3e8088874d50ece6fde219d6 | b9048652f15be10232888d2af78ef7e6eb363893 | /include/qxt/qxtletterboxwidget_p.h | dcd81e9b2a0f47d45568dabeae9c59ee268f724d | [] | no_license | vghost2008/wlib | 0457b1e191f2d461caf100486521c89f2abbf9f1 | ab7ae25eef6427df21d7022f3376ec601beec28f | refs/heads/master | 2022-05-09T11:49:07.802162 | 2019-05-07T11:39:39 | 2019-05-07T11:39:39 | 185,389,328 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,524 | h | /********************************************************************************
* License :
* Author : WangJie bluetornado@zju.edu.cn
* Description :
********************************************************************************/
#ifndef QXTLETTERBOXWIDGET_P_H
/****************************************************************************
** Copyright (c) 2006 - 2011, the LibQxt project.
** See the Qxt AUTHORS file for a list of authors and copyright holders.
** 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 LibQxt project 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 <COPYRIGHT HOLDER> 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.
**
** <http://libqxt.org> <foundation@libqxt.org>
*****************************************************************************/
#define QXTLETTERBOXWIDGET_P_H
#include "qxtletterboxwidget.h"
#include <QTimer>
class QxtLetterBoxWidgetPrivate : public QObject, public QxtPrivate<QxtLetterBoxWidget>
{
Q_OBJECT
public:
QXT_DECLARE_PUBLIC(QxtLetterBoxWidget)
QxtLetterBoxWidgetPrivate();
public:
QWidget* center;
QTimer timer;
int margin;
};
#endif // QXTLETTERBOXWIDGET_P_H
| [
"bluetornado@zju.edu.cn"
] | bluetornado@zju.edu.cn |
ac01dbb0756b955213bc4131cb000ff1ffde511f | e773d41ff293c1c0b7f1968a26cc5764e00667bb | /cefclient/browser/main_context_impl_win.cc | d59788a8b7a73af33767949f5a20e3de85da8ec1 | [] | no_license | yufanghu/fec | 43794ac187d3c1aa84bd4e660f5272c8addf830a | 87be1c1238ff638ed4c5488cf5f0701b78e4b82f | refs/heads/master | 2021-03-27T12:33:52.573027 | 2017-12-01T10:18:38 | 2017-12-01T10:18:38 | 108,273,897 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,073 | cc | // Copyright (c) 2015 The Chromium Embedded Framework 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 "cefclient/browser/main_context_impl.h"
#include <direct.h>
#include <shlobj.h>
namespace client {
std::string MainContextImpl::GetDownloadPath(const std::string& file_name) {
TCHAR szFolderPath[MAX_PATH];
std::string path;
// Save the file in the user's "My Documents" folder.
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, NULL,
0, szFolderPath))) {
path = CefString(szFolderPath);
path += "\\" + file_name;
}
return path;
}
std::string MainContextImpl::GetAppWorkingDirectory() {
char szWorkingDir[MAX_PATH + 1];
if (_getcwd(szWorkingDir, MAX_PATH) == NULL) {
szWorkingDir[0] = 0;
} else {
// Add trailing path separator.
size_t len = strlen(szWorkingDir);
szWorkingDir[len] = '\\';
szWorkingDir[len + 1] = 0;
}
return szWorkingDir;
}
} // namespace client
| [
"fibonacci2016@126.com"
] | fibonacci2016@126.com |
43b7fcaad12c788e099ed7b44642527ad17e47b1 | fd05fd318468dfddb80a3af1b413fca06e9fae90 | /SMJS_GameRulesProps.h | 8285328acf0ac0297a08a182fec89f38d837c97b | [] | no_license | Sarzhevsky/SourceMod.js | 6a6c7df9ae0d3ef7f1beffc40efb36186d8b90f9 | 639c0cb3dd60c6034f8fccea4be8ac6127f74f44 | refs/heads/master | 2021-01-22T03:23:26.301192 | 2013-11-17T21:30:52 | 2013-11-17T21:30:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,107 | h | #ifndef _INCLUDE_SMJS_GAMERULESPROPS_H_
#define _INCLUDE_SMJS_GAMERULESPROPS_H_
#include "SMJS.h"
#include "SMJS_BaseWrapped.h"
#include "SMJS_Netprops.h"
class SMJS_GameRulesProps : public SMJS_BaseWrapped, public SMJS_NPValueCacher {
public:
void *gamerules;
void *proxy;
SMJS_GameRulesProps();
WRAPPED_CLS(SMJS_GameRulesProps, SMJS_BaseWrapped){
temp->InstanceTemplate()->SetNamedPropertyHandler(GetRulesProp, SetRulesProp);
}
v8::Persistent<v8::Value> GenerateThenFindCachedValue(PLUGIN_ID plId, std::string key, SendProp *p, size_t offset){
bool isCacheable;
auto res = v8::Persistent<v8::Value>::New(SMJS_Netprops::SGetNetProp(gamerules, NULL, p, offset, &isCacheable));
if(isCacheable){
InsertCachedValue(plId, key, res);
}
return res;
}
void OnWrapperAttached(SMJS_Plugin *plugin, v8::Persistent<v8::Value> wrapper);
static void GetRulesProp(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args);
static void SetRulesProp(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<Value>& args);
};
#endif | [
"matheusavs3@gmail.com"
] | matheusavs3@gmail.com |
2789ade5b65463402ebfc694f29169ffcf47b495 | 2e3d9d4b286b7b3d0b367181f5d1c2c154fb9b28 | /Math/BottomUpResultOut/solver.cpp | c4106aea156899b69147dbaedf2d0ab426625cd9 | [] | no_license | squirrelClare/algorithm_cplusplus | 8237baf5cea6f79889eaad6360b2dadd7a1b3624 | 312a63851182962d014b6b5fba28bdd51decb033 | refs/heads/master | 2021-01-10T03:38:40.434217 | 2015-10-22T17:36:57 | 2015-10-22T17:36:57 | 44,685,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,680 | cpp | #include "solver.h"
#include<QDebug>
/**
与SteelBarCut中的不同之处在于,
该算法将每次局部最优解存储起来,
以便再次需要求解该局部最优解的
时候直接从记录中调取。以牺牲内存
为代价获得运行时间上的提升*/
Solver::Solver()
{
}
Solver::Solver(const QList<int> lengthList, const QList<int> valueList, const int totalLength)
{
/*lengthList为可以切割的长度选项
valueList为每个长度对应的价格
totalLength为原始钢条长度*/
this->totalLength=totalLength;
barList=new QMap<int,BarPart>();
//将价格表的样例存入一个QMap中
for(int i=0;i<lengthList.length();++i){
BarPart *part=new BarPart(lengthList.at(i),valueList.at(i));
barList->insert(i,*part);
}
}
void Solver::ShowResult()
{
//输出最佳结果
RodAns ans=BottomUpCutRod(totalLength);
qDebug()<<QString("长度为%1的钢条最多可卖%2")
.arg(totalLength).arg(ans.bestValue);
qDebug()<<QString("最好方案为:");
int tlength=totalLength;
QList<int>outPut;
while(tlength>=3){
outPut<<ans.proAns.at(tlength);
tlength=tlength-ans.proAns.at(tlength);
}
qDebug()<<outPut;
}
RodAns Solver::BottomUpCutRod(const int totalLength)
{
/*
原来的算法在第二次for循环的时候会调用record中的值,但是barvalue的值
并不是连续的,对于其中的间断点会被record的中初始值所代替,因此将record
的值全部初始化为0(最终的局部最优化结果肯定是非负的)*/
//record数组初始化
QList<int>proans;
for(int i=0;i<=totalLength;++i){
record<<-100;
proans<<0;
}
//算法主体部分
for(int j=0;j<=totalLength;++j){
int currentBest=0;
for(int i=0;i<barList->size();++i){
if(((j-barList->value(i).barLength)>=0)&¤tBest<barList->value(i).barValue+
record.at(j-barList->value(i).barLength)){
currentBest=barList->value(i).barValue+
record.at(j-barList->value(i).barLength);
proans.replace(j,barList->value(i).barLength);//保存局部最佳结果的第一段切割长度
}
}
record.replace(j,currentBest);
}
RodAns ans;
ans.bestValue=record.at(totalLength);
ans.proAns=proans;
return ans;
}
//将价格表的样例封装成一个类
BarPart::BarPart()
{
}
BarPart::BarPart(const int barLength,const int barValue)
{
//barValue为对应barValue的价格
this->barLength=barLength;
this->barValue=barValue;
}
| [
"zcc136314853@hotmail.com"
] | zcc136314853@hotmail.com |
f11299f4f177bb08528eafc5a291f89e623efd6d | bf53c9dc6851b501b13fa89c6e2bd2cf775b0d67 | /src/WaterSurface.cpp | 698ebd16de31516b1b6fa25c35163267e77800c8 | [] | no_license | xchuki00/PGP | 2ca971dc9af7858b57407502c777c2819d56d689 | 3f4990f84260734b5758e3731bd088e099d00575 | refs/heads/master | 2023-01-28T09:57:57.710541 | 2020-11-23T14:05:08 | 2020-11-23T14:05:08 | 315,334,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,746 | cpp | #pragma once
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <GPUEngine/geGL/StaticCalls.h>
#include <GPUEngine/geGL/geGL.h>
#include <GPUEngine/geAd/SDLWindow/SDLWindow.h>
#include <GPUEngine/geAd/SDLWindow/SDLMainLoop.h>
#include<glm/glm.hpp>
#include<glm/gtc/matrix_transform.hpp>
#include<glm/gtc/type_ptr.hpp>
#include<glm/gtc/matrix_access.hpp>
#include "controler.h"
#include "Model.h"
#include "BaseShaders.h"
#include "LightSource.h"
#include "Models.h"
#include "sphere.h"
#include "water.h"
controler* c;
Model* sp;
Water* w;
bool HittedSphere(SDL_Event const& e) {
return false;
}
bool keyDown(SDL_Event const& e) {
if (e.key.keysym.sym == SDLK_1) {
w->pushToPoint(0);
}
if (e.key.keysym.sym == SDLK_2) {
w->pushToPoint(w->getCountofSurfacePoints()*0.85);
}
if (e.key.keysym.sym == SDLK_3) {
w->pushToPoint(w->getCountofSurfacePoints()*0.6);
}
if (e.key.keysym.sym == SDLK_4) {
w->pushToPoint(w->getCountofSurfacePoints()*0.55);
}
if (e.key.keysym.sym == SDLK_5) {
w->pushToPoint(w->getCountofSurfacePoints()/4);
}
if (e.key.keysym.sym == SDLK_6) {
w->pushToPoint(w->getCountofSurfacePoints()/8);
}
return c->keyDown(e);
}
bool mouseDown(SDL_Event const& e) {
if (HittedSphere(e)) {
//sp->setDraging();
}
return c->mouseDown(e);
}
bool mouseUp(SDL_Event const& e) {
return c->mouseUp(e);
}
bool mouseMotion(SDL_Event const& e) {
return c->MouseMotion(e);
}
bool windowResize(SDL_Event const& e) {
std::cout << "DWADWA";
w->resizeTexture();
ge::gl::glViewport(0,0,c->getWindowWidth(),c->getWindowHeight());
return true;
}
using namespace ge::gl;
int main(int, char*[]) {
//create window
auto mainLoop = std::make_shared<ge::ad::SDLMainLoop>();
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
auto window = std::make_shared<ge::ad::SDLWindow>();
window->createContext("rendering");
mainLoop->addWindow("mainWindow", window);
//init OpenGL
ge::gl::init(SDL_GL_GetProcAddress);
ge::gl::setHighDebugMessage();
//sphere = new Model();
c= new controler(window,mainLoop);
window->setEventCallback(SDL_KEYDOWN, keyDown);
window->setEventCallback(SDL_MOUSEBUTTONDOWN, mouseDown);
window->setEventCallback(SDL_MOUSEBUTTONUP, mouseUp);
window->setEventCallback(SDL_MOUSEMOTION, mouseMotion);
window->setWindowEventCallback(SDL_WINDOWEVENT_SIZE_CHANGED, windowResize);
LightSource* ls = new LightSource(glm::vec3(-5,-10,-5),glm::vec3(1,1,1),1,1);
c->setLightSource(ls);
Model* aq = new Model();
aq->setControler(c);
sp = new Model();
sp->setControler(c);
glm::vec3 v[4] = {
glm::vec3(-14.999f,0.0f,4.999f),
glm::vec3(-14.999f,0.0f,-4.999f),
glm::vec3(14.999f,0.0f,4.999f)
};
w = new Water(v,3,glm::vec3(0,1,0),300,100,4.999);
w->setControler(c);
w->setLightSource(ls);
w->compileShaders();
w->buffer();
auto vs = std::make_shared<ge::gl::Shader>(GL_VERTEX_SHADER, BaseVSSrc);
auto fs = std::make_shared<ge::gl::Shader>(GL_FRAGMENT_SHADER, BaseFSSrc);
auto prgm = std::make_shared<ge::gl::Program>(vs, fs);
auto upOrDown = prgm->getUniformLocation("upOrDown");
//buffer data
aq->buffer(prgm,AquariumVer,NULL,AquariumEl,AquariumCountOfVer,AquariumCountOfEl);
aq->setTexture("../imgs/text.bmp", GL_BGR);
sp->buffer(prgm,NULL, sphereVer,sphereEl, sphereCountOfVer,sphereCountOfEl);
sp->setPosition(glm::translate(glm::mat4(1.0f), glm::vec3(10, 3, -1.5)));
ls->glGetUniformLocationLight(prgm);
w->addModel(sp);
w->addModel(aq);
Model* sp2 = new Model();
sp2->setControler(c);
sp2->setPosition(glm::translate(glm::mat4(1.0f), glm::vec3(-8, 3, 1)));
sp2->buffer(prgm, NULL, sphereVer, sphereEl, sphereCountOfVer, sphereCountOfEl);
Model* sp3 = new Model();
sp3->setControler(c);
sp3->setPosition(glm::translate(glm::mat4(1.0f), glm::vec3(0, -3, 2.697)));
sp3->buffer(prgm, NULL, sphereVer, sphereEl, sphereCountOfVer, sphereCountOfEl);
Model* pl = new Model();
pl->setControler(c);
//pl->setPosition(glm::translate(glm::mat4(1.0f), glm::vec3(0, -3, 2.697)));
pl->buffer(prgm, plane, NULL, planeEL, planeCountOfVer, planeCountOfEl);
pl->setTexture("../imgs/text.bmp", GL_RGB);
w->addModel(sp2);
w->addModel(sp3);
//draw loop
ge::util::Timer<float>timer;
mainLoop->setIdleCallback([&]() {
auto const frameTime = timer.elapsedFromLast();
w->updateSurface(frameTime);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, 1, 0);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
w->Draw(false);
glDisable(GL_STENCIL_TEST);
glEnable(GL_DEPTH_TEST);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
w->drawReflectRefract(true);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_EQUAL, 1, 0xff);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
prgm->use();
ls->glUniformLight(c->getPosition());
aq->draw(1.3333);
sp->draw(1.3333);
sp2->draw(1.3333);
sp3->draw(1.3333);
glStencilFunc(GL_EQUAL, 0, 0xff);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
prgm->use();
ls->glUniformLight(c->getPosition());
aq->draw(1);
sp->draw(1);
sp2->draw(1);
sp3->draw(1);
glDisable(GL_STENCIL_TEST);
w->Draw(false);
glDisable(GL_BLEND);
window->swap();
});
(*mainLoop)();
return EXIT_SUCCESS;
}
| [
"p.chukir@gmail.com"
] | p.chukir@gmail.com |
32aba7c26130efcbfb2358267d8900a725353ffb | 4bc40d60c146300030512b11e375cb8abbf2f5b3 | /LiteX/software/Doom/mc1-doom/src/i_video_mc1.c | 2a236239853956be6fd01e54612d3112cdc7efe5 | [
"BSD-3-Clause",
"GPL-1.0-or-later",
"LicenseRef-scancode-proprietary-license"
] | permissive | BrunoLevy/learn-fpga | fd18ea8a67cfc46d29fac9ad417ae7990b135118 | fd954b06f6dc57ee042d0c82e9418e83c4b261b4 | refs/heads/master | 2023-08-23T06:15:43.195975 | 2023-08-04T06:41:22 | 2023-08-04T06:41:22 | 267,350,664 | 2,036 | 191 | BSD-3-Clause | 2023-06-23T13:41:44 | 2020-05-27T15:04:05 | C++ | UTF-8 | C++ | false | false | 11,164 | c | // Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// Copyright (C) 1993-1996 by id Software, Inc.
// Copyright (C) 2020 by Marcus Geelnard
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// DESCRIPTION:
// Dummy system interface for video.
//
//-----------------------------------------------------------------------------
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <mr32intrin.h>
#include "doomdef.h"
#include "d_event.h"
#include "d_main.h"
#include "i_system.h"
#include "i_video.h"
#include "v_video.h"
#include "mc1.h"
// Video buffers.
static byte* s_vcp;
static byte* s_palette;
static byte* s_framebuffer;
// Pointers for the custom VRAM allocator.
static byte* s_vram_alloc_ptr;
static byte* s_vram_alloc_end;
static void MC1_AllocInit (void)
{
// We assume that the Doom binary is loaded into XRAM (0x80000000...), or
// into the "ROM" (0x00000000...) for the simulator, and that it has
// complete ownership of VRAM (0x40000000...).
s_vram_alloc_ptr = (byte*)0x40000100;
s_vram_alloc_end = (byte*)(0x40000000 + GET_MMIO (VRAMSIZE));
}
static byte* MC1_VRAM_Alloc (const size_t bytes)
{
// Check if there is enough room.
byte* ptr = s_vram_alloc_ptr;
byte* new_ptr = ptr + bytes;
if (new_ptr > s_vram_alloc_end)
return NULL;
// Align the next allocation slot to a 32 byte boundary.
if ((((size_t)new_ptr) & 31) != 0)
new_ptr += 32U - (((size_t)new_ptr) & 31);
s_vram_alloc_ptr = new_ptr;
return ptr;
}
static byte* MC1_Alloc (const size_t bytes)
{
// Prefer VRAM (for speed).
byte* ptr = MC1_VRAM_Alloc (bytes);
if (ptr == NULL)
ptr = (byte*)malloc (bytes);
return ptr;
}
static int MC1_IsVRAMPtr (const byte* ptr)
{
return ptr >= (byte*)0x40000000 && ptr < (byte*)0x80000000;
}
static void MC1_Free (byte* ptr)
{
// We can't free VRAM pointers.
if (!MC1_IsVRAMPtr (ptr))
free (ptr);
}
static void I_MC1_CreateVCP (void)
{
// Get the native video signal resolution and calculate the scaling factors.
unsigned native_width = GET_MMIO (VIDWIDTH);
unsigned native_height = GET_MMIO (VIDHEIGHT);
unsigned xincr = ((native_width - 1) << 16) / (SCREENWIDTH - 1);
unsigned yincr = ((native_height - 1) << 16) / (SCREENHEIGHT - 1);
// Frame configuraiton.
unsigned* vcp = (unsigned*)s_vcp;
*vcp++ = VCP_SETREG (VCR_XINCR, xincr);
*vcp++ = VCP_SETREG (VCR_CMODE, CMODE_PAL8);
*vcp++ = VCP_JSR (s_palette);
// Generate lines.
unsigned y = 0;
unsigned addr = (unsigned)s_framebuffer;
for (int i = 0; i < SCREENHEIGHT; ++i)
{
if (i == 0)
*vcp++ = VCP_SETREG (VCR_HSTOP, native_width);
*vcp++ = VCP_WAITY (y >> 16);
*vcp++ = VCP_SETREG (VCR_ADDR, VCP_TOVCPADDR (addr));
addr += SCREENWIDTH;
y += yincr;
}
// End of frame (wait forever).
*vcp = VCP_WAITY (32767);
// Palette.
unsigned* palette = (unsigned*)s_palette;
*palette++ = VCP_SETPAL (0, 256);
palette += 256;
*palette = VCP_RTS;
// Configure the main layer 1 VCP to call our VCP.
*((unsigned*)0x40000008) = VCP_JMP (s_vcp);
// The layer 2 VCP should do nothing.
*((unsigned*)0x40000010) = VCP_WAITY (32767);
}
static int I_MC1_TranslateKey (unsigned keycode)
{
// clang-format off
switch (keycode)
{
case KB_SPACE: return ' ';
case KB_LEFT: return KEY_LEFTARROW;
case KB_RIGHT: return KEY_RIGHTARROW;
case KB_DOWN: return KEY_DOWNARROW;
case KB_UP: return KEY_UPARROW;
case KB_ESC: return KEY_ESCAPE;
case KB_ENTER: return KEY_ENTER;
case KB_TAB: return KEY_TAB;
case KB_F1: return KEY_F1;
case KB_F2: return KEY_F2;
case KB_F3: return KEY_F3;
case KB_F4: return KEY_F4;
case KB_F5: return KEY_F5;
case KB_F6: return KEY_F6;
case KB_F7: return KEY_F7;
case KB_F8: return KEY_F8;
case KB_F9: return KEY_F9;
case KB_F10: return KEY_F10;
case KB_F11: return KEY_F11;
case KB_F12: return KEY_F12;
case KB_DEL:
case KB_BACKSPACE: return KEY_BACKSPACE;
case KB_MM_PLAY_PAUSE: return KEY_PAUSE;
case KB_KP_PLUS: return KEY_EQUALS;
case KB_KP_MINUS: return KEY_MINUS;
case KB_LSHIFT:
case KB_RSHIFT: return KEY_RSHIFT;
case KB_LCTRL:
case KB_RCTRL: return KEY_RCTRL;
case KB_LALT:
case KB_LMETA:
case KB_RALT:
case KB_RMETA: return KEY_RALT;
case KB_A: return 'a';
case KB_B: return 'b';
case KB_C: return 'c';
case KB_D: return 'd';
case KB_E: return 'e';
case KB_F: return 'f';
case KB_G: return 'g';
case KB_H: return 'h';
case KB_I: return 'i';
case KB_J: return 'j';
case KB_K: return 'k';
case KB_L: return 'l';
case KB_M: return 'm';
case KB_N: return 'n';
case KB_O: return 'o';
case KB_P: return 'p';
case KB_Q: return 'q';
case KB_R: return 'r';
case KB_S: return 's';
case KB_T: return 't';
case KB_U: return 'u';
case KB_V: return 'v';
case KB_W: return 'w';
case KB_X: return 'x';
case KB_Y: return 'y';
case KB_Z: return 'z';
case KB_0: return '0';
case KB_1: return '1';
case KB_2: return '2';
case KB_3: return '3';
case KB_4: return '4';
case KB_5: return '5';
case KB_6: return '6';
case KB_7: return '7';
case KB_8: return '8';
case KB_9: return '9';
default:
return 0;
}
// clang-format on
}
static unsigned s_keyptr;
static boolean I_MC1_PollKeyEvent (event_t* event)
{
unsigned keyptr, keycode;
int doom_key;
// Check if we have any new keycode from the keyboard.
keyptr = GET_MMIO (KEYPTR);
if (s_keyptr == keyptr)
return false;
// Get the next keycode.
++s_keyptr;
keycode = GET_KEYBUF (s_keyptr % KEYBUF_SIZE);
// Translate the MC1 keycode to a Doom keycode.
doom_key = I_MC1_TranslateKey (keycode & 0x1ff);
if (doom_key != 0)
{
// Create a Doom keyboard event.
event->type = (keycode & 0x80000000) ? ev_keydown : ev_keyup;
event->data1 = doom_key;
}
return true;
}
static boolean I_MC1_PollMouseEvent (event_t* event)
{
static unsigned s_old_mousepos;
static unsigned s_old_mousebtns;
// Do we have a new mouse movement event?
unsigned mousepos = GET_MMIO (MOUSEPOS);
unsigned mousebtns = GET_MMIO (MOUSEBTNS);
if (mousepos == s_old_mousepos && mousebtns == s_old_mousebtns)
return false;
// Get the x & y mouse delta.
int mousex = ((int)(short)mousepos) - ((int)(short)s_old_mousepos);
int mousey = (((int)mousepos) >> 16) - (((int)s_old_mousepos) >> 16);
// Create a Doom mouse event.
event->type = ev_mouse;
event->data1 = mousebtns;
event->data2 = mousex;
event->data3 = mousey;
s_old_mousepos = mousepos;
s_old_mousebtns = mousebtns;
return true;
}
void I_InitGraphics (void)
{
MC1_AllocInit ();
// Video buffers that need to be in VRAM.
const size_t vcp_size = (5 + SCREENHEIGHT * 2) * sizeof (unsigned);
const size_t palette_size = (2 + 256) * sizeof (unsigned);
const size_t framebuffer_size = SCREENWIDTH * SCREENHEIGHT * sizeof (byte);
s_vcp = MC1_VRAM_Alloc (vcp_size);
s_palette = MC1_VRAM_Alloc (palette_size);
s_framebuffer = MC1_VRAM_Alloc (framebuffer_size);
if (s_framebuffer == NULL)
I_Error ("Error: Not enough VRAM!");
// Allocate regular memory for the Doom screen.
const size_t screen_size = SCREENWIDTH * SCREENHEIGHT * sizeof (byte);
screens[0] = MC1_Alloc (screen_size);
if (MC1_IsVRAMPtr (screens[0]))
printf ("I_InitGraphics: Using VRAM for the pixel buffer\n");
I_MC1_CreateVCP ();
s_keyptr = GET_MMIO (KEYPTR);
printf (
"I_InitGraphics: Resolution = %d x %d\n"
" Framebuffer @ 0x%08x (%d)\n"
" Palette @ 0x%08x (%d)\n",
SCREENWIDTH,
SCREENHEIGHT,
(unsigned)s_framebuffer,
(unsigned)s_framebuffer,
(unsigned)(s_palette + 4),
(unsigned)(s_palette + 4));
}
void I_ShutdownGraphics (void)
{
MC1_Free (screens[0]);
}
void I_StartFrame (void)
{
// Er? This is declared in i_system.h.
}
void I_StartTic (void)
{
event_t event;
// Read mouse and keyboard events.
if (I_MC1_PollKeyEvent (&event))
D_PostEvent (&event);
if (I_MC1_PollMouseEvent (&event))
D_PostEvent (&event);
}
void I_SetPalette (byte* palette)
{
unsigned* dst = &((unsigned*)s_palette)[1];
const unsigned a = 255;
for (int i = 0; i < 256; ++i)
{
unsigned r = (unsigned)palette[i * 3];
unsigned g = (unsigned)palette[i * 3 + 1];
unsigned b = (unsigned)palette[i * 3 + 2];
#ifdef __MRISC32_PACKED_OPS__
dst[i] = _mr32_pack_h (_mr32_pack (a, g), _mr32_pack (b, r));
#else
dst[i] = (a << 24) | (b << 16) | (g << 8) | r;
#endif
}
}
void I_UpdateNoBlit (void)
{
}
void I_FinishUpdate (void)
{
memcpy (s_framebuffer, screens[0], SCREENWIDTH * SCREENHEIGHT);
}
void I_WaitVBL (int count)
{
#if 0
// TODO(m): Replace this with MC1 MMIO-based timing.
struct timeval t0, t;
long dt, waitt;
// Busy-wait for COUNT*1/60 s.
gettimeofday (&t0, NULL);
waitt = count * (1000000L / 60L);
do
{
gettimeofday (&t, NULL);
dt = (t.tv_sec - t0.tv_sec) * 1000000L + (t.tv_usec - t0.tv_usec);
} while (dt < waitt);
#else
// Run at max FPS - no wait.
(void)count;
#endif
}
void I_ReadScreen (byte* scr)
{
memcpy (scr, screens[0], SCREENWIDTH * SCREENHEIGHT);
}
| [
"Bruno.Levy@inria.fr"
] | Bruno.Levy@inria.fr |
2c5a747a79e80d3fbf7e81763656c376af17dc7b | 212d4a1c13f8ccbce673982df770258c03f9abcc | /libnmm/sml/sml-tools/Helper.cc | 067e36e2142577748d5aa6e7a04719cea41209f3 | [] | no_license | ShravanTata/Mouse_Webots_BenchMarking | 0c3d62cd1d15c82134b8bdb8605f4e83d783875d | 90d838f42675752d68190e62c47693e45b6038e0 | refs/heads/master | 2020-12-30T15:07:40.042027 | 2017-05-29T15:47:37 | 2017-05-29T15:47:37 | 91,102,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,372 | cc | #include "Helper.hh"
#include <boost/random/normal_distribution.hpp>
#include <boost/random.hpp>
//constructor
typedef boost::mt19937 RandomGenerator;
static RandomGenerator rng(static_cast<unsigned> (time(0)));
// Gaussian
typedef boost::normal_distribution<double> NormalDistribution;
typedef boost::variate_generator<RandomGenerator&, \
NormalDistribution> GaussianGenerator;
static NormalDistribution nd_amplitude(0.0, 1.0);
static GaussianGenerator gauss(rng, nd_amplitude);
extern EventManager* eventManager;
extern SmlParameters parameters;
using namespace std;
double getSignalDependentNoise(double s){
// rescaling normal random variable
// N(0,1)*A --> N(0,A*A). We want N(0,K*A*A) --> N(0,1)*sqrt(K*A*A)
static double k = Settings::get<double>("noise_variationCoefficient");
static string noise_level = "noise_level";
static string noise_class = Settings::get<string>("noise_class");
static string noise_type = Settings::get<string>("noise_type");
k=k+parameters[1][noise_level];
if(eventManager->get<int>(STATES::CYCLE_COUNT) < 1)
return 0.0;;
if(noise_class=="revert")
s = 1.0-s;
else if(noise_class=="constant")
s = 1.0;
//return gauss()*k*s*s;
if(noise_type=="sqrt")
return gauss()*sqrt(k*s*s);
else
return gauss()*k*sqrt(s*s);
} | [
"tatarama@biorobpc4.epfl.ch"
] | tatarama@biorobpc4.epfl.ch |
34b32e0ebddb7e497561bfa6cfd433687b80057a | 4bc21b62a346c48cbe29b898b7fe331d6dedc023 | /src/rpcserver.h | 914de9fc73b3017f1d06ef8829a1926a1a79d169 | [
"MIT"
] | permissive | dachcoin/dach | 0bc1f57a2be087c81a847b8114d8d38cb211d39b | 57c2b4af4005e8deba7932e81bd6ccdfbfe7f6bf | refs/heads/master | 2020-04-12T22:36:32.451311 | 2019-01-30T05:54:04 | 2019-01-30T05:54:04 | 162,793,444 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,802 | h | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2018 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_RPCSERVER_H
#define BITCOIN_RPCSERVER_H
#include "amount.h"
#include "rpcprotocol.h"
#include "uint256.h"
#include <list>
#include <map>
#include <stdint.h>
#include <string>
#include <boost/function.hpp>
#include <univalue.h>
class CRPCCommand;
namespace RPCServer
{
void OnStarted(boost::function<void ()> slot);
void OnStopped(boost::function<void ()> slot);
void OnPreCommand(boost::function<void (const CRPCCommand&)> slot);
void OnPostCommand(boost::function<void (const CRPCCommand&)> slot);
}
class CBlockIndex;
class CNetAddr;
class JSONRequest
{
public:
UniValue id;
std::string strMethod;
UniValue params;
JSONRequest() { id = NullUniValue; }
void parse(const UniValue& valRequest);
};
/** Query whether RPC is running */
bool IsRPCRunning();
/**
* Set the RPC warmup status. When this is done, all RPC calls will error out
* immediately with RPC_IN_WARMUP.
*/
void SetRPCWarmupStatus(const std::string& newStatus);
/* Mark warmup as done. RPC calls will be processed from now on. */
void SetRPCWarmupFinished();
/* returns the current warmup state. */
bool RPCIsInWarmup(std::string* statusOut);
/**
* Type-check arguments; throws JSONRPCError if wrong type given. Does not check that
* the right number of arguments are passed, just that any passed are the correct type.
* Use like: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type));
*/
void RPCTypeCheck(const UniValue& params,
const std::list<UniValue::VType>& typesExpected, bool fAllowNull=false);
/**
* Check for expected keys/value types in an Object.
* Use like: RPCTypeCheckObj(object, boost::assign::map_list_of("name", str_type)("value", int_type));
*/
void RPCTypeCheckObj(const UniValue& o,
const std::map<std::string, UniValue::VType>& typesExpected, bool fAllowNull=false);
/** Opaque base class for timers returned by NewTimerFunc.
* This provides no methods at the moment, but makes sure that delete
* cleans up the whole state.
*/
class RPCTimerBase
{
public:
virtual ~RPCTimerBase() {}
};
/**
* RPC timer "driver".
*/
class RPCTimerInterface
{
public:
virtual ~RPCTimerInterface() {}
/** Implementation name */
virtual const char *Name() = 0;
/** Factory function for timers.
* RPC will call the function to create a timer that will call func in *millis* milliseconds.
* @note As the RPC mechanism is backend-neutral, it can use different implementations of timers.
* This is needed to cope with the case in which there is no HTTP server, but
* only GUI RPC console, and to break the dependency of pcserver on httprpc.
*/
virtual RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis) = 0;
};
/** Register factory function for timers */
void RPCRegisterTimerInterface(RPCTimerInterface *iface);
/** Unregister factory function for timers */
void RPCUnregisterTimerInterface(RPCTimerInterface *iface);
/**
* Run func nSeconds from now.
* Overrides previous timer <name> (if any).
*/
void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds);
typedef UniValue(*rpcfn_type)(const UniValue& params, bool fHelp);
class CRPCCommand
{
public:
std::string category;
std::string name;
rpcfn_type actor;
bool okSafeMode;
bool threadSafe;
bool reqWallet;
};
/**
* Dach RPC command dispatcher.
*/
class CRPCTable
{
private:
std::map<std::string, const CRPCCommand*> mapCommands;
public:
CRPCTable();
const CRPCCommand* operator[](const std::string& name) const;
std::string help(std::string name) const;
/**
* Execute a method.
* @param method Method to execute
* @param params UniValue Array of arguments (JSON objects)
* @returns Result of the call.
* @throws an exception (UniValue) when an error happens.
*/
UniValue execute(const std::string &method, const UniValue ¶ms) const;
/**
* Returns a list of registered commands
* @returns List of registered commands.
*/
std::vector<std::string> listCommands() const;
};
extern const CRPCTable tableRPC;
/**
* Utilities: convert hex-encoded Values
* (throws error if not hex).
*/
extern uint256 ParseHashV(const UniValue& v, std::string strName);
extern uint256 ParseHashO(const UniValue& o, std::string strKey);
extern std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName);
extern std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey);
extern int ParseInt(const UniValue& o, std::string strKey);
extern bool ParseBool(const UniValue& o, std::string strKey);
extern int64_t nWalletUnlockTime;
extern CAmount AmountFromValue(const UniValue& value);
extern UniValue ValueFromAmount(const CAmount& amount);
extern double GetDifficulty(const CBlockIndex* blockindex = NULL);
extern std::string HelpRequiringPassphrase();
extern std::string HelpExampleCli(std::string methodname, std::string args);
extern std::string HelpExampleRpc(std::string methodname, std::string args);
extern void EnsureWalletIsUnlocked(bool fAllowAnonOnly = false);
extern UniValue getconnectioncount(const UniValue& params, bool fHelp); // in rpcnet.cpp
extern UniValue getpeerinfo(const UniValue& params, bool fHelp);
extern UniValue ping(const UniValue& params, bool fHelp);
extern UniValue addnode(const UniValue& params, bool fHelp);
extern UniValue disconnectnode(const UniValue& params, bool fHelp);
extern UniValue getaddednodeinfo(const UniValue& params, bool fHelp);
extern UniValue getnettotals(const UniValue& params, bool fHelp);
extern UniValue setban(const UniValue& params, bool fHelp);
extern UniValue listbanned(const UniValue& params, bool fHelp);
extern UniValue clearbanned(const UniValue& params, bool fHelp);
extern UniValue dumpprivkey(const UniValue& params, bool fHelp); // in rpcdump.cpp
extern UniValue importprivkey(const UniValue& params, bool fHelp);
extern UniValue importaddress(const UniValue& params, bool fHelp);
extern UniValue dumpwallet(const UniValue& params, bool fHelp);
extern UniValue importwallet(const UniValue& params, bool fHelp);
extern UniValue bip38encrypt(const UniValue& params, bool fHelp);
extern UniValue bip38decrypt(const UniValue& params, bool fHelp);
extern UniValue getgenerate(const UniValue& params, bool fHelp); // in rpcmining.cpp
extern UniValue setgenerate(const UniValue& params, bool fHelp);
extern UniValue getnetworkhashps(const UniValue& params, bool fHelp);
extern UniValue gethashespersec(const UniValue& params, bool fHelp);
extern UniValue getmininginfo(const UniValue& params, bool fHelp);
extern UniValue prioritisetransaction(const UniValue& params, bool fHelp);
extern UniValue getblocktemplate(const UniValue& params, bool fHelp);
extern UniValue submitblock(const UniValue& params, bool fHelp);
extern UniValue estimatefee(const UniValue& params, bool fHelp);
extern UniValue estimatepriority(const UniValue& params, bool fHelp);
extern UniValue getnewaddress(const UniValue& params, bool fHelp); // in rpcwallet.cpp
extern UniValue getaccountaddress(const UniValue& params, bool fHelp);
extern UniValue getrawchangeaddress(const UniValue& params, bool fHelp);
extern UniValue setaccount(const UniValue& params, bool fHelp);
extern UniValue getaccount(const UniValue& params, bool fHelp);
extern UniValue getaddressesbyaccount(const UniValue& params, bool fHelp);
extern UniValue sendtoaddress(const UniValue& params, bool fHelp);
extern UniValue sendtoaddressix(const UniValue& params, bool fHelp);
extern UniValue signmessage(const UniValue& params, bool fHelp);
extern UniValue getreceivedbyaddress(const UniValue& params, bool fHelp);
extern UniValue getreceivedbyaccount(const UniValue& params, bool fHelp);
extern UniValue getbalance(const UniValue& params, bool fHelp);
extern UniValue getunconfirmedbalance(const UniValue& params, bool fHelp);
extern UniValue movecmd(const UniValue& params, bool fHelp);
extern UniValue sendfrom(const UniValue& params, bool fHelp);
extern UniValue sendmany(const UniValue& params, bool fHelp);
extern UniValue addmultisigaddress(const UniValue& params, bool fHelp);
extern UniValue listreceivedbyaddress(const UniValue& params, bool fHelp);
extern UniValue listreceivedbyaccount(const UniValue& params, bool fHelp);
extern UniValue listtransactions(const UniValue& params, bool fHelp);
extern UniValue listaddressgroupings(const UniValue& params, bool fHelp);
extern UniValue listaccounts(const UniValue& params, bool fHelp);
extern UniValue listsinceblock(const UniValue& params, bool fHelp);
extern UniValue gettransaction(const UniValue& params, bool fHelp);
extern UniValue backupwallet(const UniValue& params, bool fHelp);
extern UniValue keypoolrefill(const UniValue& params, bool fHelp);
extern UniValue walletpassphrase(const UniValue& params, bool fHelp);
extern UniValue walletpassphrasechange(const UniValue& params, bool fHelp);
extern UniValue walletlock(const UniValue& params, bool fHelp);
extern UniValue encryptwallet(const UniValue& params, bool fHelp);
extern UniValue getwalletinfo(const UniValue& params, bool fHelp);
extern UniValue getblockchaininfo(const UniValue& params, bool fHelp);
extern UniValue getnetworkinfo(const UniValue& params, bool fHelp);
extern UniValue reservebalance(const UniValue& params, bool fHelp);
extern UniValue setstakesplitthreshold(const UniValue& params, bool fHelp);
extern UniValue getstakesplitthreshold(const UniValue& params, bool fHelp);
extern UniValue multisend(const UniValue& params, bool fHelp);
extern UniValue autocombinerewards(const UniValue& params, bool fHelp);
// dachx extern UniValue getzerocoinbalance(const UniValue& params, bool fHelp);
extern UniValue listmintedzerocoins(const UniValue& params, bool fHelp);
extern UniValue listspentzerocoins(const UniValue& params, bool fHelp);
extern UniValue listzerocoinamounts(const UniValue& params, bool fHelp);
extern UniValue mintzerocoin(const UniValue& params, bool fHelp);
extern UniValue spendzerocoin(const UniValue& params, bool fHelp);
extern UniValue resetmintzerocoin(const UniValue& params, bool fHelp);
extern UniValue resetspentzerocoin(const UniValue& params, bool fHelp);
extern UniValue getarchivedzerocoin(const UniValue& params, bool fHelp);
extern UniValue importzerocoins(const UniValue& params, bool fHelp);
extern UniValue exportzerocoins(const UniValue& params, bool fHelp);
extern UniValue reconsiderzerocoins(const UniValue& params, bool fHelp);
extern UniValue getspentzerocoinamount(const UniValue& params, bool fHelp);
extern UniValue setzdachxseed(const UniValue& params, bool fHelp);
extern UniValue getzdachxseed(const UniValue& params, bool fHelp);
extern UniValue generatemintlist(const UniValue& params, bool fHelp);
extern UniValue searchdzdachx(const UniValue& params, bool fHelp);
extern UniValue dzdachxstate(const UniValue& params, bool fHelp);
extern UniValue getrawtransaction(const UniValue& params, bool fHelp); // in rcprawtransaction.cpp
extern UniValue listunspent(const UniValue& params, bool fHelp);
extern UniValue lockunspent(const UniValue& params, bool fHelp);
extern UniValue listlockunspent(const UniValue& params, bool fHelp);
extern UniValue createrawtransaction(const UniValue& params, bool fHelp);
extern UniValue decoderawtransaction(const UniValue& params, bool fHelp);
extern UniValue decodescript(const UniValue& params, bool fHelp);
extern UniValue signrawtransaction(const UniValue& params, bool fHelp);
extern UniValue sendrawtransaction(const UniValue& params, bool fHelp);
extern UniValue findserial(const UniValue& params, bool fHelp); // in rpcblockchain.cpp
extern UniValue getblockcount(const UniValue& params, bool fHelp);
extern UniValue getbestblockhash(const UniValue& params, bool fHelp);
extern UniValue getdifficulty(const UniValue& params, bool fHelp);
extern UniValue settxfee(const UniValue& params, bool fHelp);
extern UniValue getmempoolinfo(const UniValue& params, bool fHelp);
extern UniValue getrawmempool(const UniValue& params, bool fHelp);
extern UniValue getblockhash(const UniValue& params, bool fHelp);
extern UniValue getblock(const UniValue& params, bool fHelp);
extern UniValue getblockheader(const UniValue& params, bool fHelp);
extern UniValue getfeeinfo(const UniValue& params, bool fHelp);
extern UniValue gettxoutsetinfo(const UniValue& params, bool fHelp);
extern UniValue gettxout(const UniValue& params, bool fHelp);
extern UniValue verifychain(const UniValue& params, bool fHelp);
extern UniValue getchaintips(const UniValue& params, bool fHelp);
extern UniValue invalidateblock(const UniValue& params, bool fHelp);
extern UniValue reconsiderblock(const UniValue& params, bool fHelp);
extern UniValue getaccumulatorvalues(const UniValue& params, bool fHelp);
extern UniValue getpoolinfo(const UniValue& params, bool fHelp); // in rpcmasternode.cpp
extern UniValue masternode(const UniValue& params, bool fHelp);
extern UniValue listmasternodes(const UniValue& params, bool fHelp);
extern UniValue getmasternodecount(const UniValue& params, bool fHelp);
extern UniValue createmasternodebroadcast(const UniValue& params, bool fHelp);
extern UniValue decodemasternodebroadcast(const UniValue& params, bool fHelp);
extern UniValue relaymasternodebroadcast(const UniValue& params, bool fHelp);
extern UniValue masternodeconnect(const UniValue& params, bool fHelp);
extern UniValue masternodecurrent(const UniValue& params, bool fHelp);
extern UniValue masternodedebug(const UniValue& params, bool fHelp);
extern UniValue startmasternode(const UniValue& params, bool fHelp);
extern UniValue createmasternodekey(const UniValue& params, bool fHelp);
extern UniValue getmasternodeoutputs(const UniValue& params, bool fHelp);
extern UniValue listmasternodeconf(const UniValue& params, bool fHelp);
extern UniValue getmasternodestatus(const UniValue& params, bool fHelp);
extern UniValue getmasternodewinners(const UniValue& params, bool fHelp);
extern UniValue getmasternodescores(const UniValue& params, bool fHelp);
extern UniValue mnbudget(const UniValue& params, bool fHelp); // in rpcmasternode-budget.cpp
extern UniValue preparebudget(const UniValue& params, bool fHelp);
extern UniValue submitbudget(const UniValue& params, bool fHelp);
extern UniValue mnbudgetvote(const UniValue& params, bool fHelp);
extern UniValue getbudgetvotes(const UniValue& params, bool fHelp);
extern UniValue getnextsuperblock(const UniValue& params, bool fHelp);
extern UniValue getbudgetprojection(const UniValue& params, bool fHelp);
extern UniValue getbudgetinfo(const UniValue& params, bool fHelp);
extern UniValue mnbudgetrawvote(const UniValue& params, bool fHelp);
extern UniValue mnfinalbudget(const UniValue& params, bool fHelp);
extern UniValue checkbudgets(const UniValue& params, bool fHelp);
extern UniValue getinfo(const UniValue& params, bool fHelp); // in rpcmisc.cpp
extern UniValue mnsync(const UniValue& params, bool fHelp);
extern UniValue spork(const UniValue& params, bool fHelp);
extern UniValue validateaddress(const UniValue& params, bool fHelp);
extern UniValue createmultisig(const UniValue& params, bool fHelp);
extern UniValue verifymessage(const UniValue& params, bool fHelp);
extern UniValue setmocktime(const UniValue& params, bool fHelp);
extern UniValue getstakingstatus(const UniValue& params, bool fHelp);
bool StartRPC();
void InterruptRPC();
void StopRPC();
std::string JSONRPCExecBatch(const UniValue& vReq);
#endif // BITCOIN_RPCSERVER_H
| [
"media@dachcoin.live"
] | media@dachcoin.live |
b532c0d8db525bccbc32a4a011db755b9eccce11 | 1095cfe2e29ddf4e4c5e12d713bd12f45c9b6f7d | /ext/systemc/src/sysc/datatypes/fx/scfx_pow10.h | c9b278561f747424d113f608bdbcec18f19550fe | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | gem5/gem5 | 9ec715ae036c2e08807b5919f114e1d38d189bce | 48a40cf2f5182a82de360b7efa497d82e06b1631 | refs/heads/stable | 2023-09-03T15:56:25.819189 | 2023-08-31T05:53:03 | 2023-08-31T05:53:03 | 27,425,638 | 1,185 | 1,177 | BSD-3-Clause | 2023-09-14T08:29:31 | 2014-12-02T09:46:00 | C++ | UTF-8 | C++ | false | false | 2,543 | h | /*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera 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.
*****************************************************************************/
/*****************************************************************************
scfx_pow10.h -
Original Author: Robert Graulich, Synopsys, Inc.
Martin Janssen, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
// $Log: scfx_pow10.h,v $
// Revision 1.1.1.1 2006/12/15 20:20:04 acg
// SystemC 2.3
//
// Revision 1.3 2006/01/13 18:53:58 acg
// Andy Goodrich: added $Log command so that CVS comments are reproduced in
// the source.
//
#ifndef SCFX_POW10_H
#define SCFX_POW10_H
#include "sysc/datatypes/fx/scfx_rep.h"
namespace sc_dt
{
// classes defined in this module
class scfx_pow10;
// ----------------------------------------------------------------------------
// CLASS : scfx_pow10
//
// Class to compute (and cache) powers of 10 in arbitrary precision.
// ----------------------------------------------------------------------------
const int SCFX_POW10_TABLE_SIZE = 32;
class scfx_pow10
{
public:
scfx_pow10();
~scfx_pow10();
const scfx_rep operator() ( int );
private:
scfx_rep* pos( int );
scfx_rep* neg( int );
scfx_rep m_pos[SCFX_POW10_TABLE_SIZE];
scfx_rep m_neg[SCFX_POW10_TABLE_SIZE];
};
} // namespace sc_dt
#endif
// Taf!
| [
"jungma@eit.uni-kl.de"
] | jungma@eit.uni-kl.de |
562386b22cb290f536bf08ae70457fa8816770fe | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /components/safe_browsing/core/common/safe_browsing_prefs.cc | e0b3f4727e8d5b419b756fedb9ed9953ca61da84 | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 16,705 | cc | // Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "base/check_op.h"
#include "base/command_line.h"
#include "base/metrics/histogram_macros.h"
#include "base/notreached.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/core/common/thread_utils.h"
#include "components/safe_browsing/core/features.h"
#include "net/base/url_util.h"
#include "url/gurl.h"
#include "url/url_canon.h"
namespace {
// Update the correct UMA metric based on which pref was changed and which UI
// the change was made on.
void RecordExtendedReportingPrefChanged(
const PrefService& prefs,
safe_browsing::ExtendedReportingOptInLocation location) {
bool pref_value = safe_browsing::IsExtendedReportingEnabled(prefs);
switch (location) {
case safe_browsing::SBER_OPTIN_SITE_CHROME_SETTINGS:
UMA_HISTOGRAM_BOOLEAN(
"SafeBrowsing.Pref.Scout.SetPref.SBER2Pref.ChromeSettings",
pref_value);
break;
case safe_browsing::SBER_OPTIN_SITE_ANDROID_SETTINGS:
UMA_HISTOGRAM_BOOLEAN(
"SafeBrowsing.Pref.Scout.SetPref.SBER2Pref.AndroidSettings",
pref_value);
break;
case safe_browsing::SBER_OPTIN_SITE_DOWNLOAD_FEEDBACK_POPUP:
UMA_HISTOGRAM_BOOLEAN(
"SafeBrowsing.Pref.Scout.SetPref.SBER2Pref.DownloadPopup",
pref_value);
break;
case safe_browsing::SBER_OPTIN_SITE_SECURITY_INTERSTITIAL:
UMA_HISTOGRAM_BOOLEAN(
"SafeBrowsing.Pref.Scout.SetPref.SBER2Pref.SecurityInterstitial",
pref_value);
break;
default:
NOTREACHED();
}
}
// A helper function to return a GURL containing just the scheme, host, port,
// and path from a URL. Equivalent to clearing any username, password, query,
// and ref. Return empty URL if |url| is not valid.
GURL GetSimplifiedURL(const GURL& url) {
if (!url.is_valid() || !url.IsStandard())
return GURL();
url::Replacements<char> replacements;
replacements.ClearUsername();
replacements.ClearPassword();
replacements.ClearQuery();
replacements.ClearRef();
return url.ReplaceComponents(replacements);
}
} // namespace
namespace prefs {
const char kSafeBrowsingEnabled[] = "safebrowsing.enabled";
const char kSafeBrowsingEnhanced[] = "safebrowsing.enhanced";
const char kSafeBrowsingEnterpriseRealTimeUrlCheckMode[] =
"safebrowsing.enterprise_real_time_url_check_mode";
const char kSafeBrowsingExtendedReportingOptInAllowed[] =
"safebrowsing.extended_reporting_opt_in_allowed";
const char kSafeBrowsingIncidentsSent[] = "safebrowsing.incidents_sent";
const char kSafeBrowsingProceedAnywayDisabled[] =
"safebrowsing.proceed_anyway_disabled";
const char kSafeBrowsingSawInterstitialScoutReporting[] =
"safebrowsing.saw_interstitial_sber2";
const char kSafeBrowsingScoutReportingEnabled[] =
"safebrowsing.scout_reporting_enabled";
const char kSafeBrowsingTriggerEventTimestamps[] =
"safebrowsing.trigger_event_timestamps";
const char kSafeBrowsingUnhandledGaiaPasswordReuses[] =
"safebrowsing.unhandled_sync_password_reuses";
const char kSafeBrowsingNextPasswordCaptureEventLogTime[] =
"safebrowsing.next_password_capture_event_log_time";
const char kSafeBrowsingWhitelistDomains[] =
"safebrowsing.safe_browsing_whitelist_domains";
const char kPasswordProtectionChangePasswordURL[] =
"safebrowsing.password_protection_change_password_url";
const char kPasswordProtectionLoginURLs[] =
"safebrowsing.password_protection_login_urls";
const char kPasswordProtectionWarningTrigger[] =
"safebrowsing.password_protection_warning_trigger";
const char kAdvancedProtectionLastRefreshInUs[] =
"safebrowsing.advanced_protection_last_refresh";
const char kSafeBrowsingSendFilesForMalwareCheck[] =
"safebrowsing.send_files_for_malware_check";
const char kUnsafeEventsReportingEnabled[] =
"safebrowsing.unsafe_events_reporting";
const char kBlockLargeFileTransfer[] =
"safebrowsing.block_large_file_transfers";
const char kDelayDeliveryUntilVerdict[] =
"safebrowsing.delay_delivery_until_verdict";
const char kAllowPasswordProtectedFiles[] =
"safebrowsing.allow_password_protected_files";
const char kCheckContentCompliance[] = "safebrowsing.check_content_compliance";
const char kBlockUnsupportedFiletypes[] =
"safebrowsing.block_unsupported_filetypes";
const char kURLsToCheckComplianceOfDownloadedContent[] =
"safebrowsing.urls_to_check_compliance_of_downloaded_content";
const char kURLsToCheckForMalwareOfUploadedContent[] =
"safebrowsing.urls_to_check_for_malware_of_uploaded_content";
const char kURLsToNotCheckForMalwareOfDownloadedContent[] =
"safebrowsing.urls_to_not_check_for_malware_of_downloaded_content";
const char kURLsToNotCheckComplianceOfUploadedContent[] =
"policy.urls_to_not_check_compliance_of_uploaded_content";
const char kAdvancedProtectionAllowed[] =
"safebrowsing.advanced_protection_allowed";
} // namespace prefs
namespace safe_browsing {
SafeBrowsingState GetSafeBrowsingState(const PrefService& prefs) {
if (IsEnhancedProtectionEnabled(prefs)) {
return ENHANCED_PROTECTION;
} else if (prefs.GetBoolean(prefs::kSafeBrowsingEnabled)) {
return STANDARD_PROTECTION;
} else {
return NO_SAFE_BROWSING;
}
}
void SetSafeBrowsingState(PrefService* prefs, SafeBrowsingState state) {
if (state == ENHANCED_PROTECTION) {
SetEnhancedProtectionPref(prefs, true);
SetStandardProtectionPref(prefs, true);
} else if (state == STANDARD_PROTECTION) {
SetEnhancedProtectionPref(prefs, false);
SetStandardProtectionPref(prefs, true);
} else {
SetEnhancedProtectionPref(prefs, false);
SetStandardProtectionPref(prefs, false);
}
}
bool IsSafeBrowsingEnabled(const PrefService& prefs) {
return prefs.GetBoolean(prefs::kSafeBrowsingEnabled);
}
bool IsEnhancedProtectionEnabled(const PrefService& prefs) {
// SafeBrowsingEnabled is checked too due to devices being out
// of sync or not on a version that includes SafeBrowsingEnhanced pref.
return prefs.GetBoolean(prefs::kSafeBrowsingEnhanced) &&
IsSafeBrowsingEnabled(prefs) &&
base::FeatureList::IsEnabled(kEnhancedProtection);
}
bool ExtendedReportingPrefExists(const PrefService& prefs) {
return prefs.HasPrefPath(prefs::kSafeBrowsingScoutReportingEnabled);
}
ExtendedReportingLevel GetExtendedReportingLevel(const PrefService& prefs) {
return IsExtendedReportingEnabled(prefs) ? SBER_LEVEL_SCOUT : SBER_LEVEL_OFF;
}
bool IsExtendedReportingOptInAllowed(const PrefService& prefs) {
return prefs.GetBoolean(prefs::kSafeBrowsingExtendedReportingOptInAllowed);
}
bool IsExtendedReportingEnabled(const PrefService& prefs) {
return (IsSafeBrowsingEnabled(prefs) &&
prefs.GetBoolean(prefs::kSafeBrowsingScoutReportingEnabled)) ||
IsEnhancedProtectionEnabled(prefs);
}
bool IsExtendedReportingPolicyManaged(const PrefService& prefs) {
return prefs.IsManagedPreference(prefs::kSafeBrowsingScoutReportingEnabled);
}
void RecordExtendedReportingMetrics(const PrefService& prefs) {
// This metric tracks the extended browsing opt-in based on whichever setting
// the user is currently seeing. It tells us whether extended reporting is
// happening for this user.
UMA_HISTOGRAM_BOOLEAN("SafeBrowsing.Pref.Extended",
IsExtendedReportingEnabled(prefs));
// Track whether this user has ever seen a security interstitial.
UMA_HISTOGRAM_BOOLEAN(
"SafeBrowsing.Pref.SawInterstitial.SBER2Pref",
prefs.GetBoolean(prefs::kSafeBrowsingSawInterstitialScoutReporting));
}
void RegisterProfilePrefs(PrefRegistrySimple* registry) {
registry->RegisterBooleanPref(prefs::kSafeBrowsingScoutReportingEnabled,
false);
registry->RegisterBooleanPref(
prefs::kSafeBrowsingSawInterstitialScoutReporting, false);
registry->RegisterBooleanPref(
prefs::kSafeBrowsingExtendedReportingOptInAllowed, true);
registry->RegisterBooleanPref(
prefs::kSafeBrowsingEnabled, true,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
registry->RegisterBooleanPref(prefs::kSafeBrowsingEnhanced, false);
registry->RegisterBooleanPref(prefs::kSafeBrowsingProceedAnywayDisabled,
false);
registry->RegisterDictionaryPref(prefs::kSafeBrowsingIncidentsSent);
registry->RegisterDictionaryPref(
prefs::kSafeBrowsingUnhandledGaiaPasswordReuses);
registry->RegisterStringPref(
prefs::kSafeBrowsingNextPasswordCaptureEventLogTime,
"0"); // int64 as string
registry->RegisterListPref(prefs::kSafeBrowsingWhitelistDomains);
registry->RegisterStringPref(prefs::kPasswordProtectionChangePasswordURL, "");
registry->RegisterListPref(prefs::kPasswordProtectionLoginURLs);
registry->RegisterIntegerPref(prefs::kPasswordProtectionWarningTrigger,
PASSWORD_PROTECTION_OFF);
registry->RegisterInt64Pref(prefs::kAdvancedProtectionLastRefreshInUs, 0);
registry->RegisterIntegerPref(prefs::kSafeBrowsingSendFilesForMalwareCheck,
DO_NOT_SCAN);
registry->RegisterBooleanPref(prefs::kAdvancedProtectionAllowed, true);
registry->RegisterIntegerPref(
prefs::kSafeBrowsingEnterpriseRealTimeUrlCheckMode,
REAL_TIME_CHECK_DISABLED);
}
void RegisterLocalStatePrefs(PrefRegistrySimple* registry) {
registry->RegisterDictionaryPref(prefs::kSafeBrowsingTriggerEventTimestamps);
registry->RegisterBooleanPref(prefs::kUnsafeEventsReportingEnabled, false);
registry->RegisterIntegerPref(prefs::kBlockLargeFileTransfer, 0);
registry->RegisterIntegerPref(prefs::kDelayDeliveryUntilVerdict, DELAY_NONE);
registry->RegisterIntegerPref(
prefs::kAllowPasswordProtectedFiles,
AllowPasswordProtectedFilesValues::ALLOW_UPLOADS_AND_DOWNLOADS);
registry->RegisterIntegerPref(prefs::kCheckContentCompliance, CHECK_NONE);
registry->RegisterIntegerPref(prefs::kBlockUnsupportedFiletypes,
BLOCK_UNSUPPORTED_FILETYPES_NONE);
registry->RegisterListPref(prefs::kURLsToCheckComplianceOfDownloadedContent);
registry->RegisterListPref(prefs::kURLsToNotCheckComplianceOfUploadedContent);
registry->RegisterListPref(prefs::kURLsToCheckForMalwareOfUploadedContent);
registry->RegisterListPref(
prefs::kURLsToNotCheckForMalwareOfDownloadedContent);
}
void SetExtendedReportingPrefAndMetric(
PrefService* prefs,
bool value,
ExtendedReportingOptInLocation location) {
prefs->SetBoolean(prefs::kSafeBrowsingScoutReportingEnabled, value);
RecordExtendedReportingPrefChanged(*prefs, location);
}
void SetExtendedReportingPrefForTests(PrefService* prefs, bool value) {
prefs->SetBoolean(prefs::kSafeBrowsingScoutReportingEnabled, value);
}
void SetEnhancedProtectionPrefForTests(PrefService* prefs, bool value) {
// SafeBrowsingEnabled pref needs to be turned on in order for enhanced
// protection pref to be turned on. This method is only used for tests.
prefs->SetBoolean(prefs::kSafeBrowsingEnabled, value);
prefs->SetBoolean(prefs::kSafeBrowsingEnhanced, value);
}
void SetEnhancedProtectionPref(PrefService* prefs, bool value) {
prefs->SetBoolean(prefs::kSafeBrowsingEnhanced, value);
}
void SetStandardProtectionPref(PrefService* prefs, bool value) {
prefs->SetBoolean(prefs::kSafeBrowsingEnabled, value);
}
void UpdatePrefsBeforeSecurityInterstitial(PrefService* prefs) {
// Remember that this user saw an interstitial.
prefs->SetBoolean(prefs::kSafeBrowsingSawInterstitialScoutReporting, true);
}
base::ListValue GetSafeBrowsingPreferencesList(PrefService* prefs) {
base::ListValue preferences_list;
const char* safe_browsing_preferences[] = {
prefs::kSafeBrowsingEnabled,
prefs::kSafeBrowsingExtendedReportingOptInAllowed,
prefs::kSafeBrowsingScoutReportingEnabled, prefs::kSafeBrowsingEnhanced};
// Add the status of the preferences if they are Enabled or Disabled for the
// user.
for (const char* preference : safe_browsing_preferences) {
preferences_list.Append(base::Value(preference));
bool enabled = prefs->GetBoolean(preference);
preferences_list.Append(base::Value(enabled ? "Enabled" : "Disabled"));
}
return preferences_list;
}
void GetSafeBrowsingWhitelistDomainsPref(
const PrefService& prefs,
std::vector<std::string>* out_canonicalized_domain_list) {
const base::ListValue* pref_value =
prefs.GetList(prefs::kSafeBrowsingWhitelistDomains);
CanonicalizeDomainList(*pref_value, out_canonicalized_domain_list);
}
void CanonicalizeDomainList(
const base::ListValue& raw_domain_list,
std::vector<std::string>* out_canonicalized_domain_list) {
out_canonicalized_domain_list->clear();
for (auto it = raw_domain_list.GetList().begin();
it != raw_domain_list.GetList().end(); it++) {
// Verify if it is valid domain string.
url::CanonHostInfo host_info;
std::string canonical_host =
net::CanonicalizeHost(it->GetString(), &host_info);
if (!canonical_host.empty())
out_canonicalized_domain_list->push_back(canonical_host);
}
}
bool IsURLWhitelistedByPolicy(const GURL& url,
StringListPrefMember* pref_member) {
DCHECK(CurrentlyOnThread(ThreadID::IO));
if (!pref_member)
return false;
std::vector<std::string> sb_whitelist_domains = pref_member->GetValue();
return std::find_if(sb_whitelist_domains.begin(), sb_whitelist_domains.end(),
[&url](const std::string& domain) {
return url.DomainIs(domain);
}) != sb_whitelist_domains.end();
}
bool IsURLWhitelistedByPolicy(const GURL& url, const PrefService& pref) {
DCHECK(CurrentlyOnThread(ThreadID::UI));
if (!pref.HasPrefPath(prefs::kSafeBrowsingWhitelistDomains))
return false;
const base::ListValue* whitelist =
pref.GetList(prefs::kSafeBrowsingWhitelistDomains);
for (const base::Value& value : whitelist->GetList()) {
if (url.DomainIs(value.GetString()))
return true;
}
return false;
}
bool MatchesEnterpriseWhitelist(const PrefService& pref,
const std::vector<GURL>& url_chain) {
for (const GURL& url : url_chain) {
if (IsURLWhitelistedByPolicy(url, pref))
return true;
}
return false;
}
void GetPasswordProtectionLoginURLsPref(const PrefService& prefs,
std::vector<GURL>* out_login_url_list) {
const base::ListValue* pref_value =
prefs.GetList(prefs::kPasswordProtectionLoginURLs);
out_login_url_list->clear();
for (const base::Value& value : pref_value->GetList()) {
GURL login_url(value.GetString());
// Skip invalid or none-http/https login URLs.
if (login_url.is_valid() && login_url.SchemeIsHTTPOrHTTPS())
out_login_url_list->push_back(login_url);
}
}
bool MatchesPasswordProtectionLoginURL(const GURL& url,
const PrefService& prefs) {
if (!url.is_valid())
return false;
std::vector<GURL> login_urls;
GetPasswordProtectionLoginURLsPref(prefs, &login_urls);
return MatchesURLList(url, login_urls);
}
bool MatchesURLList(const GURL& target_url, const std::vector<GURL> url_list) {
if (url_list.empty() || !target_url.is_valid())
return false;
GURL simple_target_url = GetSimplifiedURL(target_url);
for (const GURL& url : url_list) {
if (GetSimplifiedURL(url) == simple_target_url) {
return true;
}
}
return false;
}
GURL GetPasswordProtectionChangePasswordURLPref(const PrefService& prefs) {
if (!prefs.HasPrefPath(prefs::kPasswordProtectionChangePasswordURL))
return GURL();
GURL change_password_url_from_pref(
prefs.GetString(prefs::kPasswordProtectionChangePasswordURL));
// Skip invalid or non-http/https URL.
if (change_password_url_from_pref.is_valid() &&
change_password_url_from_pref.SchemeIsHTTPOrHTTPS()) {
return change_password_url_from_pref;
}
return GURL();
}
bool MatchesPasswordProtectionChangePasswordURL(const GURL& url,
const PrefService& prefs) {
if (!url.is_valid())
return false;
GURL change_password_url = GetPasswordProtectionChangePasswordURLPref(prefs);
if (change_password_url.is_empty())
return false;
return GetSimplifiedURL(change_password_url) == GetSimplifiedURL(url);
}
} // namespace safe_browsing
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
d42c8deff676e637fed89c4e7e2a62848f769323 | 76957b84c5c97ac08dd2baea6cd3d5db96d26012 | /common_project/nim/nim_doc/callback/doc_callback.h | 4c062c88ae2734f183bbc7743fddb5d21976e41b | [] | no_license | luchengbiao/base | 4e14e71b9c17ff4d2f2c064ec4f5eb7e9ce09ac8 | f8af675e01b0fee31a2b648eb0b95d0c115d68ff | refs/heads/master | 2021-06-27T12:04:29.620264 | 2019-04-29T02:39:32 | 2019-04-29T02:39:32 | 136,405,188 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 856 | h | #pragma once
#include <stdint.h>
#include <list>
#include "nim_sdk_manager\helper\nim_doc_trans_helper.h"
namespace nim_comp
{
/** @class DocTransCallback
* @brief 文档传输回调类
* @copyright (c) 2016, NetEase Inc. All rights reserved
* @author redrain
* @date 2016/12/15
*/
class DocTransCallback
{
public:
/**
* 文档转换结果通知的回调函数
* @param[in] code 错误码
* @param[in] doc_info 文档信息
* @return void 无返回值
*/
static void DocTransNotifyCallback(int32_t code, const nim::DocTransInfo& doc_info);
/**
* 接收文档信息的回调函数
* @param[in] code 错误码
* @param[in] count 服务器总条数
* @param[in] doc_infos 文档信息
* @return void 无返回值
*/
static void DocInfosCallback(int32_t code, int32_t count, const std::list<nim::DocTransInfo>& doc_infos);
};
} | [
"993925668@qq.com"
] | 993925668@qq.com |
a5978e3ee825e8c0a636da529925b087fb92e632 | dfc05885f375d723c767e85c303b706890e9bba9 | /hashmap/main.cpp | ffb749d5a8d9f2a19fd5cb476064d9abbbe91b2c | [] | no_license | z847299324/demo | 417f3f11118e38f93a4263485361ca4334bb8616 | 0f7649f5834682c4f5d32885621f4033a34e0604 | refs/heads/master | 2018-10-19T22:31:48.323534 | 2018-09-20T01:27:17 | 2018-09-20T01:27:17 | 99,782,273 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,947 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char ch;
int flag = 0;//设置标志位
char *infilename ="in", *outfilename = "out"; // 初始化的输入输出文件名
FILE *infile, *outfile;//文件指针
if (argc == 2)
strcpy(infilename, argv[1]);
else if (argc == 3) // 指定输入输出文件名
{
if (!strcmp(argv[1], argv[2]))//检测来两个传入的参数
{
printf("error:file is same\n");
exit(0);
}
strcpy(infilename, argv[1]);
strcpy(outfilename, argv[2]);
}
else if (argc > 3)
{
printf("error:传入参数过多\n");
exit(0);
}
if ((infile = fopen(infilename, "r")) == NULL)//打开文件的错误检测
{
printf("can't open input file!\n");
exit(0);
}
if ((outfile = fopen(outfilename, "w")) == NULL)//打开输出文件的检测
{
printf("can't open output file!\n");
exit(0);
}
while ((ch = fgetc(infile)) != EOF) // 读输入文件中的字符
{
if (flag == 0)
{
if (ch == '/') // 遇到"/", flag = 1;
{
flag = 1;
}
}
else if (flag == 1)
{
if (ch == '/') // 遇到"//", flag = 2;
{
flag = 2;
continue;
}
else if (ch == '*') // 遇到"/*", flag = 3;
{
flag = 3;
continue;
}
else // 遇到的"/"非注释符
{
flag = 0;
fputc('/', outfile);
}
}
else if (flag == 2)//遇到双//注释
{
if (ch == '\n') // 遇到"//"注释结尾的换行符
flag = 0;
else // 遇到"//"的注释部分
continue;
}
else if (flag == 3)
{
if (ch == '*') // 遇到"/*"注释中的"*", flag = 4;
flag = 4;
continue;
}
else if (flag == 4)
{
if (ch == '/') // 遇到"/*"注释结尾的"*/"
flag = 0;
else if (ch != '*') // 遇到"/*"的注释部分
flag = 3;
continue;
}
else
{
if (ch == ' ')
{
continue;
}
fputc(ch, outfile);
}
}
fclose(infile);
fclose(outfile);
} | [
"123456@qq.com"
] | 123456@qq.com |
010fbde138ce792da167028ff08cf326c7859740 | 755e7b5e73c5aa3b9702ba97ec33ca30c9e4e667 | /CFEM/PhyElementBar.cpp | b769156b8bb4823dda83c03c2b51522255fa7db5 | [] | no_license | JohnDTill/QtFEM | a18733aed7a42f50874c6a098b1128327e2dbb2c | 95ed1ba67e95760209f20733aee2d6be085b91cb | refs/heads/master | 2022-11-08T02:03:33.570951 | 2020-06-10T01:27:05 | 2020-06-10T01:27:05 | 174,175,275 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 630 | cpp | #include "PhyElementBar.h"
#include "PhyNode.h"
void PhyElementBar::setGeometry(){
L = fabs(eNodePtrs[1]->coordinate(0) - eNodePtrs[0]->coordinate(0));
}
void PhyElementBar::setInternalMaterialProperties(VectorXd& pMat){
A = pMat(mpb_A);
E = pMat(mpb_E);
}
void PhyElementBar::Calculate_ElementStiffness(){
// compute stiffness matrix:
ke.resize(2, 2);
double factor = A * E / L;
ke(0, 0) = ke(1, 1) = factor;
ke(1, 0) = ke(0, 1) = -factor;
}
void PhyElementBar::SpecificOutput(ostream& out) const{
double tension = A*E/L * (eNodePtrs[1]->dofs[0].value - eNodePtrs[0]->dofs[0].value);
out << tension;
}
| [
"JohnDTill@gmail.com"
] | JohnDTill@gmail.com |
9e57ed1f90551bf84fd2f2fa7e480b440b16e419 | 6b5d6690678f05a71837b85016db3da52359a2f6 | /src/net/ftp/ftp_network_transaction.h | ec0c1f8de2b39a52ee073dc70106b6d65422b117 | [
"BSD-3-Clause",
"MIT"
] | permissive | bopopescu/MQUIC | eda5477bacc68f30656488e3cef243af6f7460e6 | 703e944ec981366cfd2528943b1def2c72b7e49d | refs/heads/master | 2022-11-22T07:41:11.374401 | 2016-04-08T22:27:32 | 2016-04-08T22:27:32 | 282,352,335 | 0 | 0 | MIT | 2020-07-25T02:05:49 | 2020-07-25T02:05:49 | null | UTF-8 | C++ | false | false | 7,990 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_FTP_FTP_NETWORK_TRANSACTION_H_
#define NET_FTP_FTP_NETWORK_TRANSACTION_H_
#include <stdint.h>
#include <string>
#include <utility>
#include "base/compiler_specific.h"
#include "base/gtest_prod_util.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "net/base/address_list.h"
#include "net/base/auth.h"
#include "net/dns/host_resolver.h"
#include "net/dns/single_request_host_resolver.h"
#include "net/ftp/ftp_ctrl_response_buffer.h"
#include "net/ftp/ftp_response_info.h"
#include "net/ftp/ftp_transaction.h"
#include "net/log/net_log.h"
namespace net {
class ClientSocketFactory;
class StreamSocket;
class NET_EXPORT_PRIVATE FtpNetworkTransaction : public FtpTransaction {
public:
FtpNetworkTransaction(HostResolver* resolver,
ClientSocketFactory* socket_factory);
~FtpNetworkTransaction() override;
int Stop(int error);
// FtpTransaction methods:
int Start(const FtpRequestInfo* request_info,
const CompletionCallback& callback,
const BoundNetLog& net_log) override;
int RestartWithAuth(const AuthCredentials& credentials,
const CompletionCallback& callback) override;
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
const FtpResponseInfo* GetResponseInfo() const override;
LoadState GetLoadState() const override;
uint64_t GetUploadProgress() const override;
private:
FRIEND_TEST_ALL_PREFIXES(FtpNetworkTransactionTest,
DownloadTransactionEvilPasvUnsafeHost);
enum Command {
COMMAND_NONE,
COMMAND_USER,
COMMAND_PASS,
COMMAND_SYST,
COMMAND_TYPE,
COMMAND_EPSV,
COMMAND_PASV,
COMMAND_PWD,
COMMAND_SIZE,
COMMAND_RETR,
COMMAND_CWD,
COMMAND_LIST,
COMMAND_QUIT,
};
// Major categories of remote system types, as returned by SYST command.
enum SystemType {
SYSTEM_TYPE_UNKNOWN,
SYSTEM_TYPE_UNIX,
SYSTEM_TYPE_WINDOWS,
SYSTEM_TYPE_OS2,
SYSTEM_TYPE_VMS,
};
// Data representation type, see RFC 959 section 3.1.1. Data Types.
// We only support the two most popular data types.
enum DataType {
DATA_TYPE_ASCII,
DATA_TYPE_IMAGE,
};
// In FTP we need to issue different commands depending on whether a resource
// is a file or directory. If we don't know that, we're going to autodetect
// it.
enum ResourceType {
RESOURCE_TYPE_UNKNOWN,
RESOURCE_TYPE_FILE,
RESOURCE_TYPE_DIRECTORY,
};
enum State {
// Control connection states:
STATE_CTRL_RESOLVE_HOST,
STATE_CTRL_RESOLVE_HOST_COMPLETE,
STATE_CTRL_CONNECT,
STATE_CTRL_CONNECT_COMPLETE,
STATE_CTRL_READ,
STATE_CTRL_READ_COMPLETE,
STATE_CTRL_WRITE,
STATE_CTRL_WRITE_COMPLETE,
STATE_CTRL_WRITE_USER,
STATE_CTRL_WRITE_PASS,
STATE_CTRL_WRITE_SYST,
STATE_CTRL_WRITE_TYPE,
STATE_CTRL_WRITE_EPSV,
STATE_CTRL_WRITE_PASV,
STATE_CTRL_WRITE_PWD,
STATE_CTRL_WRITE_RETR,
STATE_CTRL_WRITE_SIZE,
STATE_CTRL_WRITE_CWD,
STATE_CTRL_WRITE_LIST,
STATE_CTRL_WRITE_QUIT,
// Data connection states:
STATE_DATA_CONNECT,
STATE_DATA_CONNECT_COMPLETE,
STATE_DATA_READ,
STATE_DATA_READ_COMPLETE,
STATE_NONE
};
// Resets the members of the transaction so it can be restarted.
void ResetStateForRestart();
// Establishes the data connection and switches to |state_after_connect|.
// |state_after_connect| should only be RETR or LIST.
void EstablishDataConnection(State state_after_connect);
void DoCallback(int result);
void OnIOComplete(int result);
// Executes correct ProcessResponse + command_name function based on last
// issued command. Returns error code.
int ProcessCtrlResponse();
int SendFtpCommand(const std::string& command,
const std::string& command_for_log,
Command cmd);
// Returns request path suitable to be included in an FTP command. If the path
// will be used as a directory, |is_directory| should be true.
std::string GetRequestPathForFtpCommand(bool is_directory) const;
// See if the request URL contains a typecode and make us respect it.
void DetectTypecode();
// Runs the state transition loop.
int DoLoop(int result);
// Each of these methods corresponds to a State value. Those with an input
// argument receive the result from the previous state. If a method returns
// ERR_IO_PENDING, then the result from OnIOComplete will be passed to the
// next state method as the result arg.
int DoCtrlResolveHost();
int DoCtrlResolveHostComplete(int result);
int DoCtrlConnect();
int DoCtrlConnectComplete(int result);
int DoCtrlRead();
int DoCtrlReadComplete(int result);
int DoCtrlWrite();
int DoCtrlWriteComplete(int result);
int DoCtrlWriteUSER();
int ProcessResponseUSER(const FtpCtrlResponse& response);
int DoCtrlWritePASS();
int ProcessResponsePASS(const FtpCtrlResponse& response);
int DoCtrlWriteSYST();
int ProcessResponseSYST(const FtpCtrlResponse& response);
int DoCtrlWritePWD();
int ProcessResponsePWD(const FtpCtrlResponse& response);
int DoCtrlWriteTYPE();
int ProcessResponseTYPE(const FtpCtrlResponse& response);
int DoCtrlWriteEPSV();
int ProcessResponseEPSV(const FtpCtrlResponse& response);
int DoCtrlWritePASV();
int ProcessResponsePASV(const FtpCtrlResponse& response);
int DoCtrlWriteRETR();
int ProcessResponseRETR(const FtpCtrlResponse& response);
int DoCtrlWriteSIZE();
int ProcessResponseSIZE(const FtpCtrlResponse& response);
int DoCtrlWriteCWD();
int ProcessResponseCWD(const FtpCtrlResponse& response);
int ProcessResponseCWDNotADirectory();
int DoCtrlWriteLIST();
int ProcessResponseLIST(const FtpCtrlResponse& response);
int DoCtrlWriteQUIT();
int ProcessResponseQUIT(const FtpCtrlResponse& response);
int DoDataConnect();
int DoDataConnectComplete(int result);
int DoDataRead();
int DoDataReadComplete(int result);
void RecordDataConnectionError(int result);
Command command_sent_;
CompletionCallback io_callback_;
CompletionCallback user_callback_;
BoundNetLog net_log_;
const FtpRequestInfo* request_;
FtpResponseInfo response_;
// Cancels the outstanding request on destruction.
SingleRequestHostResolver resolver_;
AddressList addresses_;
// User buffer passed to the Read method for control socket.
scoped_refptr<IOBuffer> read_ctrl_buf_;
scoped_ptr<FtpCtrlResponseBuffer> ctrl_response_buffer_;
scoped_refptr<IOBuffer> read_data_buf_;
int read_data_buf_len_;
// Buffer holding the command line to be written to the control socket.
scoped_refptr<IOBufferWithSize> write_command_buf_;
// Buffer passed to the Write method of control socket. It actually writes
// to the write_command_buf_ at correct offset.
scoped_refptr<DrainableIOBuffer> write_buf_;
int last_error_;
SystemType system_type_;
// Data type to be used for the TYPE command.
DataType data_type_;
// Detected resource type (file or directory).
ResourceType resource_type_;
// Initially we favour EPSV over PASV for transfers but should any
// EPSV fail, we fall back to PASV for the duration of connection.
bool use_epsv_;
AuthCredentials credentials_;
// Current directory on the remote server, as returned by last PWD command,
// with any trailing slash removed.
std::string current_remote_directory_;
uint16_t data_connection_port_;
ClientSocketFactory* socket_factory_;
scoped_ptr<StreamSocket> ctrl_socket_;
scoped_ptr<StreamSocket> data_socket_;
State next_state_;
// State to switch to after data connection is complete.
State state_after_data_connect_complete_;
};
} // namespace net
#endif // NET_FTP_FTP_NETWORK_TRANSACTION_H_
| [
"junhuac@hotmail.com"
] | junhuac@hotmail.com |
eab58b1d187bbc8260bb2f0bfad521cf86d7c74a | 68c0596591ca804f3f5d4cebc1332704ab89fd14 | /BibliotecaSTL/Pilha.cpp | bc75838c2e941dcbc0e0f908ee297b993874ee39 | [] | no_license | Daniel-Fonseca-da-Silva/C-Basic-Codes | dcf6cbb3145f5fdcba1465f8a92c498400bef2bd | f20af5e636a236e07f35c4c49d12d2a8fb47ac5c | refs/heads/master | 2020-06-23T08:37:00.501384 | 2019-07-29T03:56:23 | 2019-07-29T03:56:23 | 198,572,860 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 555 | cpp | #include <iostream>
#include <stack> // pilha
// Pilha retira o primeiro elemento do topo
// Primeiro que entra é o último que sai (first in last out)
using namespace std;
int main()
{
stack<double> pilha;
pilha.push(3.14);
pilha.push(5.123);
pilha.push(10.56);
pilha.pop(); // Retira 3.14 do topo
cout << "Topo: " << pilha.top() << endl;
cout << "Tamanho da pilha: " << pilha.size() << endl;
if(pilha.empty())
{
std::cout << "Pilha vazia: " << '\n';
}
else
{
std::cout << "Pilha não vazia: " << '\n';
}
return 0;
}
| [
"developer-web@programmer.net"
] | developer-web@programmer.net |
a1a2ea4f364cf96de37277b7b564c5f2d5da6fad | fb2337d616b5e121d66b0b59b4222d2eec9d7290 | /src/cpp/206. Reverse Linked List.cpp | caa3f84ef6dc520dd0a296f68c36af248f0f1356 | [
"MIT"
] | permissive | asdlei99/D.S.A-Leet | 02348b33bf4a7a8a4f673de9a087d8557471af59 | be19c3ccc1f704e75590786fdfd4cd3ab4818d4f | refs/heads/master | 2020-09-24T15:47:03.756271 | 2019-03-29T01:34:37 | 2019-03-29T01:34:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 681 | cpp | /*
Reverse a singly linked list.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <common.hpp>
class Solution
{
public:
ListNode *reverseList(ListNode *head)
{
if (head == NULL)
{
return NULL;
}
ListNode *pre = head;
ListNode *node = head->next;
ListNode *next = NULL;
pre->next = NULL;
while (node != NULL)
{
next = node->next;
node->next = pre;
pre = node;
node = next;
}
return pre;
}
};
//O(N) | [
"x-jj@foxmail.com"
] | x-jj@foxmail.com |
137e6ba78c4bd25145f987530a4b8f4daf98a295 | 59515f3d82033ed774c135a5310ed86f7db8b7f7 | /mainwindow.h | 8c77496833d1743f0fa21a1c3b628cb6df0835b4 | [] | no_license | CyberMakaron/2019_VT-22_Klesov_Makar_2 | e3295a27466debe43295686e46987a5937a25fa1 | e9c2de2618e906783929f301b9c2d30d276dcd20 | refs/heads/master | 2020-05-23T19:18:39.123124 | 2019-05-22T21:12:50 | 2019-05-22T21:12:50 | 186,909,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 737 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QString>
#include <QPixmap>
#include "dir_imagesworker.h"
#include "shortcutworker.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
void setImage(QString img);
~MainWindow();
private slots:
void on_openFolder_triggered();
void on_previous_img_clicked();
void on_next_img_clicked();
void on_addShortcut_triggered();
void on_Shortcut_triggered();
void on_removeShortcut_triggered();
private:
Ui::MainWindow *ui;
DirImagesWorker dir_img_w;
ShortcutWorker shortcut_w;
int mode;
};
#endif // MAINWINDOW_H
| [
"makrusim@yandex.ru"
] | makrusim@yandex.ru |
3665d4f7b455df893765c1e38391e9757ade0639 | f65ce9e212064d6c27c7f9bd13684b83fef58d83 | /Softrast/src/App.h | 8d3a8653f6b115cf7b6858a00f8fd674953d9749 | [
"MIT"
] | permissive | RickvanMiltenburg/SoftRast | 9722d2bda7b9fcfe2bf5494b09de6bbf99e27237 | e14b74804c052bb448058808cbb6dd06616ba585 | refs/heads/master | 2020-05-18T18:00:55.752279 | 2015-05-18T14:05:28 | 2015-05-18T14:05:28 | 35,819,422 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | h | #pragma once
#include <stdint.h>
#include <d3d11.h>
#include "RenderTarget.h"
class App
{
public:
App ( ID3D11Device* device, ID3D11DeviceContext* deviceContext, ID3D11RenderTargetView** backBuffer, ID3D11Texture2D** backBufferTexture );
~App ( );
bool LoadModel ( const char* path );
void OnResize ( uint32_t width, uint32_t height );
void GUITick ( float cpuDeltaTimeSeconds, float gpuDeltaTimeSeconds );
void Tick ( float cpuDeltaTimeSeconds, float gpuDeltaTimeSeconds );
private:
ID3D11Device* m_Device;
ID3D11DeviceContext* m_DeviceContext;
ID3D11RenderTargetView** m_BackBuffer;
ID3D11Texture2D** m_BackBufferTexture;
ID3D11VertexShader* m_FinalOutputVertexShader;
ID3D11PixelShader* m_FinalOutputPixelShader;
ID3D11SamplerState* m_Sampler;
ID3D11Buffer* m_IndexBuffer;
RenderTarget* m_IntermediateRenderTarget = nullptr;
DepthRenderTarget* m_DepthRenderTarget;
uint32_t m_ScreenWidth, m_ScreenHeight;
}; | [
"rick@milty.nl"
] | rick@milty.nl |
f1bf06e81bbe9e48552823d8f040ccc6bff88791 | 763269f66f7e34a21b4cf1eee065984d9ab43406 | /RC_S620S_Test/RC_S620S_Test.ino | 04d9ee7dc3380ce9235fd37ae5ba6f0070133a6e | [] | no_license | yukusakabe/HomeSensorNetwork | 44ad57f8fadc8f12d8ed36b9d340fc8eb786ff97 | 098f751b0315fbf9fdbff1ab09d9019a15de40fa | refs/heads/master | 2020-05-20T00:23:33.841505 | 2013-06-10T19:59:07 | 2013-06-10T19:59:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,488 | ino | #include <SoftwareSerial.h>
#include <TypeDefinition.h>
#include <LiquidCrystal.h>
#include <libRCS620S.h>
#define COMMAND_TIMEOUT 400
#define POLLING_INTERVAL 1000
#define LED_PIN 13
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
RCS620S rcs620s(NULL);
void setup() {
int ret;
pinMode(LED_PIN, OUTPUT); // for Polling Status
digitalWrite(LED_PIN, LOW);
Serial.begin(115200); // for RC-S620/S
lcd.begin(16, 2); // for LCD
// initialize RC-S620/S
ret = rcs620s.initDevice();
while (!ret) {} // blocking
}
void loop() {
int ret, i;
uint8_t response[RCS620S_MAX_CARD_RESPONSE_LEN], responselen;
// Polling
digitalWrite(LED_PIN, HIGH);
rcs620s.timeout = COMMAND_TIMEOUT;
ret = rcs620s.pollingTypeA();
lcd.clear();
/*
if(ret) {
lcd.print("NFCID:");
lcd.setCursor(0, 1);
for(i = 0; i < rcs620s.nfcidlen; i++)
{
if(rcs620s.idm[i] / 0x10 == 0) lcd.print(0);
lcd.print(rcs620s.nfcid[i], HEX);
}
} else {
lcd.print("Polling...");
}*/
//ret = rcs620s.cardDataExchange((const uint8_t*)"\xa2\x06\x01\x02\x03\x04", 6, response, &responselen);
ret = rcs620s.cardDataExchange((const uint8_t*)"\x30\x06", 2, response);
if(ret) {
lcd.print("Response:");
lcd.setCursor(0, 1);
for(i = 0; i < 4; i++)
{
lcd.print(response[i], HEX);
}
} else {
lcd.print("Miss...");
}
rcs620s.rfOff();
digitalWrite(LED_PIN, LOW);
delay(POLLING_INTERVAL);
}
| [
"yu@kskb.jp"
] | yu@kskb.jp |
4c144649924ed465079b211bde3170611940e0f9 | f3cc7fafad9d507bd608fb1c15fc792fd07f4615 | /src/Collisions/CollisionalFusionDD.cpp | 770e262337b3cf79624f5615f01e9271855fee47 | [] | no_license | michaeltouati/Smilei | 2eb3367b950bc4defe7a023bc802e169f6bf95a9 | e551c9640859e11df33211c37d06f83b65773132 | refs/heads/master | 2021-11-29T22:35:00.808182 | 2021-10-08T13:07:14 | 2021-10-08T13:07:14 | 235,618,233 | 0 | 0 | null | 2020-01-22T16:45:01 | 2020-01-22T16:45:00 | null | UTF-8 | C++ | false | false | 4,079 | cpp | #include "CollisionalFusionDD.h"
#include "Collisions.h"
#include "Species.h"
#include "Patch.h"
#include <cmath>
using namespace std;
// Coefficients used for energy interpolation
// The list of energies is in logarithmic scale,
// with Emin=1 keV, Emax=631 MeV and npoints=50.
const int CollisionalFusionDD::npoints = 50;
const double CollisionalFusionDD::npointsm1 = ( double )( npoints-1 );
const double CollisionalFusionDD::a1 = log(511./(2.*2.013553)); // = ln(me*c^2 / Emin / n_nucleons)
const double CollisionalFusionDD::a2 = 3.669039; // = (npoints-1) / ln( Emax/Emin )
const double CollisionalFusionDD::a3 = log(511./0.7/(2.*2.013553));; // = ln(me*c^2 / Eref / n_nucleons)
// Log of cross-section in units of 4 pi re^2
const double CollisionalFusionDD::DB_log_crossSection[50] = {
-27.307, -23.595, -20.383, -17.607, -15.216, -13.167, -11.418, -9.930, -8.666, -7.593,
-6.682, -5.911, -5.260, -4.710, -4.248, -3.858, -3.530, -3.252, -3.015, -2.814, -2.645,
-2.507, -2.398, -2.321, -2.273, -2.252, -2.255, -2.276, -2.310, -2.352, -2.402, -2.464,
-2.547, -2.664, -2.831, -3.064, -3.377, -3.773, -4.249, -4.794, -5.390, -6.021, -6.677,
-7.357, -8.072, -8.835, -9.648, -10.498, -11.387, -12.459
};
// Constructor
CollisionalFusionDD::CollisionalFusionDD(
Params *params,
vector<Particles*> product_particles,
vector<unsigned int> product_species,
double rate_multiplier
)
: CollisionalNuclearReaction(params, &product_particles, &product_species, rate_multiplier)
{
}
// Cloning constructor
CollisionalFusionDD::CollisionalFusionDD( CollisionalNuclearReaction *NR )
: CollisionalNuclearReaction( NR )
{
}
double CollisionalFusionDD::crossSection( double log_ekin )
{
// Interpolate the total cross-section at some value of ekin = m1(g1-1) + m2(g2-1)
double x = a2*( a1 + log_ekin );
double cs;
// if energy below Emin, approximate to 0.
if( x < 0. ) {
cs = 0.;
}
// if energy within table range, interpolate
else if( x < npointsm1 ) {
int i = int( x );
double a = x - ( double )i;
cs = exp(
( DB_log_crossSection[i+1]-DB_log_crossSection[i] )*a + DB_log_crossSection[i]
);
}
// if energy above table range, extrapolate
else {
double a = x - npointsm1;
cs = exp(
( DB_log_crossSection[npoints-1]-DB_log_crossSection[npoints-2] )*a + DB_log_crossSection[npoints-1]
);
}
return cs;
}
void CollisionalFusionDD::makeProducts(
Random* random, // Access to random numbers
double ekin, double log_ekin, // total kinetic energy and its natural log
double tot_charge, // total charge
std::vector<Particles*> &particles, // List of Particles objects to store the reaction products
std::vector<double> &new_p_COM, // List of gamma*v of reaction products in COM frame
std::vector<short> &q, // List of charges of reaction products
std::vector<double> &sinX, // List of sin of outgoing angle of reaction products
std::vector<double> &cosX // List of cos of outgoing angle of reaction products
) {
double U = random->uniform2(); // random number ]-1,1]
double U1 = abs( U );
bool up = U > 0.;
// Sample the products angle from empirical fits
double lnE = a3 + log_ekin;
double alpha = lnE < 0. ? 1. : exp(-0.024*lnE*lnE);
double one_m_cosX = alpha*U1 / sqrt( (1.-U1) + alpha*alpha*U1 );
cosX = { 1. - one_m_cosX };
sinX = { sqrt( one_m_cosX * (1.+cosX[0]) ) };
// Calculate the resulting momenta from energy / momentum conservation
const double Q = 6.397; // Qvalue
const double m_n = 1838.7;
const double m_He = 5497.9;
double p_COM = { sqrt(
(ekin+Q) * (ekin+Q+2.*m_n) * (ekin+Q+2.*m_He) * (ekin+Q+2.*m_n+2.*m_He) )
/ ( ( ekin+Q+m_n+m_He ) * (2.*m_He)
) };
// Set particle properties
q = { (short) tot_charge };
particles = { product_particles_[0] }; // helium3
if( up ) {
new_p_COM = { p_COM };
} else {
new_p_COM = { -p_COM };
}
}
| [
"frederic.perez@polytechnique.edu"
] | frederic.perez@polytechnique.edu |
95a21d796bda56e0e7ea2fd477905e76111afe4b | 2586a6db26d414dfbfeee28d9eeeaf50c13a3941 | /strobingled.ino | d2ddf66d9dc3eb0d969ffbc35aae9fe2527cffa8 | [] | no_license | minakhan01/ClockArduinoCode | 334b6e9221d499498978611b6402494fda45d452 | 68043e47fefe239de9ed1c81c5539668119f1fb1 | refs/heads/master | 2021-01-20T06:59:55.981210 | 2017-05-02T19:29:10 | 2017-05-02T19:29:10 | 89,946,412 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,124 | ino | // Stroboscopic Tachometer
// Ed Nisley - KE4ANU - December 2012
//----------
// Pin assignments
const byte PIN_KNOB_A = 2; // knob A switch - must be on ext interrupt 2
const byte PIN_KNOB_B = 4; // .. B switch
const byte PIN_BUTTONS = A5; // .. push-close momentary switches
const byte PIN_STROBE = 9; // LED drive, must be PWM9 = OCR1A using Timer1
const byte PIN_PWM10 = 10; // drivers for LED strip, must turn these off...
const byte PIN_PWM11 = 11;
const byte PIN_SYNC = 13; // scope sync
//----------
// Constants
const int UPDATEMS = 10; // update LEDs only this many ms apart
#define TCCRxB_CS 0x03 // Timer prescaler CS=3 -> 1:64 division
const float TICKPD = 64.0 * 62.5e-9; // basic Timer1 tick rate: prescaler * clock
enum KNOB_STATES {KNOB_CLICK_0,KNOB_CLICK_1};
// ButtonThreshold must have N_BUTTONS elements, last = 1024
enum BUTTONS {SW_KNOB, B_1, B_2, B_3, B_4, N_BUTTONS};
const word ButtonThreshold[] = {265/2, (475+265)/2, (658+475)/2, (834+658)/2, (1023+834)/2, 1024};
//----------
// Globals
float FlashLength = 0.1e-3; // strobe flash duration in seconds
word FlashLengthCt = FlashLength / TICKPD; // ... in Timer1 ticks
float FlashFreq = 50.0; // strobe flash frequency in Hz
float FlashPd = 1.0 / FlashFreq; // ... period in sec
word FlashPdCt = FlashPd / TICKPD; // ... period in Timer1 ticks
float FreqIncr = 1.0; // default frequency increment
const float FreqMin = 4.0;
const float FreqMax = 1.0/(4.0*FlashLength);
volatile char KnobCounter = 0;
volatile char KnobState;
byte Button, PrevButton;
unsigned long MillisNow;
unsigned long MillisThen;
//-- Helper routine for printf()
int s_putc(char c, FILE *t) {
Serial.write(c);
}
//-- Knob interrupt handler
void KnobHandler(void)
{
byte Inputs;
Inputs = digitalRead(PIN_KNOB_B) << 1 | digitalRead(PIN_KNOB_A); // align raw inputs
// Inputs ^= 0x02; // fix direction
switch (KnobState << 2 | Inputs) {
case 0x00 : // 0 00 - glitch
break;
case 0x01 : // 0 01 - UP to 1
KnobCounter++;
KnobState = KNOB_CLICK_1;
break;
case 0x03 : // 0 11 - DOWN to 1
KnobCounter--;
KnobState = KNOB_CLICK_1;
break;
case 0x02 : // 0 10 - glitch
break;
case 0x04 : // 1 00 - DOWN to 0
KnobCounter--;
KnobState = KNOB_CLICK_0;
break;
case 0x05 : // 1 01 - glitch
break;
case 0x07 : // 1 11 - glitch
break;
case 0x06 : // 1 10 - UP to 0
KnobCounter++;
KnobState = KNOB_CLICK_0;
break;
default : // something is broken!
KnobCounter = 0;
KnobState = KNOB_CLICK_0;
}
}
//-- Read and decipher analog switch inputs
// returns N_BUTTONS if no buttons pressed
byte ReadButtons(int PinNumber) {
word RawButton;
byte ButtonNum;
RawButton = analogRead(PinNumber);
for (ButtonNum = 0; ButtonNum <= N_BUTTONS; ButtonNum++){
if (RawButton < ButtonThreshold[ButtonNum])
break;
}
return ButtonNum;
}
//------------------
// Set things up
void setup() {
pinMode(PIN_SYNC,OUTPUT);
digitalWrite(PIN_SYNC,LOW); // show we arrived
analogWrite(PIN_PWM10,0); // turn off other PWM outputs
analogWrite(PIN_PWM11,0);
analogWrite(PIN_STROBE,1); // let Arduino set up default Timer1 PWM
TCCR1B = 0; // turn off Timer1 for strobe setup
TCCR1A = 0x82; // clear OCR1A on match, Fast PWM, lower WGM1x = 14
ICR1 = FlashPdCt;
OCR1A = FlashLengthCt;
TCNT1 = FlashLengthCt - 1;
TCCR1B = 0x18 | TCCRxB_CS; // upper WGM1x = 14, Prescale 1:64, start Timer1
pinMode(PIN_KNOB_B,INPUT_PULLUP);
pinMode(PIN_KNOB_A,INPUT_PULLUP);
KnobState = digitalRead(PIN_KNOB_A);
Button = PrevButton = ReadButtons(PIN_BUTTONS);
attachInterrupt((PIN_KNOB_A - 2),KnobHandler,CHANGE);
Serial.begin(9600);
fdevopen(&s_putc,0); // set up serial output for printf()
printf("Stroboscope Tachometer\r\nEd Nisley - KE4ZNU - December 2012\r\n");
printf("Frequency: %d.%02d\nPulse duration: %d us\n",
(int)FlashFreq,(int)(100.0 * (FlashFreq - trunc(FlashFreq))),
(int)(1e6 * FlashLength));
MillisThen = millis();
}
//------------------
// Run the test loop
void loop() {
MillisNow = millis();
if ((MillisNow - MillisThen) > UPDATEMS) {
digitalWrite(PIN_SYNC,HIGH);
Button = ReadButtons(PIN_BUTTONS);
if (PrevButton != Button) {
if (Button == N_BUTTONS) {
// printf("Button %d released\n",PrevButton);
FreqIncr = 1.0;
}
else
// printf("Button %d pressed\n",Button);
// if (Button == SW_KNOB)
FreqIncr = 0.01;
PrevButton = Button;
}
if (KnobCounter) {
FlashFreq += (float)KnobCounter * FreqIncr;
KnobCounter = 0;
FlashFreq = constrain(FlashFreq,FreqMin,FreqMax);
FlashFreq = round(100.0 * FlashFreq) / 100.0;
FlashPd = 1.0 / FlashFreq;
FlashPdCt = FlashPd / TICKPD;
noInterrupts();
TCCR1B &= 0xf8; // stop Timer1
ICR1 = FlashPdCt; // set new period
TCNT1 = FlashPdCt - 1; // force immediate update
TCCR1B |= TCCRxB_CS; // start Timer1
interrupts();
printf("Frequency: %d.%02d\n",
(int)FlashFreq,(int)(100.0 * (FlashFreq - trunc(FlashFreq))));
}
digitalWrite(PIN_SYNC,LOW);
MillisThen = MillisNow;
}
}
| [
"gordo@ALIENWARE-15-R3.mit.edu"
] | gordo@ALIENWARE-15-R3.mit.edu |
6f73a85619583c8550dfe7251e4d14d0a55be431 | 786de89be635eb21295070a6a3452f3a7fe6712c | /psddl_psana/tags/V00-03-00/src/princeton.ddl.cpp | e319a983a16e8a0f276e58caaf9c08c154e700fd | [] | no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 280 | cpp |
// *** Do not edit this file, it is auto-generated ***
#include <cstddef>
#include "psddl_psana/princeton.ddl.h"
namespace Psana {
namespace Princeton {
ConfigV1::~ConfigV1() {}
ConfigV2::~ConfigV2() {}
FrameV1::~FrameV1() {}
} // namespace Princeton
} // namespace Psana
| [
"salnikov@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7"
] | salnikov@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7 |
9c5a3c5de2737603ad4f1535e4d201a8046e2c9e | 0b77403b8605b49fe26d3888c60b70f509b91bb7 | /cad/elar_operator.cpp | 9dab29a664fcd7b1d8da8a1c3f7d0cc61d1ea161 | [] | no_license | wb-finalking/sweeping_based_on_Brep | 747376cbeb6a931b705f3968d2ecf9648aa012d4 | c12e85b277ba05f643ef7f780a5f91d3ebd9779e | refs/heads/master | 2021-08-24T10:58:04.139730 | 2017-12-09T11:12:19 | 2017-12-09T11:12:19 | 110,979,739 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,156 | cpp | #include "elar_operator.h"
#include <cstdio>
Solid *ElarOperator::mvfs(double point[3], Vertex *&vertex)
{
Solid *solid = new Solid();
Face *face = new Face();
Loop *out_lp = new Loop();
vertex = new Vertex(point[0], point[1], point[2]);
vertex->id = solid->vnum;
out_lp->id = solid->lnum;
face->id = solid->fnum;
solid->vnum += 1;
solid->fnum += 1;
solid->lnum += 1;
solid->faces = face;
face->solid = solid;
face->out_lp = out_lp;
out_lp->face = face;
return solid;
}
HalfEdge *ElarOperator::mev(Vertex *sv, double point[3], Loop *loop)
{
Solid *solid = loop->face->solid;
Edge *edge = new Edge();
HalfEdge *half_l = new HalfEdge();
HalfEdge *half_r = new HalfEdge();
Vertex *ev = new Vertex(point[0], point[1], point[2]);
ev->id = solid->vnum;
solid->vnum += 1;
half_l->sv = sv;
half_l->ev = ev;
half_r->sv = ev;
half_r->ev = sv;
edge->half_l = half_l;
edge->half_r = half_r;
half_l->edge = edge;
half_r->edge = edge;
half_r->brother = half_l;
half_l->brother = half_r;
half_l->lp = loop;
half_r->lp = loop;
//add the new two halfedges into the loop
if (loop->halfedges == NULL)
{
half_l->next = half_r;
half_r->next = half_l;
half_l->pre = half_r;
half_r->pre = half_l;
loop->halfedges = half_l;
}
else
{
HalfEdge *thalf = loop->halfedges;
while (thalf->ev != sv)thalf = thalf->next;
half_r->next = thalf->next;
thalf->next->pre = half_r;
thalf->next = half_l;
half_l->pre = thalf;
half_l->next = half_r;
half_r->pre = half_l;
}
//add the edge into the edge list of solid
addEdgeIntoSolid(edge, solid);
return half_l;
}
Loop *ElarOperator::mef(Vertex *sv, Vertex *ev, Loop *loop, bool mark)
{
Solid *solid = loop->face->solid;
Edge *edge = new Edge();
HalfEdge *half_l = new HalfEdge();
HalfEdge *half_r = new HalfEdge();
Loop *newLoop = new Loop();
half_l->sv = sv;
half_l->ev = ev;
half_r->sv = ev;
half_r->ev = sv;
half_r->brother = half_l;
half_l->brother = half_r;
half_l->edge = edge;
half_r->edge = edge;
edge->half_l = half_l;
edge->half_r = half_r;
//add the new two halfedge into the loop
HalfEdge *thalf = loop->halfedges;
HalfEdge *tmpa, *tmpb, *tmpc;
while (thalf->ev != sv)thalf = thalf->next;
tmpa = thalf;
while (thalf->ev != ev)thalf = thalf->next;
tmpb = thalf;
thalf = thalf->next;
while (thalf->ev != ev)thalf = thalf->next;
tmpc = thalf;
//divide the big loop into two small loop
half_r->next = tmpa->next;
tmpa->next->pre = half_r;
tmpa->next = half_l;
half_l->pre = tmpa;
half_l->next = tmpb->next;
tmpb->next->pre = half_l;
tmpb->next = half_r;
half_r->pre = tmpb;
loop->halfedges = half_l;
newLoop->halfedges = half_r;
half_l->lp = loop;
half_r->lp = newLoop;
Face *face = new Face();
newLoop->id = solid->lnum;
solid->lnum += 1;
addFaceIntoSolid(face, solid);
addLoopIntoFace(newLoop, face);
addEdgeIntoSolid(edge, solid);
return loop;
}
Loop *ElarOperator::kemr(Vertex *sv, Vertex *ev, Loop *loop)
{
HalfEdge *tmpa, *tmpb, *hal;
Face *face = loop->face;
Loop *inlp = new Loop();
Solid *solid = loop->face->solid;
hal = loop->halfedges;
while (hal->sv != sv || hal->ev != ev)hal = hal->next;
tmpa = hal;
while (hal->sv != ev || hal->ev != sv)hal = hal->next;
tmpb = hal;
tmpb->pre->next = tmpa->next;
tmpa->pre->next = tmpb->next;
loop->face->solid->faces->out_lp->halfedges = tmpa->pre;
inlp->halfedges = tmpb->pre;
tmpb->pre->lp = inlp;
inlp->id = solid->lnum;
solid->lnum += 1;
addLoopIntoFace(inlp, face);
delete tmpa;
delete tmpb;
return NULL;
}
void ElarOperator::kfmrh(Face *fa, Face *fb)
{
Loop *loop = fb->out_lp;
addLoopIntoFace(loop, fa);
fa->solid->lnum -= 1;
fa->solid->fnum -= 1;
Solid *solid = fa->solid;
Face *face = solid->faces;
if (face == fb)
{
solid->faces = face->next;
}
else
{
Face *tf = face;
while (face != fb && face != NULL)
{
tf = face;
face = face->next;
}
tf->next = face->next;
}
//delete fb;
}
void ElarOperator::sweep(Solid* solid,double dir[3], double d)
{
Vertex *startv, *nextv, *upv, *upprev;
HalfEdge *he, *suphe, *uphe;
double point[3];
int num = 0;
Face* f = solid->faces->next;
while (f != NULL)
{
num++;
f = f->next;
}
f = solid->faces->next;
for (int i = 0; i < num;i++)
{
Loop *loop = f->out_lp;
f = f->next;
he = loop->halfedges;
startv = he->sv;
point[0] = startv->coordinate[0] + d*dir[0];
point[1] = startv->coordinate[1] + d*dir[1];
point[2] = startv->coordinate[2] + d*dir[2];
suphe = mev(startv, point, loop);
upprev = suphe->ev;
he = he->next;
nextv = he->sv;
Loop *lp = loop;
while (nextv != startv)
{
point[0] = nextv->coordinate[0] + d*dir[0];
point[1] = nextv->coordinate[1] + d*dir[1];
point[2] = nextv->coordinate[2] + d*dir[2];
uphe = mev(nextv, point, lp);
upv = uphe->ev;
lp = mef(upprev, upv, loop, false);
upprev = upv;
he = he->next;
nextv = he->sv;
}
mef(upprev, suphe->ev, loop, false);
}
f = solid->faces->next;
Face* tmpf=f;
for (int i = 1; i < num; i++)
{
f = f->next;
kfmrh(tmpf,f);
//addLoopIntoFace(f->out_lp, tmpf);
//tmpf->next = f->next;
}
}
inline void ElarOperator::addEdgeIntoSolid(Edge *edge, Solid *&solid)
{
Edge *te = solid->edges;
if (te == NULL)solid->edges = edge;
else{
while (te->next != NULL)te = te->next;
te->next = edge;
edge->pre = te;
}
}
inline void ElarOperator::addFaceIntoSolid(Face *face, Solid *&solid)
{
Face *tface = solid->faces;
if (tface == NULL)
{
solid->faces = face;
}
else
{
while (tface->next != NULL)tface = tface->next;
tface->next = face;
face->pre = tface;
}
face->solid = solid;
face->id = solid->fnum;
solid->fnum += 1;// increase the num of faces
}
inline void ElarOperator::addLoopIntoFace(Loop *loop, Face *face)
{
loop->face = face;
//there is only one out loop but there may have lots of inner loop
if (face->out_lp == NULL)
{
face->out_lp = loop;
}
else
{
Loop *tlp = face->inner_lp;
if (tlp == NULL)face->inner_lp = loop;
else
{
while (tlp->next != NULL)tlp = tlp->next;
tlp->next = loop;
loop->pre = tlp;
}
face->innum += 1;
}
}
| [
"wbyx7071009@163.com"
] | wbyx7071009@163.com |
e1492299cbaed00e13325d3c3b2ac4fddcc33c5d | 0d37a489416e75ff013ebec2fbc2fdad80a521ac | /lib-rdm/src/rdmdevicecontroller.cpp | 8c2cb9b47dfab58b147b0b81bf42a3a33d451b5c | [] | no_license | JohnSHoover/rpidmx512 | fc26f7ee9ead5c1a9cb4dbbac5b4963744d3353d | ed1416b693d28030ba9ae45a25adf0f280bfc70b | refs/heads/master | 2022-04-10T17:31:36.334680 | 2020-04-10T16:48:45 | 2020-04-10T16:48:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,978 | cpp | /**
* @file rdmdevicecontroller.cpp
*
*/
/* Copyright (C) 2017-2019 by Arjan van Vught mailto:info@orangepi-dmx.nl
*
* 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 <stdint.h>
#include <string.h>
#include "rdmdevicecontroller.h"
#include "rdmdevice.h"
#include "debug.h"
#ifndef ALIGNED
#define ALIGNED __attribute__ ((aligned (4)))
#endif
#if defined (H3)
static const char DEVICE_LABEL[] ALIGNED = "Orange Pi RDM Controller";
#else
static const char DEVICE_LABEL[] ALIGNED = "Raspberry Pi RDM Controller";
#endif
RDMDeviceController::RDMDeviceController(void) {
DEBUG_ENTRY
struct TRDMDeviceInfoData info;
info.data = (uint8_t *) DEVICE_LABEL;
info.length = sizeof(DEVICE_LABEL) - 1;
SetLabel(&info);
DEBUG_EXIT
}
RDMDeviceController::~RDMDeviceController(void) {
}
void RDMDeviceController::Init(void) {
DEBUG_ENTRY
RDMDevice::Init();
DEBUG_EXIT
}
void RDMDeviceController::Print(void) {
RDMDevice::Print();
}
| [
"Arjan.van.Vught@gmail.com"
] | Arjan.van.Vught@gmail.com |
3167ccf6e5b50889cd259f7d2e9fe70f35c7ba2f | 7fc9ca1aa8c9281160105c7f2b3a96007630add7 | /template.cpp | 3076c5a8cd36ce2830193cc88ca60a1cc58f617a | [] | no_license | PatelManav/Codeforces_Backup | 9b2318d02c42d8402c9874ae0c570d4176348857 | 9671a37b9de20f0f9d9849cd74e00c18de780498 | refs/heads/master | 2023-01-04T03:18:14.823128 | 2020-10-27T12:07:22 | 2020-10-27T12:07:22 | 300,317,389 | 2 | 1 | null | 2020-10-27T12:07:23 | 2020-10-01T14:54:31 | C++ | UTF-8 | C++ | false | false | 462 | cpp | /*May The Force Be With Me*/
#include <bits/stdc++.h>
#define ll long long
#define MOD 1000000007
#define endl '\n'
using namespace std;
ll N;
vector<ll> arr;
void Input(){
cin >> N, arr.clear(), arr.resize(N);
for(ll i = 0; i < N; i++)
cin >> arr[i];
}
void Solve(){
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll T = 1;
//cin >> T;
while(T--){
Input();
Solve();
}
return 0;
} | [
"helewrer3@gmail.com"
] | helewrer3@gmail.com |
30ef68d4be7387083d1dc1f141379145db42a532 | 6ccaee717224338ba1889619a4c73454785588b5 | /GFG Random Problems/Foldable Binary Tree.cpp | b92f4be8e596f04e9c8c411752634037d62b3b44 | [] | no_license | nikhil-seth/cp-log | 7dc69b15d79603637976018f8269d8ed11adb08a | faf123aa41096b19303ecaff00fbc2974491c32f | refs/heads/master | 2021-06-22T02:57:05.031734 | 2021-01-04T14:26:11 | 2021-01-04T14:26:11 | 143,634,576 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 435 | cpp | // https://practice.geeksforgeeks.org/problems/foldable-binary-tree/1
// Foldable Binary Tree
bool fn(node *r1,node *r2){
if(!r1 && !r2)
return 1;
if(!r1 || !r2)
return 0;
if(r1->left && !r2->right)
return 0;
if(r1->right && !r2->left)
return 0;
return fn(r1->left,r2->right) && fn(r1->right,r2->left);
}
bool isFoldable(struct node *root)
{
return fn(root->left,root->right);
} | [
"rootedguy24@gmail.com"
] | rootedguy24@gmail.com |
98e543e31f0d4e2529876231c8d724aa9908425d | 70b3436f940e9a28e8119f16ba121ac8a6352145 | /codeforces/archive/003/a.cpp | 14825b62b260be224fdff75d094571a76110866d | [] | no_license | Erumaru/ACM | 59f85d4861e3055da3a612065a4051beafed8798 | 8a61e387a595bb50d34c7ffb78f597e6a413aefe | refs/heads/master | 2021-04-26T16:20:13.555674 | 2016-11-22T18:12:05 | 2016-11-22T18:12:05 | 70,470,175 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,900 | cpp | #pragma comment(linker, "/STACK:64000000")
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <ctime>
#include <sstream>
#include <algorithm>
#include <functional>
#include <numeric>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#define ft first
#define st second
#define mp make_pair
#define pb push_back
#define sz(n) int(n.size())
#define all(n) n.begin(), n.end()
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int N = 1e5 + 123;
const int inf = 1e9 + 7;
const ll INF = 1e18 + 7;
vector <int> zf(string s)
{
int n = sz(s);
vector <int> z (n);
for (int i = 1, j = 0; i < n; i ++)
{
if (i < j + z[j]) z[i] = min(z[i - j], z[j] + j - i);
while (i + z[i] < n && s[z[i]] == s[z[i] + i]) z[i] ++;
if (i + z[i] > j + z[j]) j = i;
}
return z;
}
string s;
vector <int> z;
int t[4000100];
void build (int v, int tl, int tr)
{
if (tl == tr) t[v] = z[tl];
else
{
int mid = (tl + tr) / 2;
build (2 * v, tl, mid);
build (2 * v + 1, mid + 1, tr);
t[v] = max(t[2 * v], t[2 * v + 1]);
}
}
int get(int v, int tl, int tr, int l, int r)
{
if (tl > r || tr < l) return 0;
if (tl >= l && tr <= r) return t[v];
int mid = (tl + tr) / 2;
return max(get(2 * v, tl, mid, l, r), get(2 * v + 1, mid + 1, tr, l, r));
}
int main ()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> s;
z = zf(s);
int n = sz(s);
build (1, 0, n - 1);
//for (int i = 0; i < n; i ++) cout << z[i] << " ";
//cout << "\n";
int ans = 0;
for (int i = 2; i < n; i ++)
{
if (z[i] == sz(s) - i)
{
int cur = get(1, 0, n - 1, 1, i - 1);
//cout << cur << " ";
if (cur != inf && cur >= z[i])
{
ans = max(ans, z[i]);
}
}
}
if (ans == 0) cout << "Just a legend\n";
else cout << s.substr(0, ans) << "\n";
}
| [
"toremuratuly.abzal@gmail.com"
] | toremuratuly.abzal@gmail.com |
3c7cdeb936f4fd2c44ff3ff0b2eba29529681160 | 24316e8888a959dec8a4af3e98e86e96a454f025 | /include/threadedcanvas.h | b3d46c17be727a28c686d14149f99050c2c57c30 | [
"Apache-2.0"
] | permissive | aerccu/LedDisplay | a1b33c271e3a89ae61f2e68ca9641b92d8786dd8 | 2152e8d56b51123cff1cfc657a887d51a05c3a70 | refs/heads/master | 2020-06-06T19:45:26.260394 | 2020-04-26T14:37:41 | 2020-04-26T14:37:41 | 192,838,056 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,692 | h | /*
* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: 4; -*-
* Author : aerccu
* Created : 16.08.19
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef THREADEDCANVAS_H
#define THREADEDCANVAS_H
#include "thread.h"
#include "canvas.h"
namespace display {
class ThreadedCanvas : public Thread {
public:
ThreadedCanvas(Canvas* canvas) : running_(false), canvas_(canvas) {}
virtual ~ThreadedCanvas() {}
virtual void start(int rt_priority = 0, uint32_t affinity_mask = 0)
{
{
Mutexlock mLock(&mutex_);
running_ = true;
}
Thread::start(rt_priority, affinity_mask);
}
void stop()
{
Mutexlock mLock(&mutex_);
running_ = false;
}
virtual void run() = 0;
protected:
inline Canvas* canvas() { return canvas_; }
inline bool running()
{
Mutexlock mLock(&mutex_);
return running_;
}
private:
Mutex mutex_;
bool running_;
Canvas* const canvas_;
};
}
#endif // THEADEDCANVAS_H
| [
"aerccu@gmail.com"
] | aerccu@gmail.com |
144ffdbbbf1c194afd07c31ea87856ddb6f41d95 | 37097fdaecb287e965273b1eeb089db69d4c0ce1 | /src/planning/knowledge_representation/src/kdb_node.cpp | df7cfc6d35fa9ad88c49df2dc0b8cad7e5054319 | [
"BSD-3-Clause-Clear",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | RobotJustina/tmc_justina_docker | 9d5fc63188238608bc47ec896aae0fdd9e490223 | 8aa968a81ae4526f6f6c2d55b83954b57b28ea92 | refs/heads/main | 2023-06-01T04:37:55.193899 | 2021-06-27T04:23:21 | 2021-06-27T04:23:21 | 361,206,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,800 | cpp | #include <iostream>
#include <sstream>
#include "ros/ros.h"
#include "knowledge_msgs/kdbFilePath.h"
#include "std_msgs/Bool.h"
#include "std_msgs/Empty.h"
#include "std_msgs/String.h"
#include "std_msgs/ColorRGBA.h"
std::string locationsFilePath;
std::string objectsFilePath;
std::string categoriesFilePath;
std::string peopleFilePath;
bool srvLocationPath(knowledge_msgs::kdbFilePath::Request &req, knowledge_msgs::kdbFilePath::Response &res){
std::cout << "location server"<< std::endl;
res.kdb_file_path = locationsFilePath;
return true;
}
bool srvObjectPath(knowledge_msgs::kdbFilePath::Request &req, knowledge_msgs::kdbFilePath::Response &res){
std::cout << "objects server"<< std::endl;
res.kdb_file_path = objectsFilePath;
return true;
}
bool srvCategoryPath(knowledge_msgs::kdbFilePath::Request &req, knowledge_msgs::kdbFilePath::Response &res){
std::cout << "categories server"<< std::endl;
res.kdb_file_path = categoriesFilePath;
return true;
}
bool srvPeoplePath(knowledge_msgs::kdbFilePath::Request &req, knowledge_msgs::kdbFilePath::Response &res){
std::cout << "people server"<< std::endl;
res.kdb_file_path = peopleFilePath;
return true;
}
int main(int argc, char ** argv) {
std::cout << "Node for set kdb paths" << std::endl;
ros::init(argc, argv, "kdb_node");
ros::NodeHandle nh;
ros::Rate rate(10);
locationsFilePath = "";
for (int i = 0; i < argc; i++) {
std::string strParam(argv[i]);
if (strParam.compare("-l") == 0)
locationsFilePath = argv[++i];
}
objectsFilePath = "";
for (int i = 0; i < argc; i++) {
std::string strParam(argv[i]);
if (strParam.compare("-o") == 0)
objectsFilePath = argv[++i];
}
categoriesFilePath = "";
for (int i = 0; i < argc; i++) {
std::string strParam(argv[i]);
if (strParam.compare("-c") == 0)
categoriesFilePath = argv[++i];
}
peopleFilePath = "";
for (int i = 0; i < argc; i++) {
std::string strParam(argv[i]);
if (strParam.compare("-p") == 0)
peopleFilePath = argv[++i];
}
ros::ServiceServer serviceLocationPath = nh.advertiseService("/knowledge_representation/getLocationPath", srvLocationPath);
ros::ServiceServer serviceObjectPath = nh.advertiseService("/knowledge_representation/getObjectPath", srvObjectPath);
ros::ServiceServer serviceCategoryPath = nh.advertiseService("/knowledge_representation/getCategoryPath", srvCategoryPath);
ros::ServiceServer servicePeoplePath = nh.advertiseService("/knowledge_representation/getPeoplePath", srvPeoplePath);
while (ros::ok()) {
rate.sleep();
ros::spinOnce();
}
return 1;
}
| [
"jc.shogun.t6s@gmail.com"
] | jc.shogun.t6s@gmail.com |
6f23cfe4c5f012dfd215e8027eaa536b1727d920 | 969628b6cfc2f726fcbee28f19f47bcddb5cabfd | /走迷宫/tool.cpp | cfad40af869613eb6a563bc8a9e4b613a132a2b2 | [] | no_license | MallocGad/little-game | 94c04427ed7b179e0583c2c430d759052f05c8d7 | 4bb3a9be19a9f4f8b3095f10adb96ab94b4ad917 | refs/heads/master | 2021-01-15T12:59:21.642390 | 2017-08-09T12:55:04 | 2017-08-09T12:55:04 | 99,663,089 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,946 | cpp | /*******************************************
所需函数的实现
********************************************/
#include"tool.h"
Person::Person()
{
_edirection = UP;
_rPos = p_rPos = { 7,2 };
}
void Person::direction(char a[][11])
{
switch (_edirection)
{
case UP:
if (a[_rPos.x][_rPos.y + 1] == '1')
{
if (a[_rPos.x - 1][_rPos.y] == '1')
_edirection = LEFT;
}
else
_edirection = RIGHT;
break;
case LEFT:
if (a[_rPos.x - 1][_rPos.y] == '1') {
if (a[_rPos.x][_rPos.y - 1] == '1')
_edirection = DOWN;
}
else
_edirection = UP;
break;
case RIGHT:
if (a[_rPos.x + 1][_rPos.y] == '1')
{
if (a[_rPos.x][_rPos.y + 1] == '1')
_edirection = UP;
}
else
_edirection = DOWN;
break;
case DOWN:
if (a[_rPos.x][_rPos.y - 1] == '1')
{
if (a[_rPos.x + 1][_rPos.y] == '1')
_edirection = RIGHT;
}
else
_edirection = LEFT;
break;
default:cout << "erro" << endl; exit(0); break;
}
}
void Person::move(char a[][11])
{
p_rPos = _rPos;
step++;
switch (_edirection)
{
case UP:
_rPos.x--;
if (a[_rPos.x][_rPos.y] == '1')
_rPos.x++;
break;
case LEFT:_rPos.y--;
if (a[_rPos.x][_rPos.y] == '1')
_rPos.y++;
break;
case RIGHT:_rPos.y++;
if (a[_rPos.x][_rPos.y] == '1')
_rPos.y--;
break;
case DOWN:_rPos.x++;
if (a[_rPos.x][_rPos.y] == '1')
_rPos.x--;
break;
default:
cout << "erro!" << endl; exit(0);
break;
}
}
int Person::Juge()
{
if (_rPos.x == _exity && _rPos.y == _exitx)
{
return 1;
}
return 0;
}
Manp::Manp(char a[][11], int x, int y)
{
int i , j;
for (i = 0; i < x; i++)
{
for (j = 0; j < y; j++)
cout << a[i][j];
cout << endl;
}
}
void Manp::Drowp(struct Pos p, struct Pos p2,char e)
{
Gotoxy(p2.y, p2.x);
cout << '0';
Gotoxy(p.y, p.x);
cout << e;
}
void Manp::Gotoxy(int x, int y)
{
COORD Pos;
Pos.X = x;
Pos.Y = y;
HANDLE hout;
hout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hout, Pos);
} | [
"1165318097@qq.com"
] | 1165318097@qq.com |
5bfbbf7e528dc68db230ac4df9b570b1f27d9a2d | b8194fee4ddf498b2c1bd302ec4ba9466746250d | /build/Android/Debug/app/src/main/include/Fuse.SystemFont.Weight.h | ab880743dd7b10d6cc58bcdb21b432d2cb5ed2dc | [] | no_license | color0e/Fabric_Fuse_Project | e49e7371c9579d80c9ec96c1f2d3a90de7b52149 | 9b20a0347e5249315cf7af587e04234ec611c6be | refs/heads/master | 2020-03-30T16:49:34.363764 | 2018-10-03T16:26:28 | 2018-10-03T16:26:28 | 151,428,896 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 337 | h | // This file was generated based on '../../AppData/Local/Fusetools/Packages/Fuse.Common/1.9.0/SystemFont.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Int.h>
namespace g{
namespace Fuse{
// public enum SystemFont.Weight :38
uEnumType* SystemFont__Weight_typeof();
}} // ::g::Fuse
| [
"limjangsoon@naver.com"
] | limjangsoon@naver.com |
073e10196e543065c089b2527c2c23cf2370900e | 6cc10a9754ef04f5fa30bee1681ebe044312a881 | /includes/InputSource.hpp | b16feb9db8f44e36ba1fb21fd355c3358935a31d | [] | no_license | Adubedat/AbstractVM | 3955a5bad63b960266ba81b37709291958dbf07e | 7f04a7c422d62e12bfe7bf2d40b744f84bd8cbc7 | refs/heads/master | 2021-01-25T14:33:47.314535 | 2018-04-23T17:59:00 | 2018-04-23T17:59:00 | 123,711,795 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,025 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* InputSource.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adubedat <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/06 16:31:10 by adubedat #+# #+# */
/* Updated: 2018/03/07 19:32:11 by adubedat ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef INPUT_SOURCE_HPP
# define INPUT_SOURCE_HPP
# include <iostream>
# include <fstream>
class InputSource
{
public:
InputSource(void);
InputSource(InputSource const & src);
virtual ~InputSource(void);
static unsigned int getLineNbr();
virtual int getNextLine(std::string &line) = 0;
virtual bool isCin();
protected:
static unsigned int _lineNbr;
};
class FileInputSource : public InputSource
{
public:
FileInputSource(void);
FileInputSource(FileInputSource const & src);
FileInputSource(std::string file_name);
virtual ~FileInputSource(void);
std::ifstream *get_ifs(void) const;
virtual FileInputSource &operator=(FileInputSource const & rhs);
virtual int getNextLine(std::string &line);
private:
std::ifstream *_ifs;
};
class StandardInputSource : public InputSource
{
public:
StandardInputSource(void);
StandardInputSource(StandardInputSource const & src);
virtual ~StandardInputSource(void);
virtual StandardInputSource &operator=(StandardInputSource const & rhs);
virtual int getNextLine(std::string &line);
virtual bool isCin();
private:
int _eof;
};
#endif
| [
"arthur.dubedat@gmail.com"
] | arthur.dubedat@gmail.com |
601463a3f4a936ca6f5ed9a1a33f787917361316 | 3543b7f88aea464dc4b26148196e53c46b70d38e | /cgg06_Normal_Mapping_and_OBJ/Renderer3DRaycasting.h | a9ae288fd492e46bd234a34f2ebb770a2ff73672 | [] | no_license | vanish87/CGG | 77e76450062edd8743beda2bb80590bd5a172738 | b1f6f6d924c7bf08af078572f78a98fcad782f20 | refs/heads/master | 2020-09-04T21:31:46.534548 | 2015-09-13T23:50:12 | 2015-09-13T23:50:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 416 | h | #ifndef RENDERER3DRAYCASTING_H_
#define RENDERER3DRAYCASTING_H_
#include "Renderer3D.h"
class Color;
class Ray;
class Renderer3DRaycasting : public Renderer3D
{
private:
Color raycasting(Ray& ray, double* dist);
Renderer3DRaycasting(const Renderer3DRaycasting& src);
public:
Renderer3DRaycasting();
Renderer3DRaycasting(Camera3D& camera);
virtual ~Renderer3DRaycasting();
virtual void render();
};
#endif | [
"rumpf@student.tugraz.at"
] | rumpf@student.tugraz.at |
895e8f900ab69053fc48faaff37e9e79041f973d | 0160c375f0f49778fa2d58cf14595d581dbfc308 | /test/test.utils.cpp | ae8d8b9802dee1eb8fb0e180dfe4a03c218e49e6 | [
"MIT"
] | permissive | chensoft/libfs | 4d81c845b9264244ac5c12043ccc0c666de5a130 | 3288a865ffa71cfc197ea0fb54c042fa2c9546a6 | refs/heads/master | 2020-03-25T04:46:08.588642 | 2018-12-27T11:15:54 | 2018-12-27T11:15:54 | 143,412,033 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 910 | cpp | /**
* Created by Jian Chen
* @since 2018.09.03
* @author Jian Chen <admin@chensoft.com>
* @link http://chensoft.com
*/
#include "fs/fs.hpp"
#include "catch.hpp"
TEST_CASE("fs.utils")
{
CHECK(std::string(u8"\u9648\u5251") == "\xE9\x99\x88\xE5\x89\x91");
CHECK(fs::widen(u8"\u9648\u5251") == L"\u9648\u5251");
CHECK(fs::narrow(L"\u9648\u5251") == "\xE9\x99\x88\xE5\x89\x91");
CHECK(fs::prune("").empty());
CHECK(fs::prune("/") == "/");
CHECK(fs::prune("//") == "/");
CHECK(fs::prune("/usr/local") == "/usr/local");
CHECK(fs::prune("/usr/local/") == "/usr/local");
CHECK(fs::prune("/usr/local//") == "/usr/local");
CHECK(fs::prune("C:\\") == "C:\\");
CHECK(fs::prune("C:\\\\") == "C:\\");
CHECK(fs::prune("C:\\Windows") == "C:\\Windows");
CHECK(fs::prune("C:\\Windows\\") == "C:\\Windows");
CHECK(fs::prune("C:\\Windows\\\\") == "C:\\Windows");
} | [
"admin@chensoft.com"
] | admin@chensoft.com |
f45010a6e5b008d3fe2513dd36a06195dc0147f2 | b5b4d7b9afe4405d7c20c65b22a17a4201aa3765 | /src/Magnum/SceneGraph/MatrixTransformation3D.hpp | 916b72733eefcc66f2d781884bfaa718e0b137f4 | [
"MIT"
] | permissive | guangbinl/magnum | bfb8fbd949261092d0f9b3645ed2478a92544e98 | a5d58aaab74f6ecb5d6678055b280b831e045e59 | refs/heads/master | 2023-02-18T02:10:51.396888 | 2021-01-10T11:24:25 | 2021-01-10T11:24:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,148 | hpp | #ifndef Magnum_SceneGraph_MatrixTransformation3D_hpp
#define Magnum_SceneGraph_MatrixTransformation3D_hpp
/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020 Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/** @file
* @brief @ref compilation-speedup-hpp "Template implementation" for @ref MatrixTransformation3D.h
* @m_since{2020,06}
*/
#include "MatrixTransformation3D.h"
#include "Magnum/Math/Quaternion.h"
namespace Magnum { namespace SceneGraph {
/* These are here to avoid including Quaternion in MatrixTransformation3D.h */
template<class T> Object<BasicMatrixTransformation3D<T>>& BasicMatrixTransformation3D<T>::rotate(const Math::Quaternion<T>& quaternion) {
return transform(Math::Matrix4<T>::from(quaternion.toMatrix(), {}));
}
template<class T> Object<BasicMatrixTransformation3D<T>>& BasicMatrixTransformation3D<T>::rotateLocal(const Math::Quaternion<T>& quaternion) {
return transformLocal(Math::Matrix4<T>::from(quaternion.toMatrix(), {}));
}
}}
#endif
| [
"mosra@centrum.cz"
] | mosra@centrum.cz |
38c5dc7e95318507648e92b0226103c93feeaa62 | e49b23d9112411dd763311aed589ea47ab3a5029 | /src/stacker_attribute_buffer.cpp | 15f811dafa741fd421fd050d592e44150e16e517 | [
"MIT"
] | permissive | scullion/stacker | 754992aa9d583c5250a765f41ec22fad8c1bb380 | 541890f5c56971653138b991e70d0a64bbf9e852 | refs/heads/master | 2020-06-03T17:09:46.040380 | 2014-06-11T15:54:53 | 2014-06-11T15:54:53 | 20,300,216 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 52,340 | cpp | #include "stacker_attribute.h"
#include <cstddef>
#include <cstring>
#include <cfloat>
#include <algorithm>
#include "stacker_shared.h"
#include "stacker_util.h"
#include "stacker_attribute_buffer.h"
namespace stkr {
#pragma pack(push, 1)
/* Helper used to read attribute data located after the header in memory. */
union AttributeData {
int16_t int16;
int32_t int32;
float float32;
char string[1];
};
struct BufferEntry {
Attribute header;
AttributeData data;
};
#pragma pack(pop)
/* Constants used to form operator masks, used in validation. */
enum AttributeOperatorBit {
AOP_BIT_SET = 1 << AOP_SET,
AOP_BIT_OVERRIDE = 1 << AOP_OVERRIDE,
AOP_BIT_ADD = 1 << AOP_ADD,
AOP_BIT_SUBTRACT = 1 << AOP_SUBTRACT,
AOP_BIT_MULTIPLY = 1 << AOP_MULTIPLY,
AOP_BIT_DIVIDE = 1 << AOP_DIVIDE,
AOP_BIT_ASSIGNMENT = AOP_BIT_SET | AOP_BIT_OVERRIDE,
AOP_BIT_ADDITIVE = AOP_BIT_ADD | AOP_BIT_SUBTRACT,
AOP_BIT_MULTIPLICATIVE = AOP_BIT_MULTIPLY | AOP_BIT_DIVIDE,
AOP_BIT_ARITHMETIC = AOP_BIT_ADDITIVE | AOP_BIT_MULTIPLICATIVE
};
extern const char * const STORAGE_STRINGS[NUM_ATTRIBUTE_TYPES] =
{ "none", "int16", "int32", "float32", "string" };
/* Returns the attribute operator corresponding to a token, or -1 if the token
* is not an operator token. */
int token_to_attribute_operator(int name)
{
switch (name) {
case TOKEN_EQUALS:
return AOP_SET;
case TOKEN_COLON_EQUALS:
return AOP_OVERRIDE;
case TOKEN_PLUS_EQUALS:
return AOP_ADD;
case TOKEN_DASH_EQUALS:
return AOP_SUBTRACT;
case TOKEN_STAR_EQUALS:
return AOP_MULTIPLY;
case TOKEN_SLASH_EQUALS:
return AOP_DIVIDE;
}
return -1;
}
/* Returns the storage type and mode set of an attribute given its name. */
AttributeSemantic attribute_semantic(int name)
{
switch (name) {
case TOKEN_WIDTH:
case TOKEN_HEIGHT:
case TOKEN_MIN_WIDTH:
case TOKEN_MIN_HEIGHT:
case TOKEN_MAX_WIDTH:
case TOKEN_MAX_HEIGHT:
case TOKEN_BACKGROUND_WIDTH:
case TOKEN_BACKGROUND_HEIGHT:
case TOKEN_BACKGROUND_OFFSET_X:
case TOKEN_BACKGROUND_OFFSET_Y:
return ASEM_DIMENSON;
case TOKEN_GROW:
case TOKEN_SHRINK:
return ASEM_GROWTH_FACTOR;
case TOKEN_PADDING:
case TOKEN_PADDING_LEFT:
case TOKEN_PADDING_RIGHT:
case TOKEN_PADDING_TOP:
case TOKEN_PADDING_BOTTOM:
case TOKEN_MARGIN:
case TOKEN_MARGIN_LEFT:
case TOKEN_MARGIN_RIGHT:
case TOKEN_MARGIN_TOP:
case TOKEN_MARGIN_BOTTOM:
case TOKEN_LEADING:
case TOKEN_INDENT:
return ASEM_ABSOLUTE_DIMENSION;
case TOKEN_URL:
return ASEM_URL;
case TOKEN_ARRANGE:
case TOKEN_ALIGN:
case TOKEN_BACKGROUND_HORIZONTAL_ALIGNMENT:
case TOKEN_BACKGROUND_VERTICAL_ALIGNMENT:
return ASEM_ALIGNMENT;
case TOKEN_JUSTIFY:
return ASEM_JUSTIFICATION;
case TOKEN_FONT:
case TOKEN_MATCH:
return ASEM_STRING;
case TOKEN_CLASS:
return ASEM_STRING_SET;
case TOKEN_FONT_SIZE:
case TOKEN_BORDER_WIDTH:
return ASEM_ABSOLUTE_DIMENSION;
case TOKEN_COLOR:
case TOKEN_BACKGROUND_COLOR:
case TOKEN_BORDER_COLOR:
case TOKEN_SELECTION_COLOR:
case TOKEN_SELECTION_FILL_COLOR:
case TOKEN_TINT:
return ASEM_COLOR;
case TOKEN_GLOBAL:
case TOKEN_BOLD:
case TOKEN_ITALIC:
case TOKEN_UNDERLINE:
case TOKEN_ENABLED:
case TOKEN_CLIP_LEFT:
case TOKEN_CLIP_RIGHT:
case TOKEN_CLIP_TOP:
case TOKEN_CLIP_BOTTOM:
return ASEM_FLAG;
case TOKEN_BACKGROUND:
return ASEM_BACKGROUND;
case TOKEN_LAYOUT:
return ASEM_LAYOUT;
case TOKEN_CLIP:
return ASEM_EDGES;
case TOKEN_WHITE_SPACE:
return ASEM_WHITE_SPACE;
case TOKEN_WRAP:
return ASEM_WRAP_MODE;
case TOKEN_BACKGROUND_SIZE:
return ASEM_BACKGROUND_SIZE;
case TOKEN_BACKGROUND_BOX:
case TOKEN_CLIP_BOX:
return ASEM_BOUNDING_BOX;
case TOKEN_CURSOR:
return ASEM_CURSOR;
}
return ASEM_INVALID;
}
/* Returns a mask of the storage types permitted for a (semantic, mode)
* combination. */
static unsigned storage_mask(AttributeSemantic semantic, int mode)
{
switch (semantic) {
case ASEM_DIMENSON:
case ASEM_ABSOLUTE_DIMENSION:
case ASEM_GROWTH_FACTOR:
return STORAGE_BIT_NUMERIC;
case ASEM_REAL:
return STORAGE_BIT_FLOAT32;
case ASEM_STRING:
case ASEM_STRING_SET:
case ASEM_URL:
return mode != ADEF_UNDEFINED ? STORAGE_BIT_STRING :
STORAGE_BIT_NONE;
case ASEM_BACKGROUND:
if (mode == BGMODE_URL)
return STORAGE_BIT_STRING;
if (mode == BGMODE_COLOR)
return STORAGE_BIT_INT32;
return STORAGE_BIT_NONE;
case ASEM_COLOR:
return STORAGE_BIT_INT32;
case ASEM_FLAG:
case ASEM_ALIGNMENT:
case ASEM_JUSTIFICATION:
case ASEM_LAYOUT:
case ASEM_WHITE_SPACE:
case ASEM_WRAP_MODE:
case ASEM_BACKGROUND_SIZE:
case ASEM_BOUNDING_BOX:
case ASEM_CURSOR:
case ASEM_EDGES:
return STORAGE_BIT_NONE;
}
ensure(false);
return STORAGE_NONE;
}
/* Given an attribute value token, returns a number specifying any special
* interpretation that should be used during the value's validation and
* conversion. For example, a number might be a percentage, or a string might be
* a URL. */
ValueSemantic value_semantic(int type_token)
{
switch (type_token) {
case TOKEN_INTEGER:
case TOKEN_STRING:
case TOKEN_FLOAT:
return VSEM_NONE;
case TOKEN_BOOLEAN:
return VSEM_BOOLEAN;
case TOKEN_PERCENTAGE:
return VSEM_PERCENTAGE;
case TOKEN_COLOR_LITERAL:
return VSEM_COLOR;
case TOKEN_URL_LITERAL:
return VSEM_URL;
default:
if (is_enum_token(type_token))
return VSEM_TOKEN;
break;
}
return VSEM_INVALID;
}
/* Returns a mask of operators that can be applied to a particular kind of
* attribute. */
static unsigned supported_operators(AttributeSemantic semantic)
{
switch (semantic) {
case ASEM_DIMENSON:
case ASEM_ABSOLUTE_DIMENSION:
case ASEM_REAL:
return AOP_BIT_ASSIGNMENT | AOP_BIT_ARITHMETIC;
case ASEM_STRING:
case ASEM_URL:
return AOP_BIT_ASSIGNMENT | AOP_BIT_ADD;
case ASEM_EDGES:
case ASEM_STRING_SET:
return AOP_BIT_ASSIGNMENT | AOP_BIT_ADDITIVE;
case ASEM_COLOR:
return AOP_BIT_ASSIGNMENT | AOP_BIT_MULTIPLY;
default:
break;
}
return AOP_BIT_ASSIGNMENT;
}
/* True if 'mode' means "auto" for a particular attribute. */
bool is_auto_mode(int name, int mode)
{
AttributeSemantic semantic = attribute_semantic(name);
switch (semantic) {
case ASEM_DIMENSON:
case ASEM_ABSOLUTE_DIMENSION:
return (mode == DMODE_AUTO);
}
return false;
}
/* True if an attribute can be inherited from parent nodes. */
bool is_inheritable(int name)
{
switch (name) {
case TOKEN_LEADING:
case TOKEN_INDENT:
case TOKEN_ARRANGE:
case TOKEN_ALIGN:
case TOKEN_JUSTIFY:
case TOKEN_FONT:
case TOKEN_FONT_SIZE:
case TOKEN_COLOR:
case TOKEN_BORDER_COLOR:
case TOKEN_BACKGROUND_COLOR:
case TOKEN_SELECTION_COLOR:
case TOKEN_SELECTION_FILL_COLOR:
case TOKEN_TINT:
case TOKEN_BOLD:
case TOKEN_ITALIC:
case TOKEN_UNDERLINE:
case TOKEN_ENABLED:
case TOKEN_WHITE_SPACE:
case TOKEN_WRAP:
case TOKEN_CURSOR:
return true;
}
return false;
}
AttributeAssignment make_assignment(Token name, int value,
ValueSemantic vs, AttributeOperator op)
{
AttributeAssignment assignment;
assignment.name = name;
assignment.op = op;
variant_set_integer(&assignment.value, value, vs);
return assignment;
}
AttributeAssignment make_assignment(Token name, unsigned value,
ValueSemantic vs, AttributeOperator op)
{
return make_assignment(name, (int)value, vs, op);
}
AttributeAssignment make_assignment(Token name, float value,
ValueSemantic vs, AttributeOperator op)
{
AttributeAssignment assignment;
assignment.name = name;
assignment.op = op;
variant_set_float(&assignment.value, value, vs);
return assignment;
}
AttributeAssignment make_assignment(Token name, const char *value,
ValueSemantic vs, AttributeOperator op)
{
AttributeAssignment assignment;
assignment.name = name;
assignment.op = op;
variant_set_string(&assignment.value, value, vs);
return assignment;
}
/* Parses a string of space- or comma-delimited tokens into the attribute
* storage form for string sets: zero or more null-terminated strings
* concatenated end to end, terminated by an extra null at the end. Returns
* a negative error code if the string has inconsistent delimiters. */
int parse_string_list(const char *s, int length, char *buffer,
unsigned buffer_size)
{
int result_length = 0, elements = 0;
char delimiter = 0;
for (int i = 0; i != length; ) {
while (i != length && isspace(s[i]))
i++;
if (i == length)
break;
if (elements != 0 && ((delimiter != 0) || s[i] == ',')) {
if ((delimiter != 0) != (s[i] == ',')) {
if (elements > 1)
return -1;
delimiter = s[i];
}
do { ++i; } while (i != length && isspace(s[i]));
}
int start = i;
while (i != length && !isspace(s[i]) && s[i] != ',')
++i;
if (i != start) {
unsigned token_length = i - start;
if (buffer != NULL && result_length + token_length + 1 < buffer_size) {
memcpy(buffer + result_length, s + start, token_length);
buffer[result_length + token_length] = '\0';
}
result_length += token_length + 1;
}
elements++;
}
if (buffer != NULL) {
if ((unsigned)result_length >= buffer_size)
buffer[buffer_size - 1] = '\0';
else
buffer[result_length] = '\0';
}
return result_length;
}
static bool string_set_contains(const char *s, unsigned length, const char *p)
{
const char *end = s + length;
while (s != end) {
if (0 == strcmp(p, s))
return true;
s += 1 + strlen(s);
}
return false;
}
/* Eliminates duplicates from a string set, returning the size delta. */
static int string_set_unique(char *s, unsigned length)
{
char *d = s;
while (*s != '\0') {
unsigned item_length = 1 + strlen(s);
length -= item_length;
if (!string_set_contains(s + item_length, length, s)) {
memmove(d, s, item_length);
d += item_length;
}
s += item_length;
}
*d = '\0';
return d - s;
}
/* Deletes entries in A that are part of B. A and B are null-terminated lists
* of null-terminated strings. Returns the (zero or negative) adjustment in
* the number of characters in A. */
static int string_set_difference(char *a, const char *b, unsigned length_b)
{
unsigned length_p;
const char *p;
for (p = a; *p != '\0'; p += 1 + length_p) {
length_p = strlen(p);
if (!string_set_contains(b, length_b, p)) {
strcpy(a, p);
a += length_p + 1;
}
}
*a = '\0';
return a - p;
}
static const unsigned VALIDATION_BUFFER_SIZE = 1024;
/* Temporary container for the result of validation. */
struct ValidationResult {
AttributeSemantic semantic;
AttributeStorage storage;
char buffer[VALIDATION_BUFFER_SIZE];
AttributeData *data;
int size;
int capacity;
int terminators;
};
static void vresult_init(ValidationResult *vr)
{
vr->storage = STORAGE_NONE;
vr->capacity = 0;
vr->size = 0;
vr->data = (AttributeData *)vr->buffer;
vr->terminators = 0;
}
static void vresult_set_static(ValidationResult *vr, const char *s, unsigned length)
{
vr->storage = STORAGE_STRING;
vr->data = (AttributeData *)s;
vr->size = (int)length;
vr->capacity = 0;
vr->terminators = 1;
}
static char *vresult_allocate(ValidationResult *vr, unsigned capacity)
{
vr->storage = STORAGE_STRING;
if (capacity > VALIDATION_BUFFER_SIZE) {
vr->data = (AttributeData *)(new char[capacity]);
vr->capacity = (int)capacity;
} else {
vr->data = (AttributeData *)vr->buffer;
vr->capacity = -int(capacity);
}
return vr->data->string;
}
static void vresult_free(ValidationResult *vr)
{
if (vr->capacity > 0)
delete [] (char *)vr->data;
}
/* Performs validation checks common to all attributes. A return value <= 0
* indicates that validation has succeded or failed in the pre-check. */
static int initialize_validation(int name, ValueSemantic vs,
AttributeOperator op, ValidationResult *result)
{
vs;
/* Make sure the token is an attribute name. */
AttributeSemantic as = attribute_semantic(name);
if (as == ASEM_INVALID)
return STKR_NO_SUCH_ATTRIBUTE;
result->semantic = as;
/* A valid operation for this kind of attribute? */
if (((1 << op) & supported_operators(as)) == 0)
return STKR_INVALID_OPERATION;
return ADEF_DEFINED;
}
/* Determines whether an integer (value, semantic) pair can be assigned to an
* attribute with the specified semantic. If it can, the mode the attribute
* will be switched into is returned. Otherwise, a validation error code is
* returned. */
static int validate_integer(int name, ValueSemantic vs, int value,
AttributeOperator op, ValidationResult *result)
{
int rc = initialize_validation(name, vs, op, result);
if (rc < ADEF_DEFINED)
return rc;
/* Every attribute can be undefined. */
if (vs == VSEM_TOKEN && value == TOKEN_UNDEFINED)
return ADEF_UNDEFINED;
/* What mode will this (value, semantic) pair switch the attribute into? */
int mode = STKR_TYPE_MISMATCH;
AttributeSemantic as = result->semantic;
switch (as) {
case ASEM_DIMENSON:
if (vs == VSEM_PERCENTAGE) {
mode = unsigned(value) > 100 ?
STKR_OUT_OF_BOUNDS : DMODE_FRACTIONAL;
}
/* Fall through. */
case ASEM_ABSOLUTE_DIMENSION:
if (vs == VSEM_TOKEN && value == TOKEN_AUTO)
mode = DMODE_AUTO;
else if (vs == VSEM_NONE)
mode = DMODE_ABSOLUTE;
break;
case ASEM_GROWTH_FACTOR:
if (vs == VSEM_NONE)
mode = value < 0 ? STKR_OUT_OF_BOUNDS : ADEF_DEFINED;
break;
case ASEM_COLOR:
if (vs == VSEM_COLOR || vs == VSEM_NONE)
mode = ADEF_DEFINED;
break;
case ASEM_FLAG:
if (vs == VSEM_BOOLEAN) {
if (value == 0)
mode = FLAGMODE_FALSE;
else if (value == 1)
mode = FLAGMODE_TRUE;
else
mode = STKR_OUT_OF_BOUNDS;
}
break;
case ASEM_ALIGNMENT:
if (vs == VSEM_TOKEN) {
mode = ALIGN_START + (value - TOKEN_START);
if (mode < ALIGN_START || mode >= ALIGN_SENTINEL)
mode = STKR_TYPE_MISMATCH;
}
break;
case ASEM_JUSTIFICATION:
if (vs == VSEM_TOKEN) {
switch (value) {
case TOKEN_LEFT:
mode = JUSTIFY_LEFT;
break;
case TOKEN_RIGHT:
mode = JUSTIFY_RIGHT;
break;
case TOKEN_CENTER:
mode = JUSTIFY_CENTER;
break;
case TOKEN_FLUSH:
mode = JUSTIFY_FLUSH;
break;
default:
mode = STKR_TYPE_MISMATCH;
break;
}
}
break;
case ASEM_LAYOUT:
if (vs == VSEM_TOKEN) {
if (value == TOKEN_NONE) {
mode = LAYOUT_NONE;
} else {
mode = LAYOUT_BLOCK + (value - TOKEN_BLOCK);
if (mode < LAYOUT_BLOCK || mode >= LAYOUT_SENTINEL)
mode = STKR_TYPE_MISMATCH;
}
}
break;
case ASEM_EDGES:
if (vs == VSEM_TOKEN) {
switch (value) {
case TOKEN_NONE:
mode = EDGE_FLAG_NONE;
break;
case TOKEN_ALL:
mode = EDGE_FLAG_ALL;
break;
case TOKEN_HORIZONTAL:
mode = EDGE_FLAG_HORIZONTAL;
break;
case TOKEN_VERTICAL:
mode = EDGE_FLAG_VERTICAL;
break;
case TOKEN_LEFT:
mode = EDGE_FLAG_LEFT;
break;
case TOKEN_RIGHT:
mode = EDGE_FLAG_RIGHT;
break;
case TOKEN_TOP:
mode = EDGE_FLAG_TOP;
break;
case TOKEN_BOTTOM:
mode = EDGE_FLAG_BOTTOM;
break;
default:
mode = STKR_TYPE_MISMATCH;
break;
}
} else if (vs == VSEM_EDGES) {
mode = (value == (value & EDGE_FLAG_ALL)) ?
value : STKR_OUT_OF_BOUNDS;
}
break;
case ASEM_WHITE_SPACE:
if (vs == VSEM_TOKEN) {
if (value == TOKEN_NORMAL)
mode = WSM_NORMAL;
else if (value == TOKEN_PRESERVE)
mode = WSM_PRESERVE;
else
mode = STKR_TYPE_MISMATCH;
}
break;
case ASEM_WRAP_MODE:
if (vs == VSEM_TOKEN) {
if (value == TOKEN_WORD_WRAP)
mode = WRAPMODE_WORD;
else if (value == TOKEN_CHARACTER_WRAP)
mode = WRAPMODE_CHARACTER;
else
mode = STKR_TYPE_MISMATCH;
}
break;
case ASEM_BOUNDING_BOX:
if (vs == VSEM_TOKEN) {
if (value == TOKEN_AUTO || value == TOKEN_NONE) {
mode = BBOX_PADDING;
} else {
mode = BBOX_CONTENT + (value - TOKEN_CONTENT_BOX);
if (mode < BBOX_CONTENT || mode >= BBOX_SENTINEL)
mode = STKR_TYPE_MISMATCH;
}
}
break;
case ASEM_BACKGROUND_SIZE:
if (vs == VSEM_TOKEN) {
if (value == TOKEN_AUTO || value == TOKEN_NONE) {
mode = VLPM_STANDARD;
} else {
mode = VLPM_FIT + (value - TOKEN_FIT);
if (mode < VLPM_FIT || mode >= VLPM_SENTINEL)
mode = STKR_TYPE_MISMATCH;
}
}
break;
case ASEM_BACKGROUND:
if (vs == VSEM_TOKEN) {
if (value == TOKEN_NONE) {
mode = ADEF_UNDEFINED;
} else {
mode = BGMODE_PANE_FIRST + (value - TOKEN_FLAT);
if (mode < BGMODE_PANE_FIRST || mode > BGMODE_PANE_LAST)
mode = STKR_TYPE_MISMATCH;
}
} else if (vs == VSEM_COLOR) {
mode = BGMODE_COLOR;
}
break;
case ASEM_CURSOR:
if (vs == VSEM_TOKEN) {
if (value == TOKEN_DEFAULT || value == TOKEN_AUTO ||
value == TOKEN_NONE) {
mode = CT_DEFAULT;
} else {
mode = CT_HAND + (value - TOKEN_CURSOR_HAND);
if (mode < CT_HAND || mode >= CT_SENTINEL)
mode = STKR_TYPE_MISMATCH;
}
}
break;
}
if (mode < 0)
return mode;
/* Choose the smallest storage type that can represent the value without
* loss of information, or, failing that, the widest permitted type. */
unsigned permitted_types = storage_mask(as, mode);
if ((permitted_types & STORAGE_BIT_INT16) != 0 &&
value >= SHRT_MIN && value <= SHRT_MAX) {
result->storage = STORAGE_INT16;
} else if ((permitted_types & STORAGE_BIT_INT32) != 0) {
result->storage = STORAGE_INT32;
} else if ((permitted_types & STORAGE_BIT_FLOAT32) != 0) {
result->storage = STORAGE_FLOAT32;
} else if ((permitted_types & STORAGE_BIT_INT16) != 0) {
result->storage = STORAGE_INT16;
} else if ((permitted_types & STORAGE_BIT_NONE) != 0) {
result->storage = STORAGE_NONE;
} else {
assertb(false);
return 0;
}
/* Convert the value to its storage type. */
switch (result->storage) {
case STORAGE_NONE:
result->size = 0;
break;
case STORAGE_INT16:
if (value < SHRT_MIN || value > SHRT_MAX)
return STKR_OUT_OF_BOUNDS;
if (as == ASEM_DIMENSON && mode == DMODE_FRACTIONAL) {
ensure(vs == VSEM_PERCENTAGE);
value = int((uint32_t)value * INT16_MAX / 100u);
}
result->data->int16 = (int16_t)value;
result->size = sizeof(int16_t);
break;
case STORAGE_INT32:
if (as == ASEM_DIMENSON && mode == DMODE_FRACTIONAL) {
ensure(vs == VSEM_PERCENTAGE);
value = int((uint64_t)value * INT32_MAX / 100ull);
}
result->data->int32 = value;
result->size = sizeof(int32_t);
break;
case STORAGE_FLOAT32:
result->data->float32 = (float)value;
result->size = sizeof(float);
break;
default:
assertb(false);
return 0;
}
return mode;
}
static int validate_float(int name, ValueSemantic vs, float value,
AttributeOperator op, ValidationResult *result)
{
int rc = initialize_validation(name, vs, op, result);
if (rc < ADEF_DEFINED)
return rc;
/* Determine the mode. */
int mode = STKR_TYPE_MISMATCH;
AttributeSemantic as = result->semantic;
switch (as) {
case ASEM_DIMENSON:
if (vs == VSEM_PERCENTAGE) {
float tolerance = 100.0f * FLT_EPSILON;
mode = (value < -tolerance || value > 100.0f + tolerance) ?
STKR_OUT_OF_BOUNDS : DMODE_FRACTIONAL;
break;
}
/* Fall through. */
case ASEM_ABSOLUTE_DIMENSION:
if (vs == VSEM_NONE)
mode = DMODE_ABSOLUTE;
break;
case ASEM_GROWTH_FACTOR:
if (vs == VSEM_NONE) {
mode = ADEF_DEFINED;
if (value < 0.0f)
mode = STKR_OUT_OF_BOUNDS;
}
break;
}
if (mode < 0)
return mode;
/* Choose the widest numeric type permitted. */
unsigned permitted_types = storage_mask(as, mode);
if ((permitted_types & STORAGE_BIT_FLOAT32) != 0) {
result->storage = STORAGE_FLOAT32;
} else if ((permitted_types & STORAGE_BIT_INT32) != 0) {
result->storage = STORAGE_INT32;
} else if ((permitted_types & STORAGE_BIT_INT16) != 0) {
result->storage = STORAGE_INT16;
} else if ((permitted_types & STORAGE_BIT_NONE) != 0) {
result->storage = STORAGE_NONE;
} else {
assertb(false);
return 0;
}
/* Convert the value to its storage type. */
if (vs == VSEM_PERCENTAGE)
value *= 1.0f / 100.0f;
switch (result->storage) {
case STORAGE_NONE:
result->size = 0;
break;
case STORAGE_INT16:
if (value < float(SHRT_MIN) || value > float(SHRT_MAX))
return STKR_OUT_OF_BOUNDS;
if (as == ASEM_DIMENSON && mode == DMODE_FRACTIONAL) {
result->data->int16 = (int16_t)round_signed(value * float(INT16_MAX));
} else {
result->data->int16 = (int16_t)round_signed(value);
}
result->size = sizeof(int16_t);
break;
case STORAGE_INT32:
if (as == ASEM_DIMENSON && mode == DMODE_FRACTIONAL) {
result->data->int32 = round_signed(value * float(INT32_MAX));
} else {
result->data->int32 = round_signed(value);
}
result->size = sizeof(int32_t);
break;
case STORAGE_FLOAT32:
result->data->float32 = value;
result->size = sizeof(float);
break;
default:
assertb(false);
return 0;
}
return mode;
}
/* Determines whether an string (value, semantic) pair can be assigned to an
* attribute with the specified semantic. If it can, the mode the attribute
* will be switched into is returned. Otherwise, a validation error code is
* returned. */
static int validate_string(int name, ValueSemantic vs,
const char *value, int length, AttributeOperator op,
ValidationResult *result)
{
int rc = initialize_validation(name, vs, op, result);
if (rc < ADEF_DEFINED)
return rc;
if (length < 0)
length = (int)strlen(value);
vresult_set_static(result, value, length);
/* Determine the new mode. */
int mode = STKR_TYPE_MISMATCH;
AttributeSemantic as = result->semantic;
switch (as) {
case ASEM_STRING:
if (vs == VSEM_NONE)
mode = ADEF_DEFINED;
break;
case ASEM_STRING_SET:
if (vs == VSEM_NONE || vs == VSEM_LIST)
mode = ADEF_DEFINED;
break;
case ASEM_URL:
if (vs == VSEM_NONE || vs == VSEM_URL)
mode = ADEF_DEFINED;
break;
case ASEM_BACKGROUND:
if (vs == VSEM_URL)
mode = BGMODE_URL;
break;
}
if (mode < 0)
return mode;
/* Choose the storage type. */
unsigned permitted_types = storage_mask(as, mode);
if ((permitted_types & STORAGE_BIT_STRING) != 0) {
result->storage = STORAGE_STRING;
} else if ((permitted_types & STORAGE_BIT_NONE) != 0) {
result->storage = STORAGE_NONE;
} else {
assertb(false);
return 0;
}
/* Convert the value to storage form if required. */
if (as == ASEM_STRING_SET) {
rc = parse_string_list(value, length, result->buffer,
sizeof(result->buffer));
if (rc < 0)
return rc;
if (rc >= sizeof(result->buffer)) {
rc = parse_string_list(value, length,
vresult_allocate(result, rc + 1), rc + 1);
} else {
result->data = (AttributeData *)result->buffer;
}
result->size = rc;
result->terminators = 1;
if (rc >= 0)
result->size += string_set_unique(result->data->string, rc);
mode = rc < 0 ? rc : ADEF_DEFINED;
}
return mode;
}
static BufferEntry *abuf_allocate_replace(
AttributeBuffer *abuf,
int name,
int mode,
AttributeStorage storage_type,
AttributeOperator op,
unsigned required_size);
static int abuf_fold(
AttributeBuffer *abuf,
BufferEntry *ea,
AttributeStorage type_b,
int mode_b,
AttributeOperator op_b,
const AttributeData *data_b,
unsigned size_b,
BufferEntry **out_folded);
/*
* Attribute Buffers
*/
inline BufferEntry *abuf_next_entry(BufferEntry *entry)
{
return (BufferEntry *)((char *)entry + sizeof(Attribute) +
entry->header.size);
}
inline BufferEntry *abuf_end(AttributeBuffer *abuf)
{
return (BufferEntry *)(abuf->buffer + abuf->size);
}
/* Returns the number of attributes in the range [start, end). */
static unsigned count_attributes_between(const BufferEntry *start,
const BufferEntry *end)
{
unsigned count = 0;
while (start != end) {
start = abuf_next_entry((BufferEntry *)start);
count++;
}
return count;
}
static void abuf_reallocate(AttributeBuffer *abuf, unsigned new_size)
{
if (int(new_size) > abs(abuf->capacity)) {
char *block = new char[new_size];
if (abuf->buffer != NULL) {
memcpy(block, abuf->buffer, abuf->size);
if (abuf->capacity > 0)
delete [] abuf->buffer;
}
abuf->buffer = block;
abuf->capacity = int(new_size);
}
abuf->size = int(new_size);
}
/* Allocates a new entry at the end of the buffer. */
static BufferEntry *abuf_create_attribute(AttributeBuffer *abuf, int name,
int mode, AttributeStorage storage, AttributeOperator op,
unsigned data_size)
{
unsigned offset = abuf->size;
unsigned new_size = abuf->size + sizeof(Attribute) + data_size;
abuf_reallocate(abuf, new_size);
BufferEntry *entry = (BufferEntry *)((char *)abuf->buffer + offset);
entry->header.name = (uint8_t)name;
entry->header.mode = mode;
entry->header.type = storage;
entry->header.folded = false;
entry->header.op = op;
entry->header.size = check16(data_size);
abuf->num_attributes++;
return entry;
}
/* Deletes a single buffer entry. */
static void abuf_remove_one(AttributeBuffer *abuf, Attribute *attribute)
{
unsigned attr_size = sizeof(Attribute) + attribute->size;
char *buf_end = (char *)abuf->buffer + abuf->size;
char *attr_end = (char *)attribute + attr_size;
unsigned suffix = buf_end - attr_end;
memmove(attribute, attr_end, suffix);
abuf->size -= int(attr_size);
abuf->num_attributes--;
}
/* Removes all entries for a name. */
static void abuf_remove_all(AttributeBuffer *abuf, int name)
{
BufferEntry *entry = (BufferEntry *)abuf->buffer;
BufferEntry *end = (BufferEntry *)(abuf->buffer + abuf->size);
unsigned bytes_removed = 0;
while (entry != end) {
unsigned entry_size = sizeof(Attribute) + entry->header.size;
unsigned gap = 0;
if (entry->header.name == name) {
gap = entry_size;
abuf->num_attributes--;
}
memmove((char *)entry - bytes_removed, entry, entry_size);
entry = (BufferEntry *)((char *)entry + entry_size);
bytes_removed += gap;
}
abuf->size -= bytes_removed;
}
/* Allocates or reallocates storage for a single buffer entry. Any existing
* entries for the attribute are removed. */
static BufferEntry *abuf_allocate_replace(AttributeBuffer *abuf, int name,
int mode, AttributeStorage storage_type, AttributeOperator op,
unsigned required_size)
{
/* FIXME (TJM): reuse memory. */
abuf_remove_all(abuf, name);
return abuf_create_attribute(abuf, name, mode, storage_type,
op, required_size);
}
/* Resizes a buffer entry. Existing entry data is preserved (but will be
* truncated if the new size is smaller than the old). */
static BufferEntry *abuf_resize_entry(AttributeBuffer *abuf,
BufferEntry *entry, unsigned data_size)
{
unsigned new_size = abuf->size + (data_size - entry->header.size);
unsigned start_offset = (char *)entry - (char *)abuf->buffer;
unsigned old_end_offset = start_offset + sizeof(Attribute) + entry->header.size;
unsigned new_end_offset = start_offset + sizeof(Attribute) + data_size;
char *old_end = abuf->buffer + old_end_offset;
if (int(new_size) > abs(abuf->capacity)) {
char *new_buffer = new char[new_size];
char *new_end = new_buffer + new_end_offset;
unsigned copy_size = std::min(old_end_offset, new_end_offset);
memcpy(new_buffer, abuf->buffer, copy_size);
memcpy(new_end, old_end, abuf->size - old_end_offset);
entry = (BufferEntry *)(new_buffer + start_offset);
if (abuf->capacity > 0)
delete [] abuf->buffer;
abuf->buffer = new_buffer;
abuf->capacity = int(new_size);
} else {
char *new_end = (char *)abuf->buffer + new_end_offset;
memmove(new_end, old_end, abuf->size - old_end_offset);
}
abuf->size = int(new_size);
entry->header.size = check16(data_size);
return entry;
}
void abuf_init(AttributeBuffer *abuf, void *storage, unsigned storage_size)
{
abuf->buffer = storage_size != 0 ? (char *)storage : NULL;
abuf->size = 0;
abuf->capacity = -int(storage_size);
abuf->num_attributes = 0;
}
void abuf_clear(AttributeBuffer *abuf)
{
if (abuf->capacity > 0) {
delete [] abuf->buffer;
abuf->buffer = NULL;
abuf->capacity = 0;
}
abuf->size = 0;
abuf->num_attributes = 0;
}
const Attribute *abuf_first(const AttributeBuffer *abuf)
{
return abuf->size != 0 ? (const Attribute *)(abuf->buffer) : NULL;
}
const Attribute *abuf_next(const AttributeBuffer *abuf,
const Attribute *attribute)
{
if (attribute != NULL) {
const BufferEntry *end = abuf_end((AttributeBuffer *)abuf);
const BufferEntry *next = abuf_next_entry((BufferEntry *)attribute);
attribute = (next != end) ? (const Attribute *)next : NULL;
}
return attribute;
}
/* Appends an entry to the end of the buffer. */
Attribute *abuf_append(AttributeBuffer *abuf, const Attribute *attribute)
{
unsigned attr_size = sizeof(Attribute) + attribute->size;
abuf_reallocate(abuf, abuf->size + attr_size);
BufferEntry *dest = (BufferEntry *)(abuf->buffer + abuf->size - attr_size);
memcpy(dest, attribute, attr_size);
abuf->num_attributes++;
return &dest->header;
}
/* Adds an entry to the start of the buffer. */
Attribute *abuf_prepend(AttributeBuffer *abuf, const Attribute *attribute)
{
unsigned attr_size = sizeof(Attribute) + attribute->size;
abuf_reallocate(abuf, abuf->size + attr_size);
memmove(abuf->buffer + attr_size, abuf->buffer, abuf->size - attr_size);
memcpy(abuf->buffer, attribute, attr_size);
abuf->num_attributes++;
return (Attribute *)abuf_first(abuf);
}
/* Overwrites one attribute with another in place. */
Attribute *abuf_replace(AttributeBuffer *abuf, Attribute *a,
const Attribute *b)
{
BufferEntry *ea = (BufferEntry *)a;
if (ea->header.size != b->size)
ea = abuf_resize_entry(abuf, ea, b->size);
memcpy(ea, b, sizeof(Attribute) + b->size);
return &ea->header;
}
/* Replaces the range of attributes [start, end) with the attributes from a
* source buffer. */
void abuf_replace_range(AttributeBuffer *abuf, const Attribute *start,
const Attribute *end, const AttributeBuffer *source)
{
if (start == NULL)
start = (const Attribute *)abuf_first(abuf);
if (end == NULL)
end = (const Attribute *)abuf_end(abuf);
unsigned old_start = 0;
unsigned new_range_size = 0;
if (source != NULL) {
new_range_size = source->size;
abuf->num_attributes += source->num_attributes;
}
if (start != NULL && end != NULL) {
old_start = (char *)start - abuf->buffer;
unsigned old_end = (char *)end - abuf->buffer;
unsigned old_range_size = old_end - old_start;
unsigned old_size = abuf->size;
abuf->num_attributes -= count_attributes_between(
(const BufferEntry *)start,
(const BufferEntry *)end);
unsigned new_end = old_start + new_range_size;
unsigned new_size = abuf->size + new_range_size - old_range_size;
abuf_reallocate(abuf, new_size);
memmove(abuf->buffer + new_end, abuf->buffer + old_end,
old_size - old_end);
} else {
abuf_reallocate(abuf, new_range_size);
}
if (new_range_size != 0)
memcpy(abuf->buffer + old_start, source->buffer, new_range_size);
}
/* Returns the value of a numerical attribute as an integer. */
static int unpack_integer(AttributeSemantic semantic, int mode,
AttributeStorage storage, const AttributeData *data)
{
semantic; mode;
switch (storage) {
case STORAGE_INT16:
return (int)data->int16;
case STORAGE_INT32:
return data->int32;
case STORAGE_FLOAT32:
return round_signed(data->float32);
}
assertb(false);
return 0;
}
/* Returns the value of numerical attribute as a float. */
static float unpack_float(AttributeSemantic semantic, int mode,
AttributeStorage storage, const AttributeData *data)
{
float result;
switch (storage) {
case STORAGE_INT16:
result = float(data->int16);
if (semantic == ASEM_DIMENSON && mode == DMODE_FRACTIONAL)
result *= 1.0f / float(INT16_MAX);
break;
case STORAGE_INT32:
result = float(data->int32);
if (semantic == ASEM_DIMENSON && mode == DMODE_FRACTIONAL)
result *= 1.0f / float(INT32_MAX);
break;
case STORAGE_FLOAT32:
result = data->float32;
break;
default:
assertb(false);
result = 0.0f;
break;
}
return result;
}
static int do_integer_op(AttributeOperator op, int va, int vb)
{
switch (op) {
case AOP_ADD:
return va + vb;
case AOP_SUBTRACT:
return va - vb;
case AOP_MULTIPLY:
return va * vb;
case AOP_DIVIDE:
return vb != 0 ? va / vb : 0;
case AOP_SET:
case AOP_OVERRIDE:
return vb;
}
assertb(false);
return 0;
}
static float do_float_op(AttributeOperator op, float va, float vb)
{
switch (op) {
case AOP_ADD:
return va + vb;
case AOP_SUBTRACT:
return va - vb;
case AOP_MULTIPLY:
return va * vb;
case AOP_DIVIDE:
return vb != 0.0f ? va / vb : 0.0f;
case AOP_SET:
case AOP_OVERRIDE:
return vb;
}
assertb(false);
return 0.0f;
}
/* Attempts to replace operation A with an operation that does the same thing
* as A followed by B. Returns a pointer to the modified A if folding occurred,
* otherwise returns NULL. */
static int abuf_fold(
AttributeBuffer *abuf,
BufferEntry *ea,
AttributeStorage type_b,
int mode_b,
AttributeOperator op_b,
const AttributeData *data_b,
unsigned size_b,
BufferEntry **out_folded)
{
/* Assignments just replace the existing attribute with a SET. */
AttributeOperator op_a = (AttributeOperator)ea->header.op;
if (op_b <= AOP_OVERRIDE) {
if (ea->header.size != size_b)
ea = abuf_resize_entry(abuf, ea, size_b);
ea->header.mode = mode_b;
ea->header.folded = false;
ea->header.op = op_b;
ea->header.size = size_b;
ea->header.type = type_b;
memcpy(&ea->data, data_b, size_b);
if (out_folded != NULL)
*out_folded = ea;
return true;
}
/* Arithmetic with an undefined RHS is a no-op. */
if (mode_b == ADEF_UNDEFINED) {
if (out_folded != NULL)
*out_folded = ea;
return false;
}
/* The type of the result is the wider of the operand types. */
AttributeSemantic as = attribute_semantic(ea->header.name);
AttributeStorage type_a = (AttributeStorage)ea->header.type;
AttributeStorage type_ab = type_a > type_b ? type_a : type_b;
/* Determine the operation to execute and the operation represented by the
* result. */
AttributeOperator op = op_b, result_op = op_a;
if (op_a <= AOP_OVERRIDE) {
/* A is a set. The result is the same kind set. */
result_op = op_a;
} else {
/* Neither op is a set. The result is a modifier. */
if (op_a == op_b) {
/* The operators are the same. We can always fold, but if the
* operator is non-associative, we have to invert it so that the
* folded operation has the same effect as applying A followed
* by B, e.g. -(a - b) => -(a + b) == - a - b. */
if (op == AOP_SUBTRACT || op == AOP_DIVIDE)
op = (AttributeOperator)(int(op) + 1);
} else {
/* Different operators can be folded only if they are closed over
* the result type. This is true of the arithmetic operators but not
* of set-difference. For example, the sequence "+ 4 - 3" can be
* folded into "+1", but the sequence "union {x} diff {y}" cannot be
* represented as a single set union or difference. */
if (as == ASEM_STRING_SET)
return STKR_CANNOT_FOLD;
}
}
/* Perform the operation. */
bool changed = false;
if (type_ab == STORAGE_NONE) {
assertb(as == ASEM_EDGES);
int new_mode = ea->header.mode;
switch (op) {
case AOP_ADD:
new_mode |= mode_b;
break;
case AOP_SUBTRACT:
new_mode &= ~mode_b;
break;
}
if ((new_mode & EDGE_FLAG_ALL) != 0)
new_mode &= ~EDGE_FLAG_NONE;
if (new_mode != ea->header.mode) {
ea->header.mode = new_mode;
changed = true;
}
} else if (type_ab == STORAGE_INT16 || type_ab == STORAGE_INT32) {
int va = unpack_integer(as, ea->header.mode, type_a, &ea->data);
int vb = unpack_integer(as, mode_b, type_b, data_b);
int result = do_integer_op(op, va, vb);
if (type_a != type_ab) {
unsigned data_size = (type_ab == STORAGE_INT16) ?
sizeof(int16_t) : sizeof(int32_t);
ea = abuf_resize_entry(abuf, ea, data_size);
ea->header.type = type_ab;
changed = true;
}
if (type_ab == STORAGE_INT16) {
if (as == ASEM_DIMENSON && (ea->header.mode == DMODE_FRACTIONAL ||
mode_b == DMODE_FRACTIONAL))
result >>= 16;
int16_t converted = saturate16(result);
if (converted != ea->data.int16) {
ea->data.int16 = converted;
changed = true;
}
} else {
if (ea->data.int32 != result) {
ea->data.int32 = result;
changed = true;
}
}
} else if (type_ab == STORAGE_FLOAT32) {
float va = unpack_float(as, ea->header.mode, type_a, &ea->data);
float vb = unpack_float(as, mode_b, type_b, data_b);
float result = do_float_op(op, va, vb);
if (type_a != STORAGE_FLOAT32) {
ea = abuf_resize_entry(abuf, ea, sizeof(float));
ea->header.type = STORAGE_FLOAT32;
changed = true;
}
if (result != ea->data.float32) {
ea->data.float32 = result;
changed = true;
}
} else if (type_ab == STORAGE_STRING) {
if (type_a == STORAGE_NONE) {
ea = abuf_resize_entry(abuf, ea, size_b);
ea->header.mode = mode_b;
ea->header.folded = false;
ea->header.op = op_b;
ea->header.size = size_b;
ea->header.type = type_b;
memcpy(&ea->data, data_b, size_b);
changed = true;
} else {
unsigned length_a = ea->header.size - 1;
unsigned length_b = size_b - 1;
unsigned length_ab;
ea->header.type = STORAGE_STRING;
char *p = ea->data.string, *q = (char *)data_b->string;
if (op == AOP_ADD) {
length_ab = length_a + length_b;
if (ea->header.size != length_ab + 1) {
ea = abuf_resize_entry(abuf, ea, length_ab + 1);
p = ea->data.string;
}
memcpy(p + length_a, q, length_b + 1);
q = p + length_a;
} else {
length_ab = length_a;
}
if (as == ASEM_STRING_SET) {
unsigned length_q = length_b;
if (op == AOP_ADD) {
std::swap(p, q);
length_q = length_a;
}
length_ab += string_set_difference(p, q, length_q);
if (ea->header.size != length_ab + 1)
ea = abuf_resize_entry(abuf, ea, length_ab + 1);
}
changed = length_ab != length_a;
}
}
ea->header.op = result_op;
if (out_folded != NULL)
*out_folded = ea;
return changed;
}
int abuf_fold(AttributeBuffer *abuf, Attribute *a, const Attribute *b,
Attribute **out_folded)
{
return abuf_fold(
abuf,
(BufferEntry *)a,
(AttributeStorage)b->type,
b->mode,
(AttributeOperator)b->op,
&((const BufferEntry *)b)->data,
b->size,
(BufferEntry **)out_folded);
}
/* Returns an attribute's current mode, or 'defmode' if the attribute is
* undefined. */
int abuf_read_mode(const Attribute *attribute, int defmode)
{
return attribute != NULL && attribute->mode != ADEF_UNDEFINED ?
attribute->mode : defmode;
}
/* Reads an attribute as an integer. */
int abuf_read_integer(const Attribute *attribute, int32_t *result,
int32_t defval)
{
if (attribute == NULL || attribute->mode == ADEF_UNDEFINED) {
*result = defval;
return ADEF_UNDEFINED;
}
AttributeSemantic as = attribute_semantic(attribute->name);
const BufferEntry *entry = (const BufferEntry *)attribute;
*result = unpack_integer(as, entry->header.mode,
(AttributeStorage)entry->header.type, &entry->data);
return attribute->mode;
}
/* Reads an attribute as an integer. If the attribute represent a partially
* evaluated expression, it is evaluated with the supplied LHS.*/
int abuf_evaluate_integer(const Attribute *attribute, int32_t *result,
int32_t lhs, int32_t defval)
{
int mode = abuf_read_integer(attribute, result, defval);
if (mode != ADEF_UNDEFINED)
*result = do_integer_op((AttributeOperator)attribute->op, lhs, *result);
return mode;
}
/* Reads an attribute as a float. */
int abuf_read_float(const Attribute *attribute, float *result, float defval)
{
if (attribute == NULL || attribute->mode == ADEF_UNDEFINED) {
*result = defval;
return ADEF_UNDEFINED;
}
AttributeSemantic as = attribute_semantic(attribute->name);
const BufferEntry *entry = (const BufferEntry *)attribute;
*result = unpack_float(as, entry->header.mode,
(AttributeStorage)entry->header.type, &entry->data);
return attribute->mode;
}
/* Reads an attribute as a float. If the attribute represent a partially
* evaluated expression, it is evaluated with the supplied LHS. */
int abuf_evaluate_float(const Attribute *attribute, float *result,
float lhs, float defval)
{
int mode = abuf_read_float(attribute, result, defval);
if (mode != ADEF_UNDEFINED)
*result = do_float_op((AttributeOperator)attribute->op, lhs, *result);
return mode;
}
/* Reads an attribute value as a string, returning a pointer to the data inside
* the buffer via 'result'. The result string is guaranteed to be null
* terminated. The result pointer is invalidated by any mutation of the
* attribute buffer. */
int abuf_read_string(const Attribute *attribute, const char **result,
uint32_t *length, const char *defval)
{
if (attribute == NULL || attribute->mode == ADEF_UNDEFINED)
goto missing;
switch (attribute->type) {
case STORAGE_STRING:
*result = ((const BufferEntry *)attribute)->data.string;
if (length != NULL)
*length = attribute->size - 1;
break;
default:
assertb(false);
goto missing;
}
return attribute->mode;
missing:
*result = defval;
if (length != NULL)
*length = defval != NULL ? strlen(defval) : 0;
return ADEF_UNDEFINED;
}
/* Reads an attribute value as a string, copying the result to 'buffer', which
* is guaranteed to be null terminated. */
int abuf_read_string(const Attribute *attribute, char *buffer,
uint32_t buffer_size, uint32_t *out_length, const char *defval,
StringSetRepresentation ssr)
{
const char *data = NULL;
uint32_t length = 0;
int mode = abuf_read_string(attribute, &data, &length, defval);
if (buffer != NULL && buffer_size != 0) {
if (length + 1 > buffer_size)
length = buffer_size - 1;
memcpy(buffer, data, length);
buffer[length] = '\0';
/* If this is a set, format a set literal of the requested type. */
if (attribute_semantic(attribute->name) == ASEM_STRING_SET &&
ssr != SSR_INTERNAL) {
char delimiter = (ssr == SSR_COMMA_DELIMITED) ? ',' : ' ';
for (unsigned i = 0; i < length; ++i)
if (buffer[i] == '\0')
buffer[i] = delimiter;
if (length != 0)
buffer[--length] = '\0';
}
}
if (out_length != NULL)
*out_length = length;
return mode;
}
/* Creates a new attribute at the end of the buffer and stores the supplied
* value in it. Does not check for existing values. */
static Attribute *append_validated_attribute(AttributeBuffer *abuf, int name,
int mode, AttributeOperator op, const ValidationResult *vr)
{
if (mode < 0)
return NULL;
BufferEntry *entry = abuf_create_attribute(abuf, name, mode, vr->storage,
op, vr->size + vr->terminators);
memcpy(&entry->data, vr->data, vr->size);
memset(&entry->data.string[vr->size], 0, vr->terminators);
return &entry->header;
}
/* Copies the result of attribute validation into an attribute buffer entry,
* returning true if the stored value was changed. */
static int store_validated_attribute(AttributeBuffer *abuf, int name, int mode,
AttributeOperator op, const ValidationResult *vr, bool fold)
{
/* Do nothing if validation failed. */
if (mode < 0)
return mode;
/* Validated strings are not necessarily null terminated. */
unsigned stored_size = vr->size + vr->terminators;
/* A size query? */
if (abuf == NULL)
return sizeof(Attribute) + stored_size;
BufferEntry *entry;
if (fold) {
/* Try to fold with any existing entries. */
entry = (BufferEntry *)abuf->buffer;
BufferEntry *end = (BufferEntry *)(abuf->buffer + abuf->size);
while (entry != end) {
if (entry->header.name == name) {
int rc = abuf_fold(abuf, entry, vr->storage, mode,
op, vr->data, stored_size, NULL);
if (rc >= 0)
return rc;
}
entry = abuf_next_entry(entry);
}
/* Folding wasn't possible. Create a new attribute. */
entry = abuf_create_attribute(abuf, name, mode, vr->storage, op,
stored_size);
} else {
/* Reallocate memory for the attribute. */
entry = abuf_allocate_replace(abuf, name, mode, vr->storage,
op, stored_size);
/* Is the new value different from the old? */
if (mode == (int)entry->header.mode &&
op == (AttributeOperator)entry->header.op &&
entry->header.size == stored_size &&
(0 == memcmp(&entry->data, vr->data, vr->size))) {
return false;
}
}
/* Copy the validated data into the attribute and pad with the specified
* number of zero bytes. */
memcpy(&entry->data, vr->data, vr->size);
memset(&entry->data.string[vr->size], 0, vr->terminators);
return true;
}
static int abuf_handle_shorthand_integer(AttributeBuffer *abuf, int name,
ValueSemantic vs, int value, AttributeOperator op, bool fold);
static int abuf_handle_shorthand_float(AttributeBuffer *abuf, int name,
ValueSemantic vs, float value, AttributeOperator op, bool fold);
int abuf_set_integer(AttributeBuffer *abuf, int name, ValueSemantic vs,
int value, AttributeOperator op, bool fold)
{
/* Handle shorthand attributes like 'pad'. */
int rc = abuf_handle_shorthand_integer(abuf, name, vs, value, op, fold);
if (rc >= 0)
return rc;
/* Validate the value and determine the new mode. */
ValidationResult vr;
vresult_init(&vr);
int new_mode = validate_integer(name, vs, value, op, &vr);
/* Store the validated value. */
int result = store_validated_attribute(abuf, name, new_mode, op, &vr, fold);
vresult_free(&vr);
return result;
}
int abuf_set_float(AttributeBuffer *abuf, int name, ValueSemantic vs,
float value, AttributeOperator op, bool fold)
{
/* Handle shorthand atributes. */
int rc = abuf_handle_shorthand_float(abuf, name, vs, value, op, fold);
if (rc >= 0)
return rc;
/* Validate the value and determine the new mode. */
ValidationResult vr;
vresult_init(&vr);
int new_mode = validate_float(name, vs, value, op, &vr);
/* Store the validated value. */
int result = store_validated_attribute(abuf, name, new_mode, op, &vr, fold);
vresult_free(&vr);
return result;
}
int abuf_set_string(AttributeBuffer *abuf, int name, ValueSemantic vs,
const char *value, int length, AttributeOperator op, bool fold)
{
/* Validate the value and determine the new mode. */
ValidationResult vr;
vresult_init(&vr);
int new_mode = validate_string(name, vs, value, length, op, &vr);
/* Store the validated value. */
int result = store_validated_attribute(abuf, name, new_mode, op, &vr, fold);
vresult_free(&vr);
return result;
}
/* Calls the appropriate function to store a variant into an attribute buffer. */
int abuf_set(AttributeBuffer *abuf, Token name, const Variant *value,
AttributeOperator op, bool fold)
{
switch (value->type) {
case VTYPE_INTEGER:
/* Note that tokens representing enum values go through this path.
* Their integer value is the token itself. */
return abuf_set_integer(abuf, name, value->semantic,
value->integer, op, fold);
case VTYPE_FLOAT:
return abuf_set_float(abuf, name, value->semantic,
value->real, op, fold);
case VTYPE_STRING:
return abuf_set_string(abuf, name, value->semantic,
value->string.data, value->string.length, op, fold);
}
assertb(false);
return -1;
}
/* Convenience function to add a new integer attribute without checking for
* existing values. */
Attribute *abuf_append_integer(AttributeBuffer *abuf, int name,
ValueSemantic vs, int value, AttributeOperator op)
{
ValidationResult vr;
vresult_init(&vr);
int mode = validate_integer(name, vs, value, op, &vr);
return append_validated_attribute(abuf, name, mode, op, &vr);
}
/* Convenience function to add a new float attribute without checking for
* existing values. */
Attribute *abuf_append_float(AttributeBuffer *abuf, int name,
ValueSemantic vs, float value, AttributeOperator op)
{
ValidationResult vr;
vresult_init(&vr);
int mode = validate_float(name, vs, value, op, &vr);
return append_validated_attribute(abuf, name, mode, op, &vr);
}
/* Convenience function to add a new string attribute without checking for
* existing values. */
Attribute *abuf_append_string(AttributeBuffer *abuf, int name,
ValueSemantic vs, const char *value, int length, AttributeOperator op)
{
ValidationResult vr;
vresult_init(&vr);
int mode = validate_string(name, vs, value, length, op, &vr);
return append_validated_attribute(abuf, name, mode, op, &vr);
}
/* Handles the storage of shorthand attributes like 'pad', which set other
* attributes but have no storage of their own. */
int abuf_handle_shorthand_integer(AttributeBuffer *abuf, int name,
ValueSemantic vs, int value, AttributeOperator op, bool fold)
{
int rc = -1;
if (name == TOKEN_PADDING) {
rc = abuf_set_integer(abuf, TOKEN_PADDING_LEFT, vs, value, op, fold);
rc += abuf_set_integer(abuf, TOKEN_PADDING_RIGHT, vs, value, op, fold);
rc += abuf_set_integer(abuf, TOKEN_PADDING_TOP, vs, value, op, fold);
rc += abuf_set_integer(abuf, TOKEN_PADDING_BOTTOM, vs, value, op, fold);
} else if (name == TOKEN_MARGIN) {
rc = abuf_set_integer(abuf, TOKEN_MARGIN_LEFT, vs, value, op, fold);
rc += abuf_set_integer(abuf, TOKEN_MARGIN_RIGHT, vs, value, op, fold);
rc += abuf_set_integer(abuf, TOKEN_MARGIN_TOP, vs, value, op, fold);
rc += abuf_set_integer(abuf, TOKEN_MARGIN_BOTTOM, vs, value, op, fold);
} else if (name >= TOKEN_CLIP_LEFT && name <= TOKEN_CLIP_BOTTOM) {
int edges = EDGE_FLAG_LEFT << (name - TOKEN_CLIP_LEFT);
op = (value == FLAGMODE_TRUE) ? AOP_ADD : AOP_SUBTRACT;
rc = abuf_set_integer(abuf, TOKEN_CLIP, VSEM_EDGES, edges, op, true);
}
return rc;
}
/* Handles the storage of shorthand attributes like 'pad', which set other
* attributes but have no storage of their own. */
int abuf_handle_shorthand_float(AttributeBuffer *abuf, int name,
ValueSemantic vs, float value, AttributeOperator op, bool fold)
{
int rc = -1;
if (name == TOKEN_PADDING) {
rc = abuf_set_float(abuf, TOKEN_PADDING_LEFT, vs, value, op, fold);
rc += abuf_set_float(abuf, TOKEN_PADDING_RIGHT, vs, value, op, fold);
rc += abuf_set_float(abuf, TOKEN_PADDING_TOP, vs, value, op, fold);
rc += abuf_set_float(abuf, TOKEN_PADDING_BOTTOM, vs, value, op, fold);
} else if (name == TOKEN_MARGIN) {
rc = abuf_set_float(abuf, TOKEN_MARGIN_LEFT, vs, value, op, fold);
rc += abuf_set_float(abuf, TOKEN_MARGIN_RIGHT, vs, value, op, fold);
rc += abuf_set_float(abuf, TOKEN_MARGIN_TOP, vs, value, op, fold);
rc += abuf_set_float(abuf, TOKEN_MARGIN_BOTTOM, vs, value, op, fold);
}
return rc;
}
/* Generates a string representation of an attribute value for use in a
* diagnostic message. */
int attribute_value_string(char *buffer, unsigned buffer_size,
const Attribute *attribute)
{
char value_buffer[1024];
const char *data = (const char *)(attribute + 1);
int length = 0;
AttributeSemantic as = attribute_semantic(attribute->name);
switch (attribute->type) {
case STORAGE_NONE:
length = snprintf(buffer, buffer_size, "none/%u", attribute->mode);
break;
case STORAGE_STRING:
{
unsigned value_length = 0;
abuf_read_string(attribute, value_buffer, sizeof(value_buffer),
&value_length, NULL, SSR_COMMA_DELIMITED);
if (as == ASEM_STRING_SET) {
length = snprintf(buffer, buffer_size, "{%s}/%u",
value_buffer, attribute->mode);
} else {
length = snprintf(buffer, buffer_size, "%s/%u",
value_buffer, attribute->mode);
}
}
break;
case STORAGE_INT16:
case STORAGE_INT32:
{
int32_t value = (attribute->type == STORAGE_INT16) ?
*(int16_t *)data : *(int32_t *)data;
if (as == ASEM_DIMENSON && attribute->mode == DMODE_FRACTIONAL) {
uint32_t divisor = (attribute->type == STORAGE_INT16) ?
INT16_MAX : INT32_MAX;
float percentage = 100.0f * (float)value / (float)divisor;
length = snprintf(buffer, buffer_size, "%.1f%%/%u", percentage, attribute->mode);
} else {
length = snprintf(buffer, buffer_size, "%d/%u", value, attribute->mode);
}
}
break;
case STORAGE_FLOAT32:
length = snprintf(buffer, buffer_size, "%.2f/%u", *(float *)data, attribute->mode);
break;
default:
length = snprintf(buffer, buffer_size, "corrupt");
}
if (length < 0 || length == (int)buffer_size)
length = buffer_size - 1;
buffer[length] = '\0';
return length;
}
} // namespace stkr
| [
"thomasjamesmoran@gmail.com"
] | thomasjamesmoran@gmail.com |
ca56c2a64be6538942e31ba2db189f2405cec3ca | e38fe12f1573c98ada37520292b64d2c454cd17c | /SlowakCodeTests/AIWonder.cpp | 990b2ec4e80fff576e17ff67fb2aeb0c1bcfd941 | [] | no_license | marzix/7Wonders | 08d85ab7687f74e528138a6fea092584336e1f26 | 6a8665f1d327b9c34c8e1dc156f50066bce9b219 | refs/heads/master | 2020-04-06T07:06:37.443853 | 2018-06-29T14:55:56 | 2018-06-29T14:55:56 | 65,573,965 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,038 | cpp | #include "AIWonder.h"
#include <ios>
#include <iostream>
#include <fstream>
#include <iomanip>
using std::cout;
using std::cerr;
using std::endl;
using std::setw;
using std::left;
using std::right;
using std::showpos;
using std::noshowpos;
#define netFileName "AIWonder.net"
#define trainingDataFile "AIWonder.data"
#pragma warning(disable: 4996)
AIWonder AIWonder::AI;
FANN::neural_net AIWonder::net;
AIWonder::AIWonder()
{
}
AIWonder::AIWonder(const AIWonder &)
{
}
AIWonder & AIWonder::getSingleton()
{
return AI;
}
int AIWonder::takeCard(char * cardsData)
{
int taken = 0;
float temp = 0.0f;
fann_type inputData[6];
char * codes = strtok(cardsData, " ");
for (int i = 0; i < 6; i++)
{
inputData[i] = atof(codes);
codes = strtok(NULL, " ");
}
fann_type *calc_out = net.run(inputData);
for (int j = 0; j < 5; j++)
{
if (calc_out[j] > temp)
{
temp = calc_out[j];
taken = j + 1;
}
}
return taken;
}
void AIWonder::train()
{
std::ifstream dataFile(trainingDataFile);
if (!dataFile.good())
{
cout << "No dataFile for training AI\n";
system("pause");
exit(0);
}
const float learning_rate = 0.005f;
const unsigned int num_layers = 3;
const unsigned int num_input = 6;
const unsigned int num_hidden = 8;
const unsigned int num_output = 5;
const float desired_error = 0.0001f;
const unsigned int max_iterations = 500000;
const unsigned int iterations_between_reports = 100000;
cout << endl << "Creating network." << endl;
if (!net.create_standard(num_layers, num_input, num_hidden, num_output))
{
system("pause");
exit(0);
}
net.set_learning_rate(learning_rate);
net.set_activation_steepness_hidden(0.4);
net.set_activation_steepness_output(0.4);
net.set_activation_function_hidden(FANN::SIGMOID_SYMMETRIC_STEPWISE);
net.set_activation_function_output(FANN::SIGMOID_SYMMETRIC_STEPWISE);
// Set additional properties such as the training algorithm
net.set_training_algorithm(FANN::TRAIN_RPROP);
// Output network type and parameters
cout << endl << "Training network." << endl;
FANN::training_data data;
if (data.read_train_from_file(trainingDataFile))
{
// Initialize and train the network with the data
net.init_weights(data);
cout << "Max Epochs " << setw(8) << max_iterations << ". "
<< "Desired Error: " << left << desired_error << right << endl;
net.train_on_data(data, max_iterations,
iterations_between_reports, desired_error);
/*
cout << endl << "Testing network." << endl;
for (unsigned int i = 0; i < data.length_train_data(); ++i)
{
// Run the network on the test data
fann_type *calc_out = net.run(data.get_input()[i]);
cout << "XOR test (" << showpos << data.get_input()[i][0] << ", " << data.get_input()[i][1] << ", " << data.get_input()[i][2] << ", " << data.get_input()[i][3] << ", " << data.get_input()[i][4] << ", " << data.get_input()[i][5] << ") -> "
<< calc_out[0] << ", " << calc_out[1] << ", " << calc_out[2] << ", " << calc_out[3] << ", " << calc_out[4] << ", "
<< ", should be " << data.get_output()[i][0] << ", " << data.get_output()[i][1] << ", " << data.get_output()[i][2] << ", " << data.get_output()[i][3] << ", " << data.get_output()[i][4] << ", "
<< "difference = " << noshowpos
<< fann_abs(*calc_out - data.get_output()[i][0]) << endl;
int taken = 0;
float temp = 0.0f;
for (int j = 0; j < 5; j++)
{
if (abs(calc_out[j]) > temp)
{
temp = abs(calc_out[j]);
taken = j + 1;
}
}
cout << "Taken : " << taken << endl;
}
system("pause\n");
*/
cout << endl << "Saving network." << endl;
// Save the network in floating point and fixed point
net.save(netFileName);
cout << endl << "Training AI completed\n" << endl;
}
}
void AIWonder::initAI()
{
std::ifstream netFile(netFileName);
if (netFile.good())
{
cout << "Reading neural network from file\n";
net.create_from_file(netFileName);
}
else
{
cout << "Neural network have not been found. Try to train on data from file " << trainingDataFile << endl;
train();
}
} | [
"rafal.potoczek@gmail.com"
] | rafal.potoczek@gmail.com |
06590f44c0accf67cb35df7410e6c29f278da85a | d6b48d0260beee183aa97d051b80373475a7e7c0 | /build-SLStudio-Desktop-Debug/moc_PoseFilter.cpp | bfcc265293bfa80994a0273254b72d25a87f0117 | [] | no_license | hehongyu1995/slstudio | c624f5fcae94f200560ec59137857391369a4904 | 2d85bec24382e609504030463001d16bd4aa1f5d | refs/heads/master | 2020-12-02T22:47:14.502981 | 2017-07-14T05:23:34 | 2017-07-14T05:23:34 | 96,179,511 | 0 | 0 | null | 2017-07-04T05:43:28 | 2017-07-04T05:43:28 | null | UTF-8 | C++ | false | false | 4,467 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'PoseFilter.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/tracker/PoseFilter.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'PoseFilter.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_PoseFilter_t {
QByteArrayData data[6];
char stringdata0[73];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_PoseFilter_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_PoseFilter_t qt_meta_stringdata_PoseFilter = {
{
QT_MOC_LITERAL(0, 0, 10), // "PoseFilter"
QT_MOC_LITERAL(1, 11, 23), // "newFilteredPoseEstimate"
QT_MOC_LITERAL(2, 35, 0), // ""
QT_MOC_LITERAL(3, 36, 15), // "Eigen::Affine3f"
QT_MOC_LITERAL(4, 52, 1), // "T"
QT_MOC_LITERAL(5, 54, 18) // "filterPoseEstimate"
},
"PoseFilter\0newFilteredPoseEstimate\0\0"
"Eigen::Affine3f\0T\0filterPoseEstimate"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_PoseFilter[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 24, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
5, 1, 27, 2, 0x0a /* Public */,
// signals: parameters
QMetaType::Void, 0x80000000 | 3, 4,
// slots: parameters
QMetaType::Void, 0x80000000 | 3, 4,
0 // eod
};
void PoseFilter::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
PoseFilter *_t = static_cast<PoseFilter *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->newFilteredPoseEstimate((*reinterpret_cast< Eigen::Affine3f(*)>(_a[1]))); break;
case 1: _t->filterPoseEstimate((*reinterpret_cast< Eigen::Affine3f(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (PoseFilter::*_t)(Eigen::Affine3f );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&PoseFilter::newFilteredPoseEstimate)) {
*result = 0;
}
}
}
}
const QMetaObject PoseFilter::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_PoseFilter.data,
qt_meta_data_PoseFilter, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *PoseFilter::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *PoseFilter::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_PoseFilter.stringdata0))
return static_cast<void*>(const_cast< PoseFilter*>(this));
return QObject::qt_metacast(_clname);
}
int PoseFilter::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 2;
}
return _id;
}
// SIGNAL 0
void PoseFilter::newFilteredPoseEstimate(Eigen::Affine3f _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_END_MOC_NAMESPACE
| [
"hehongyu1995@github.com"
] | hehongyu1995@github.com |
63ebed55dcb891723fe16d631f8d263b443b5835 | 1e5d25a8e0e31b78c4e979af55ee2ad64687c258 | /92 Reverse Linked List II/reverseLinkedListII.cpp | f34ee72a31caa0ceb3380a3f5bdb8ddae0e35387 | [] | no_license | charlenellll/LeetCodeSolution | ed02ee9b4059d6c1c6972af8cc56ea7bc85d401f | 3b846bf4cc1817aaae9e4e392547ad9ccde04e76 | refs/heads/master | 2021-01-01T16:18:58.440351 | 2019-11-19T15:48:04 | 2019-11-19T15:48:04 | 97,808,314 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,117 | cpp | //2nd round
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* pre = NULL, *cur = head;
for(int i = 1; i < m; i++ ){
pre = cur;
cur = cur->next;
}
if( !cur->next ) return head;
ListNode* before = pre, *tail = cur;
pre = cur, cur = cur->next;
for(int i = 0; i < n-m; i++ ){
ListNode* after = cur->next;
cur->next = pre;
pre = cur;
cur = after;
}
if(before) // Notice here! In some test cases m=1, before is NULL, then there is nothing before the new head, the new head is the tempHead of the middle reversed part.
before->next = pre;
else
head = pre;
tail->next = cur;
return head;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(m == n)
return head;
ListNode* cur = head;
ListNode* pre = NULL;
ListNode* next;
int index = 1;
// Point 1 : No need to use "next" in this loop
while(cur != NULL){
if( index == m )
break;
pre = cur;
cur = cur->next;
index++;
}
ListNode* head_point = pre;
ListNode* tail_point = cur;
// Point 2: Important step! Set pre to NULL again.
pre = NULL;
for( int i = 0; i < n-m+1; i++){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
// Point 3 & 4
if(head_point != NULL)
head_point->next = pre;
else
head = pre;
tail_point->next = cur;
return head;
}
};
// I've made a few mistakes which are marked in the comments. Think about it thoroughly.
// Linked list and pointers can be a bit tricky | [
"charleneliaojl@gmail.com"
] | charleneliaojl@gmail.com |
aef8427d73ac89fbd587419700f2dcee76c41630 | f6737c532718980a62d5d19753be9b1e94f908c1 | /boost/asynchronous/scheduler/stealing_multiqueue_threadpool_scheduler.hpp | b285f73e86866ce42ae09cf2f13504f0641444d8 | [] | no_license | Shevchenko-Alexander/asynchronous | 8096228eda9b1e6455edcda746c91722f16973e9 | 1f0acf7bcd628d3ad0db50d8b921d5494f43f8a1 | refs/heads/master | 2020-04-03T11:41:37.695317 | 2018-10-29T15:06:26 | 2018-10-29T15:06:26 | 155,228,999 | 0 | 0 | null | 2018-10-29T14:47:59 | 2018-10-29T14:47:57 | null | UTF-8 | C++ | false | false | 16,250 | hpp | // Boost.Asynchronous library
// Copyright (C) Christophe Henry 2013
//
// Use, modification and distribution is subject to 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)
//
// For more information, see http://www.boost.org
#ifndef BOOST_ASYNC_SCHEDULER_STEALING_MULTIQUEUE_THREADPOOL_SCHEDULER_HPP
#define BOOST_ASYNC_SCHEDULER_STEALING_MULTIQUEUE_THREADPOOL_SCHEDULER_HPP
#include <utility>
#include <vector>
#include <cstddef>
#include <memory>
#include <functional>
#include <future>
#include <boost/thread/thread.hpp>
#include <boost/thread/tss.hpp>
#include <boost/asynchronous/scheduler/detail/scheduler_helpers.hpp>
#include <boost/asynchronous/scheduler/detail/exceptions.hpp>
#include <boost/asynchronous/detail/any_interruptible.hpp>
#include <boost/asynchronous/scheduler/detail/interruptible_job.hpp>
#include <boost/asynchronous/diagnostics/default_loggable_job.hpp>
#include <boost/asynchronous/job_traits.hpp>
#include <boost/asynchronous/scheduler/detail/job_diagnostic_closer.hpp>
#include <boost/asynchronous/queue/find_queue_position.hpp>
#include <boost/asynchronous/queue/any_queue.hpp>
#include <boost/asynchronous/scheduler/detail/multi_queue_scheduler_policy.hpp>
#include <boost/asynchronous/detail/any_joinable.hpp>
#include <boost/asynchronous/queue/lockfree_queue.hpp>
#include <boost/asynchronous/scheduler/tss_scheduler.hpp>
#include <boost/asynchronous/scheduler/detail/lockable_weak_scheduler.hpp>
#include <boost/asynchronous/scheduler/detail/any_continuation.hpp>
#include <boost/asynchronous/scheduler/cpu_load_policies.hpp>
#include <boost/asynchronous/scheduler/detail/execute_in_all_threads.hpp>
namespace boost { namespace asynchronous
{
//TODO boost.parameter
template<class Q,
class FindPosition=boost::asynchronous::default_find_position< >,
class CPULoad =
#ifdef BOOST_ASYNCHRONOUS_NO_SAVING_CPU_LOAD
boost::asynchronous::no_cpu_load_saving
#else
boost::asynchronous::default_save_cpu_load<>
#endif
,
// just for testing, ignore
bool IsImmediate=false >
class stealing_multiqueue_threadpool_scheduler: public boost::asynchronous::detail::multi_queue_scheduler_policy<Q,FindPosition>
{
public:
typedef Q queue_type;
typedef typename Q::job_type job_type;
typedef typename boost::asynchronous::job_traits<typename Q::job_type>::diagnostic_table_type diag_type;
typedef stealing_multiqueue_threadpool_scheduler<Q,FindPosition,CPULoad,IsImmediate> this_type;
template<typename... Args>
stealing_multiqueue_threadpool_scheduler(size_t number_of_workers, Args... args)
: boost::asynchronous::detail::multi_queue_scheduler_policy<Q,FindPosition>(number_of_workers,std::move(args)...)
, m_number_of_workers(number_of_workers)
{
m_private_queues.reserve(number_of_workers);
for (size_t i = 0; i< number_of_workers;++i)
{
m_private_queues.push_back(
std::make_shared<boost::asynchronous::lockfree_queue<boost::asynchronous::any_callable> >());
}
}
template<typename... Args>
stealing_multiqueue_threadpool_scheduler(size_t number_of_workers, std::string const& name, Args... args)
: boost::asynchronous::detail::multi_queue_scheduler_policy<Q,FindPosition>(number_of_workers,std::move(args)...)
, m_number_of_workers(number_of_workers)
, m_name(name)
{
m_private_queues.reserve(number_of_workers);
for (size_t i = 0; i< number_of_workers;++i)
{
m_private_queues.push_back(
std::make_shared<boost::asynchronous::lockfree_queue<boost::asynchronous::any_callable> >());
}
set_name(name);
}
void constructor_done(std::weak_ptr<this_type> weak_self)
{
m_weak_self = weak_self;
if (IsImmediate)
init(m_number_of_workers,std::vector<boost::asynchronous::any_queue_ptr<job_type> >(),m_weak_self);
}
void init(size_t number_of_workers,std::vector<boost::asynchronous::any_queue_ptr<job_type> > const& others,std::weak_ptr<this_type> weak_self)
{
m_diagnostics = std::make_shared<diag_type>(number_of_workers);
m_thread_ids.reserve(number_of_workers);
m_group.reset(new boost::thread_group);
for (size_t i = 0; i< number_of_workers;++i)
{
std::promise<boost::thread*> new_thread_promise;
std::shared_future<boost::thread*> fu = new_thread_promise.get_future();
boost::thread* new_thread =
m_group->create_thread(std::bind(&stealing_multiqueue_threadpool_scheduler::run,this->m_queues,
m_private_queues[i],others,i,m_diagnostics,fu,weak_self));
new_thread_promise.set_value(new_thread);
m_thread_ids.push_back(new_thread->get_id());
}
}
~stealing_multiqueue_threadpool_scheduler()
{
for (size_t i = 0; i< m_number_of_workers;++i)
{
auto fct = m_diagnostics_fct;
auto diag = m_diagnostics;
auto l = [fct,diag]() mutable
{
if (fct)
fct(boost::asynchronous::scheduler_diagnostics(diag->get_map(),diag->get_current()));
};
boost::asynchronous::detail::default_termination_task<typename Q::diagnostic_type,boost::thread_group>
ttask(std::move(l));
// this task has to be executed lat => lowest prio
#ifndef BOOST_NO_RVALUE_REFERENCES
boost::asynchronous::any_callable job(std::move(ttask));
m_private_queues[i]->push(std::move(job),std::numeric_limits<std::size_t>::max());
#else
m_private_queues[i]->push(boost::asynchronous::any_callable(ttask),std::numeric_limits<std::size_t>::max());
#endif
}
}
//TODO move?
boost::asynchronous::any_joinable get_worker()const
{
return boost::asynchronous::any_joinable (boost::asynchronous::detail::worker_wrap<boost::thread_group>(m_group));
}
std::vector<boost::thread::id> thread_ids()const
{
return m_thread_ids;
}
boost::asynchronous::scheduler_diagnostics
get_diagnostics(std::size_t =0)const
{
return boost::asynchronous::scheduler_diagnostics(m_diagnostics->get_map(),m_diagnostics->get_current());
}
void clear_diagnostics()
{
m_diagnostics->clear();
}
void register_diagnostics_functor(std::function<void(boost::asynchronous::scheduler_diagnostics)> fct,
boost::asynchronous::register_diagnostics_type =
boost::asynchronous::register_diagnostics_type())
{
m_diagnostics_fct = fct;
}
void set_steal_from_queues(std::vector<boost::asynchronous::any_queue_ptr<job_type> > const& others)
{
init(m_number_of_workers,others,m_weak_self);
}
void set_name(std::string const& name)
{
for (size_t i = 0; i< m_number_of_workers;++i)
{
boost::asynchronous::detail::set_name_task<typename Q::diagnostic_type> ntask(name);
#ifndef BOOST_NO_RVALUE_REFERENCES
boost::asynchronous::any_callable job(std::move(ntask));
m_private_queues[i]->push(std::move(job),std::numeric_limits<std::size_t>::max());
#else
m_private_queues[i]->push(boost::asynchronous::any_callable(ntask),std::numeric_limits<std::size_t>::max());
#endif
}
}
void processor_bind(std::vector<std::tuple<unsigned int/*first core*/,unsigned int/*number of threads*/>> p)
{
// our thread (queue) index. 0 means "don't care" and is therefore not desirable)
size_t t = 0;
for(auto const& v : p)
{
for (size_t i = 0; i< std::get<1>(v) && (t < m_number_of_workers);++i)
{
boost::asynchronous::detail::processor_bind_task task(std::get<0>(v)+i);
boost::asynchronous::any_callable job(std::move(task));
m_private_queues[t++]->push(std::move(job),std::numeric_limits<std::size_t>::max());
}
}
}
std::vector<std::future<void>> execute_in_all_threads(boost::asynchronous::any_callable c)
{
std::vector<std::future<void>> res;
res.reserve(m_number_of_workers);
for (size_t i = 0; i< m_number_of_workers;++i)
{
std::promise<void> p;
auto fu = p.get_future();
res.emplace_back(std::move(fu));
boost::asynchronous::detail::execute_in_all_threads_task task(c,std::move(p));
m_private_queues[i]->push(std::move(task),std::numeric_limits<std::size_t>::max());
}
return res;
}
std::string get_name()const
{
return m_name;
}
// try to execute a job, return true
static bool execute_one_job(std::vector<std::shared_ptr<queue_type> > const& queues,size_t index,
std::vector<boost::asynchronous::any_queue_ptr<job_type> > const& other_queues,
CPULoad& cpu_load,std::shared_ptr<diag_type> diagnostics,
std::list<boost::asynchronous::any_continuation>& waiting)
{
bool popped = false;
// get a job
typename Q::job_type job;
try
{
bool popped = queues[index]->try_pop(job);
if (!popped)
{
// ok we have nothing to do, maybe we can steal some work?
for (std::size_t i=1; i< queues.size(); ++i)
{
if (index >= i)
{
popped = queues[(index-i)%queues.size()]->try_steal(job);
}
else
{
popped = queues[queues.size()-(i-index)]->try_steal(job);
}
if (popped)
break;
}
}
if (!popped)
{
// ok we have nothing to do, maybe we can steal some work from other pools?
for (std::size_t i=0; i< other_queues.size(); ++i)
{
popped = (*other_queues[i]).try_steal(job);
if (popped)
break;
}
}
// did we manage to pop or steal?
if (popped)
{
cpu_load.popped_job();
// log time
boost::asynchronous::job_traits<typename Q::job_type>::set_started_time(job);
// log thread
boost::asynchronous::job_traits<typename Q::job_type>::set_executing_thread_id(job,boost::this_thread::get_id());
// log current
boost::asynchronous::job_traits<typename Q::job_type>::add_current_diagnostic(index,job,diagnostics.get());
// execute job
job();
boost::asynchronous::job_traits<typename Q::job_type>::reset_current_diagnostic(index,diagnostics.get());
boost::asynchronous::job_traits<typename Q::job_type>::set_finished_time(job);
boost::asynchronous::job_traits<typename Q::job_type>::add_diagnostic(job,diagnostics.get());
}
else
{
// look for waiting tasks
if (!waiting.empty())
{
for (std::list<boost::asynchronous::any_continuation>::iterator it = waiting.begin(); it != waiting.end();)
{
if ((*it).is_ready())
{
boost::asynchronous::any_continuation c = std::move(*it);
it = waiting.erase(it);
c();
}
else
{
++it;
}
}
}
}
}
catch(boost::thread_interrupted&)
{
// task interrupted, no problem, just continue
}
catch(std::exception&)
{
if (popped)
{
boost::asynchronous::job_traits<typename Q::job_type>::set_failed(job);
boost::asynchronous::job_traits<typename Q::job_type>::set_finished_time(job);
boost::asynchronous::job_traits<typename Q::job_type>::add_diagnostic(job,diagnostics.get());
boost::asynchronous::job_traits<typename Q::job_type>::reset_current_diagnostic(index,diagnostics.get());
}
}
return popped;
}
static void run(std::vector<std::shared_ptr<queue_type> > const& queues,
std::shared_ptr<boost::asynchronous::lockfree_queue<boost::asynchronous::any_callable> > const& private_queue,
std::vector<boost::asynchronous::any_queue_ptr<job_type> > const& other_queues,
size_t index,std::shared_ptr<diag_type> diagnostics,std::shared_future<boost::thread*> self,
std::weak_ptr<this_type> this_)
{
boost::thread* t = self.get();
boost::asynchronous::detail::multi_queue_scheduler_policy<Q,FindPosition>::m_self_thread.reset(new thread_ptr_wrapper(t));
// thread scheduler => tss
boost::asynchronous::any_weak_scheduler<job_type> self_as_weak = boost::asynchronous::detail::lockable_weak_scheduler<this_type>(this_);
boost::asynchronous::get_thread_scheduler<job_type>(self_as_weak,true);
boost::asynchronous::get_own_queue_index<>(index+1,true);
std::list<boost::asynchronous::any_continuation>& waiting =
boost::asynchronous::get_continuations(std::list<boost::asynchronous::any_continuation>(),true);
CPULoad cpu_load;
while(true)
{
try
{
{
bool popped = execute_one_job(queues,index,other_queues,cpu_load,diagnostics,waiting);
if (!popped)
{
cpu_load.loop_done_no_job();
// nothing for us to do, give up our time slice
boost::this_thread::yield();
}
// check for shutdown
boost::asynchronous::any_callable djob;
popped = private_queue->try_pop(djob);
if (popped)
{
djob();
}
} // job destroyed (for destruction useful)
// check if we got an interruption job
boost::this_thread::interruption_point();
}
catch(boost::asynchronous::detail::shutdown_exception&)
{
// we are done, execute jobs posted short before to the end, then shutdown
while(execute_one_job(queues,index,other_queues,cpu_load,diagnostics,waiting));
delete boost::asynchronous::detail::multi_queue_scheduler_policy<Q,FindPosition>::m_self_thread.release();
return;
}
catch(boost::thread_interrupted&)
{
// task interrupted, no problem, just continue
}
catch(std::exception&)
{
// TODO, user-defined error
}
}
}
private:
size_t m_number_of_workers;
std::shared_ptr<boost::thread_group> m_group;
std::vector<boost::thread::id> m_thread_ids;
std::shared_ptr<diag_type> m_diagnostics;
std::weak_ptr<this_type> m_weak_self;
std::vector<std::shared_ptr<
boost::asynchronous::lockfree_queue<boost::asynchronous::any_callable>>> m_private_queues;
std::function<void(boost::asynchronous::scheduler_diagnostics)> m_diagnostics_fct;
const std::string m_name;
};
}} // boost::async::scheduler
#endif // BOOST_ASYNC_SCHEDULER_STEALING_MULTIQUEUE_THREADPOOL_SCHEDULER_HPP
| [
"christophe.j.henry@googlemail.com"
] | christophe.j.henry@googlemail.com |
05ee3fbd5b2648a390d996fbb8b4e6a96521f66a | 31c6face9f3a545a0b4df81a2f6c36362b9c5f81 | /mechanics/Widgets/actionentitywidget.h | d1671118e45e240cf81d010ec860d2b540129344 | [] | no_license | drblallo/Mapper | e92e5540e2b654b1d4408ffd77ed3f081d5c1968 | 8770fa4ec8a7faae4059f9652656fe699979134a | refs/heads/master | 2021-01-01T19:57:46.839135 | 2017-11-26T09:51:51 | 2017-11-26T09:51:51 | 98,729,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | h | #ifndef ACTIONENTITYWIDGET_H
#define ACTIONENTITYWIDGET_H
#include <QWidget>
namespace mechanics
{
class EntityAction;
}
using namespace mechanics;
namespace Ui {
class ActionEntityWidget;
}
class ActionEntityWidget : public QWidget
{
Q_OBJECT
public:
explicit ActionEntityWidget(QWidget *parent = 0, EntityAction* act = NULL);
~ActionEntityWidget();
private:
Ui::ActionEntityWidget *ui;
EntityAction* action;
};
#endif // ACTIONENTITYWIDGET_H
| [
"blalloscompany@gmail.com"
] | blalloscompany@gmail.com |
fa4b183133a5c27c90ebe74ae3677c1c0fa42d1a | 2bae07914bcd383fefe415194ffb63e2b007aff2 | /engine/modules/tool/tool_generic_data/include/tiki/tool_generic_data/generic_data_tag.hpp | 74455d3db07ed51ba7575a2491cd8e08c723b03a | [] | no_license | TikiTek/mechanica | ec4972b541bfb7dc685b0b7918785c5ca99622d2 | d151a818a279f1969b977ff7a935148b18ab9546 | refs/heads/master | 2021-10-09T07:27:23.308704 | 2021-10-08T07:42:04 | 2021-10-08T07:42:04 | 71,704,579 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 891 | hpp | #pragma once
#include "tiki/base/dynamic_string.hpp"
#include "tiki/base/types.hpp"
namespace tiki
{
class GenericDataTag
{
TIKI_NONCOPYABLE_CLASS( GenericDataTag );
public:
explicit GenericDataTag();
explicit GenericDataTag( const GenericDataTag* pCopyFrom );
~GenericDataTag();
const DynamicString& getTag() const;
void setTag( const DynamicString& tag );
const DynamicString& getContent() const;
void setContent( const DynamicString& content );
GenericDataTag* getChildTag() const;
const GenericDataTag* getChildTag();
void setChildTag( GenericDataTag* pChildTag );
bool parseTagString( const DynamicString& rawText );
DynamicString toString() const;
static bool isTagString( const DynamicString& rawText );
private:
DynamicString m_tag;
DynamicString m_content;
GenericDataTag* m_pChildTag;
};
}
| [
"mail@timboden.de"
] | mail@timboden.de |
3e9172cb8b65853efe9dd6032616749442a61044 | 09c5c4baed3d26701e866be100e4e52d9a34b856 | /StudyAlone/StudyAlone/SupervisorCCTV.h | 40b0907e07a0d00705931f64f298a4f8aee493a8 | [] | no_license | sangdo913/Algorithms | 556ac5fc789e35df2f65601e4439caca967edd7b | ee11265895d8ce3314f009df38166defc4b946c7 | refs/heads/master | 2022-09-11T12:00:58.615980 | 2022-07-31T11:11:04 | 2022-07-31T11:11:04 | 116,484,870 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,789 | h | #pragma once
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct CCTVInfo
{
typedef struct Cod { int r, c; } cod;
typedef enum {UP = 0b1, RIGHT = 0b0010, DOWN = 0b0100, LEFT = 0b1000} DIR;
typedef enum {floor = 0, wall = 6, sensing = 7, final = -1} OBSTACLE;
typedef enum {U = 0, R, D, L} CONV;
const int CCTVCount[6] = { -1,4,2,4,4,1 };
const int CCTVDirect[6] = { -1,RIGHT, LEFT | RIGHT, UP | RIGHT, LEFT | UP | RIGHT, 0b1111};
const int dr[4] = { -1,0,1,0 };
const int dc[4] = { 0,1,0,-1 };
int conv[4];
cod camera[8];
int map[10][10];
int n, m;
int cNum, minArea;
int check[10][10];
int checkFloor()
{
int res = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
res += (map[i][j] == floor);
}
}
return res;
}
void sense(cod &pos, int direct, int cnt)
{
cod next;
next.r = pos.r + dr[direct];
next.c = pos.c + dc[direct];
while (map[next.r][next.c] != wall && map[next.r][next.c] != final)
{
if (check[next.r][next.c] == -1 && map[next.r][next.c] == floor)
{
map[next.r][next.c] = sensing;
check[next.r][next.c] = cnt;
}
next.r += dr[direct];
next.c += dc[direct];
}
}
void cancleSensing(cod &pos, int direct, int cnt)
{
cod next;
next.r = pos.r + dr[direct];
next.c = pos.c + dc[direct];
while (map[next.r][next.c] != wall && map[next.r][next.c] != final)
{
if (map[next.r][next.c] == sensing && check[next.r][next.c] == cnt)
{
map[next.r][next.c] = 0;
check[next.r][next.c] = -1;
}
next.r += dr[direct];
next.c += dc[direct];
}
}
int min(int i1, int i2)
{
return i1 < i2 ? i1 : i2;
}
void getSafeArea(int cnt)
{
if (cnt == cNum)
{
minArea = min(minArea, checkFloor());
return;
}
for (int d = 0; d < CCTVCount[map[camera[cnt].r][camera[cnt].c]]; d++)
{
int directions = CCTVDirect[map[camera[cnt].r][camera[cnt].c]];
for (int i = 0; i < 4; i++)
{
if (directions & conv[i])
{
sense(camera[cnt], (i + d) % 4,cnt );
}
}
getSafeArea(cnt + 1);
for (int i = 0; i < 4; i++)
{
if (directions & conv[i])
{
cancleSensing(camera[cnt], (i + d) % 4,cnt);
}
}
}
}
void init()
{
memset(map, -1, sizeof(map));
memset(check, -1, sizeof(check));
cNum = 0;
conv[U] = UP;
conv[R] = RIGHT;
conv[D] = DOWN;
conv[L] = LEFT;
minArea = 100;
scanf("%d %d\n", &n, &m);
for(int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
scanf("%d ", &map[i][j]);
if (map[i][j] != wall && map[i][j] != floor)
{
camera[cNum].r = i;
camera[cNum++].c = j;
}
}
}
}CCTV_info;
int CCTV()
{
CCTV_info.init();
CCTV_info.getSafeArea(0);
int res = CCTV_info.minArea;
cout << res << '\n';
return 0;
} | [
"sangdo913@naver.com"
] | sangdo913@naver.com |
018621d8b2cd6dd8510fa9c0f020671775000083 | 1ac3f7213b2c4cda9872275d5c735dee27333825 | /codes/data_structures/stack/cpp/templated_stack.cpp | 4f72da0bff8462f87633cad5ae592efdd7f18371 | [
"MIT"
] | permissive | basu0001/first-pr-Hacktoberfest--2019 | b13a805590bd80f955a158a841dc657c6439dfd9 | 479553e67728fa8409dbceed7cb3d7554127c946 | refs/heads/master | 2021-06-28T10:24:15.910424 | 2021-02-02T07:38:31 | 2021-02-02T07:38:31 | 212,898,561 | 8 | 55 | MIT | 2021-02-01T18:11:35 | 2019-10-04T20:37:04 | Java | UTF-8 | C++ | false | false | 571 | cpp | #include <exception>
#include <iostream>
#include "Stack.hpp"
/*
* Main is only used to test different
* methods on my stack
*
*/
int main(void) {
Stack<int> s;
std::cout << "Initializing stack" << std::endl;
for (int i = 0; i < 10; ++i)
s.push(i);
std::cout << "Done!" << std::endl;
while ( !s.empty() )
{
std::cout << s.top() << std::endl;
s.pop();
}
std::cout << "Popping off another (inexistant) element" << std::endl;
try
{
s.pop();
}
catch (std::exception& e)
{
std::cerr << "[ERR] " << e.what() << std::endl;
}
return 0;
}
| [
"rajarshee1234@gmail.com"
] | rajarshee1234@gmail.com |
70fa4b3fe5aa99d79dfcdca4b04c33c071d38848 | 040eab433f00786ec34142f242c0735e8c19fd9c | /samples/threat_level/src/GameOverState.hpp | bc9d7f62528ec2774a79ee22dcebb55783e72e48 | [
"Zlib"
] | permissive | MORTAL2000/crogine | d7c73f174dfd7b1cf89ee693f98c7ecd41bb11f4 | 488b46dc3f706def8fdae30346c248f01c95b49c | refs/heads/master | 2020-12-20T20:52:56.810085 | 2020-01-24T15:41:32 | 2020-01-24T15:41:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,220 | hpp | /*-----------------------------------------------------------------------
Matt Marchant 2017
http://trederia.blogspot.com
crogine test application - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
#ifndef TL_GAMEOVER_STATE_HPP_
#define TL_GAMEOVER_STATE_HPP_
#include <crogine/core/State.hpp>
#include <crogine/ecs/Scene.hpp>
#include <crogine/graphics/ResourceAutomation.hpp>
#include <crogine/graphics/Texture.hpp>
#include "StateIDs.hpp"
#include "ResourceIDs.hpp"
namespace cro
{
class UISystem;
class SpriteSheet;
}
struct SharedResources;
using ResourcePtr = std::unique_ptr<SharedResources>;
class GameOverState final : public cro::State
{
public:
GameOverState(cro::StateStack&, cro::State::Context, ResourcePtr&);
~GameOverState() = default;
cro::StateID getStateID() const override { return States::GameOver; }
bool handleEvent(const cro::Event&) override;
void handleMessage(const cro::Message&) override;
bool simulate(cro::Time) override;
void render() override;
private:
cro::Scene m_uiScene;
SharedResources& m_sharedResources;
cro::UISystem* m_uiSystem;
cro::Texture m_backgroundTexture;
void load();
void updateView();
void createTextBox(const cro::SpriteSheet&);
void handleTextEvent(const cro::Event&);
void updateTextBox();
};
#endif //TL_GAMEOVER_STATE_HPP_ | [
"matty_styles@hotmail.com"
] | matty_styles@hotmail.com |
a078be2d0024efc7b378e3a6a1508818642413b4 | 020aa89d2205271caa1023aeba139539f9a621a3 | /list/seqList.h | 2b73a2fd0200e8d230c1811dc752b99ddac2de14 | [] | no_license | pengzi2017/Data-Structure | 39344f7d0bca9d73be438e6a9aae906f3a661a13 | 1c135b416ddb4e43219cbee39babdc46c232e00e | refs/heads/master | 2021-01-22T21:21:51.644461 | 2017-09-13T09:09:38 | 2017-09-13T09:09:38 | 85,414,711 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,583 | h | //顺序表
#ifndef SEQLIST_H
#define SEQLIST_H
#include"list.h"
#include<iostream>
using namespace std;
const int defaultSize = 100;
template<class T>
class SeqList:public List<T>
{
public:
SeqList(int sz=defaultSize);
SeqList(SeqList<T>&L);
~SeqList() { delete[] data; };
int Size()const {return size;};//表的最大体积
void resize();//调整表的大小
int Length()const {return length;};//表的长度
int search(const T x)const;//查找x,返回x的位置,找不到则返回负值;
bool getData(int i, T&x)const;//取第i个数,传值给x
bool setData(int i, const T x);//将第i个数的值设置成x
bool insert(int i, const T x);//在i位置 后一位 插入x(i从1计数)
bool remove(int i, T&x);//删除第i位的值,传值给x(i从1计数)
bool isEmpty()const//判断是否空
{
if (length == 0)
return true;
else
return false;
}
bool isFull()const//判断是否满
{
if (length == size)
return true;
else
return false;
}
void sort();//排序
void input(T endTag);
void output()const;
//friend ostream operator<<(ostream &out,SeqList<T>&L);
SeqList<T>operator=(SeqList<T>&L);
private:
T *data;
int length;//长度,从1计数
int size;//最大容量
};
template<class T>
SeqList<T>::SeqList(int sz)
{
size = sz;
data = new T[size];
length = 0;
}
template<class T>
SeqList<T>::SeqList(SeqList<T>& L)
{
size = L.size;
length = L.length;
data = new T[size + defaultSize];
if (data == NULL)
{
cout << "内存分配错误" << endl;
exit(1);
}
for (int i = 0; i < length; i++)
data[i] = L.data[i];
}
template<class T>
void SeqList<T>::resize()
{
T *datas = new T[size];
for (int i = 0; i < length; i++)
datas[i] = data[i];
data = new T[size + defaultSize];
for (int i = 0; i < length; i++)
data[i] = datas[i];
size = size + defaultSize;
delete[] datas;
}
template<class T>
int SeqList<T>::search(const T x) const
{
for (int i = 0; i < length; i++)
{
if (data[i] == x)
return i + 1;
}
return -1;
}
template<class T>
bool SeqList<T>::getData(int i, T & x) const
{
if (i<1 || i>length)
return false;
else
{
x = data[i - 1];
return true;
}
}
template<class T>
bool SeqList<T>::setData(int i, const T x)
{
if (i<1 || i>length)
return false;
else
data[i - 1] = x;
return true;
}
template<class T>
bool SeqList<T>::insert(int i, const T x)
{
if (i<0 || i>length)return false;
if (size - length < 10)
resize();
for (int j = length; j > i; j--)
data[j] = data[j - 1];
data[i] = x;
length++;
return true;
}
template<class T>
bool SeqList<T>::remove(int i, T & x)
{
if (i < 1 || i>length)return false;
x = data[i - 1];
for (int j = i - 1; i < length; i++)
data[j] = data[j + 1];
length--;
return true;
}
template<class T>
void SeqList<T>::sort()
{
//升序,冒泡排序
int bubbleNum;
do
{
bubbleNum = 0;
for (int i = 0; i<length - 1; i++)
if (data[i] > data[i + 1])
{
T temp = data[i + 1];
data[i + 1] = data[i];
data[i] = temp;
bubbleNum++;
}
} while (bubbleNum != 0);
}
template<class T>
void SeqList<T>::input(T endTag)
{
T value;
cin >> value;
while (value != endTag)
{
if (size - length < 10)
resize();
data[length] = value;
length++;
cin >> value;
}
}
template<class T>
void SeqList<T>::output() const
{
for (int i = 0; i < length; i++)
cout << data[i] << ",";
cout << endl;
}
template<class T>
SeqList<T> SeqList<T>::operator=(SeqList<T>& L)
{
size = L.size;
length = L.length;
data = new T[size];
for (int i = 0; i < length; i++)
data[i] = L.data[i];
return *this;
}
#endif
| [
"15804052717@163.com"
] | 15804052717@163.com |
ce46a56086a3e463dd5b2a593504331fcab6d8b5 | 90c720b09228236ac0a0419b83bb4c870b1c7714 | /src/qt/addressbookpage.cpp | f660c870bc433e97170ee9f85d86e02bc6160471 | [
"MIT"
] | permissive | FilokOfficial/filok | 80b6fb2d4a47a20da21d8b41aeede290a80cfcb7 | 20dbb5f6e6f5f73b0676f4bf302233644d4d7ce1 | refs/heads/master | 2020-04-18T18:43:48.645184 | 2019-02-05T21:28:24 | 2019-02-05T21:28:24 | 167,693,244 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,169 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The Filok developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/filok-config.h"
#endif
#include "addressbookpage.h"
#include "ui_addressbookpage.h"
#include "addresstablemodel.h"
#include "bitcoingui.h"
#include "csvmodelwriter.h"
#include "editaddressdialog.h"
#include "guiutil.h"
#include <QIcon>
#include <QMenu>
#include <QMessageBox>
#include <QSortFilterProxyModel>
AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget* parent) : QDialog(parent),
ui(new Ui::AddressBookPage),
model(0),
mode(mode),
tab(tab)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->newAddress->setIcon(QIcon());
ui->copyAddress->setIcon(QIcon());
ui->deleteAddress->setIcon(QIcon());
ui->exportButton->setIcon(QIcon());
#endif
switch (mode) {
case ForSelection:
switch (tab) {
case SendingTab:
setWindowTitle(tr("Choose the address to send coins to"));
break;
case ReceivingTab:
setWindowTitle(tr("Choose the address to receive coins with"));
break;
}
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableView->setFocus();
ui->closeButton->setText(tr("C&hoose"));
ui->exportButton->hide();
break;
case ForEditing:
switch (tab) {
case SendingTab:
setWindowTitle(tr("Sending addresses"));
break;
case ReceivingTab:
setWindowTitle(tr("Receiving addresses"));
break;
}
break;
}
switch (tab) {
case SendingTab:
ui->labelExplanation->setText(tr("These are your FLK addresses for sending payments. Always check the amount and the receiving address before sending coins."));
ui->deleteAddress->setVisible(true);
break;
case ReceivingTab:
ui->labelExplanation->setText(tr("These are your FLK addresses for receiving payments. It is recommended to use a new receiving address for each transaction."));
ui->deleteAddress->setVisible(false);
break;
}
// Context menu actions
QAction* copyAddressAction = new QAction(tr("&Copy Address"), this);
QAction* copyLabelAction = new QAction(tr("Copy &Label"), this);
QAction* editAction = new QAction(tr("&Edit"), this);
deleteAction = new QAction(ui->deleteAddress->text(), this);
// Build context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(editAction);
if (tab == SendingTab)
contextMenu->addAction(deleteAction);
contextMenu->addSeparator();
// Connect signals for context menu actions
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction()));
connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));
connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked()));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept()));
}
AddressBookPage::~AddressBookPage()
{
delete ui;
}
void AddressBookPage::setModel(AddressTableModel* model)
{
this->model = model;
if (!model)
return;
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
switch (tab) {
case ReceivingTab:
// Receive filter
proxyModel->setFilterRole(AddressTableModel::TypeRole);
proxyModel->setFilterFixedString(AddressTableModel::Receive);
break;
case SendingTab:
// Send filter
proxyModel->setFilterRole(AddressTableModel::TypeRole);
proxyModel->setFilterFixedString(AddressTableModel::Send);
break;
}
ui->tableView->setModel(proxyModel);
ui->tableView->sortByColumn(0, Qt::AscendingOrder);
// Set column widths
#if QT_VERSION < 0x050000
ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);
#else
ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);
#endif
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
this, SLOT(selectionChanged()));
// Select row for newly created address
connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(selectNewAddress(QModelIndex, int, int)));
selectionChanged();
}
void AddressBookPage::on_copyAddress_clicked()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address);
}
void AddressBookPage::onCopyLabelAction()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label);
}
void AddressBookPage::onEditAction()
{
if (!model)
return;
if (!ui->tableView->selectionModel())
return;
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if (indexes.isEmpty())
return;
EditAddressDialog dlg(
tab == SendingTab ?
EditAddressDialog::EditSendingAddress :
EditAddressDialog::EditReceivingAddress,
this);
dlg.setModel(model);
QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
dlg.loadRow(origIndex.row());
dlg.exec();
}
void AddressBookPage::on_newAddress_clicked()
{
if (!model)
return;
EditAddressDialog dlg(
tab == SendingTab ?
EditAddressDialog::NewSendingAddress :
EditAddressDialog::NewReceivingAddress,
this);
dlg.setModel(model);
if (dlg.exec()) {
newAddressToSelect = dlg.getAddress();
}
}
void AddressBookPage::on_deleteAddress_clicked()
{
QTableView* table = ui->tableView;
if (!table->selectionModel())
return;
QModelIndexList indexes = table->selectionModel()->selectedRows();
if (!indexes.isEmpty()) {
table->model()->removeRow(indexes.at(0).row());
}
}
void AddressBookPage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView* table = ui->tableView;
if (!table->selectionModel())
return;
if (table->selectionModel()->hasSelection()) {
switch (tab) {
case SendingTab:
// In sending tab, allow deletion of selection
ui->deleteAddress->setEnabled(true);
ui->deleteAddress->setVisible(true);
deleteAction->setEnabled(true);
break;
case ReceivingTab:
// Deleting receiving addresses, however, is not allowed
ui->deleteAddress->setEnabled(false);
ui->deleteAddress->setVisible(false);
deleteAction->setEnabled(false);
break;
}
ui->copyAddress->setEnabled(true);
} else {
ui->deleteAddress->setEnabled(false);
ui->copyAddress->setEnabled(false);
}
}
void AddressBookPage::done(int retval)
{
QTableView* table = ui->tableView;
if (!table->selectionModel() || !table->model())
return;
// Figure out which address was selected, and return it
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes) {
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if (returnValue.isEmpty()) {
// If no address entry selected, return rejected
retval = Rejected;
}
QDialog::done(retval);
}
void AddressBookPage::on_exportButton_clicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(this,
tr("Export Address List"), QString(),
tr("Comma separated file (*.csv)"), NULL);
if (filename.isNull())
return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole);
writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole);
if (!writer.write()) {
QMessageBox::critical(this, tr("Exporting Failed"),
tr("There was an error trying to save the address list to %1. Please try again.").arg(filename));
}
}
void AddressBookPage::contextualMenu(const QPoint& point)
{
QModelIndex index = ui->tableView->indexAt(point);
if (index.isValid()) {
contextMenu->exec(QCursor::pos());
}
}
void AddressBookPage::selectNewAddress(const QModelIndex& parent, int begin, int /*end*/)
{
QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent));
if (idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) {
// Select row of newly created address, once
ui->tableView->setFocus();
ui->tableView->selectRow(idx.row());
newAddressToSelect.clear();
}
}
| [
"root"
] | root |
9694e535e1cb20131840c1281b5a9f2b7b9aeaa1 | c1b7e15de90d3b7ce33d51f002c99b1d9b6ca715 | /ChineseChess/CommonLib/CommandDecoder.h | f4b8c68f4f26ce2226cc47ff5bfbfe873f15bac5 | [] | no_license | mainina/ChineseChess | a4c60be7ce31228b98f850e6514bb59114d7e6cc | 40a3191bd9ecc8e2297079446d95752e73d73611 | refs/heads/master | 2021-01-02T08:13:29.982351 | 2017-08-25T07:34:18 | 2017-08-25T07:34:18 | 96,449,367 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 480 | h | #pragma once
#include <string>
#include "Decoder.h"
#include "CmdData.h"
#include <vector>
class CommandDecoder: public Decoder
{
public:
CommandDecoder(char bufRecv[]);
~CommandDecoder();
virtual bool decode();
CmdData* getData() { return mCmdData; }
int getCommand() { return cmd; }
const char getChBegin() { return chBegin; }
const char getChEnd() { return chEnd; }
protected:
const char chBegin = 0x02;
const char chEnd = 0x03;
int cmd;
CmdData* mCmdData;
};
| [
"mainina200@sohu.com"
] | mainina200@sohu.com |
5823f5f0c88476ed68ec683e504041eef7742720 | 14a2979c0baeb2ef14b3f34bb4017d541c8b0d8f | /apps/DataCollections/chainblock.h | a39b8a6a29db0a6392469762861d24c074bfcac3 | [
"MIT"
] | permissive | MangoCats/aosuite | 1fb6d3c929ad0634b07beb3a2fc7548dbcb6f0e9 | bddabf44eb965f55a6f8628040c73fea4902db2f | refs/heads/master | 2021-12-07T18:59:35.991784 | 2021-09-16T21:55:53 | 2021-09-16T21:55:53 | 144,416,778 | 0 | 0 | MIT | 2018-08-11T20:39:07 | 2018-08-11T20:39:06 | null | UTF-8 | C++ | false | false | 2,437 | h | /* MIT License
*
* Copyright (c) 2018 Assign Onward
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef CHAINBLOCK_H
#define CHAINBLOCK_H
#include "datavarlength.h"
#include "hash.h"
#include <QMap>
#define PropertyMap QMap<typeCode_t,DataItem *>
/**
* @brief The ChainBlock class - contains a block in the chain
*/
class ChainBlock : public DataVarLength
{
Q_OBJECT
public:
explicit ChainBlock( QByteArray di = QByteArray(), QObject *p = NULL );
ChainBlock( const ChainBlock &r, QObject *p = NULL )
: DataVarLength( QByteArray(), AO_GENESIS_BLOCK, p ? p : r.parent() ),
hash( r.hash ), properties( r.properties ) {}
void operator = ( const QByteArray &di );
Hash getHash() const { return hash; }
void setHash( const Hash &h ) { hash = h; }
QByteArray toDataItem( bool cf = false );
bool isValid() { return hash.isValid(); }
DataItem *getProp( typeCode_t key ) { return ( properties.contains( key ) ) ? properties.value( key ) : new DataItem(AO_UNDEFINED_DATAITEM,this); }
void add( const typeCode_t& key, DataItem *value ) { properties.insert( key, value ); }
private:
Hash hash; // hash signature (unique ID) of the genesis block
PropertyMap properties; // Collection of properties that describe the chain
};
#endif // CHAINBLOCK_H
| [
"assign.onward@gmail.com"
] | assign.onward@gmail.com |
36c1395b78dabd497d5fdbd98587c5feb080f233 | 2927dcbbb0723e8e76710040407c5561fb6b0121 | /04096/windows/architectures/source/tool/GLView.h | cd51ff3227d26f939d10f18f4dbef14653f17bd3 | [] | 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 | 927 | h | #ifndef GLView_h
#define GLView_h
#include <stdint.h>
#include <QtGui>
#include <QGLWidget>
#include "project.h"
namespace aurora {
// opengl view
class GLWidget : public QGLWidget
{
Q_OBJECT
public:
GLWidget(const QGLWidget* shareWidget = 0);
~GLWidget();
project::Project *project;
QSize minimumSizeHint() const;
QSize sizeHint() const;
signals:
void initialize();
protected:
void initializeGL();
void resizeGL(int width, int height);
void paintGL();
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
};
// opengl viewport with menu bar (e.g. for camera selection) and opengl view
class GLView : public QWidget
{
public:
GLView(QMenu* cameraMenu, const QGLWidget* shareWidget = 0);
virtual ~GLView();
virtual void paintEvent(QPaintEvent* e);
GLWidget* inner;
};
} // namespace aurora
#endif
| [
"youngthug@youngthug.com"
] | youngthug@youngthug.com |
95ac183ce96fcefdc06183e8167fc7302bc299fa | f0bd63eddce3d90c1d56ce6782b99557a6daf04b | /homework/assignment26.cpp | 23c88294ee26ad014374b8b07ec857d8d4306627 | [] | no_license | rsguru/cs124 | 205092b65b43c916d2abe456cf33dad93b160edd | 0579cc77c7e38c79781a72cc425668ae8bce58eb | refs/heads/master | 2021-01-11T20:42:38.138083 | 2016-12-22T04:43:02 | 2016-12-22T04:43:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,124 | cpp | /***********************************************************************
* Program:
* Assignment ##, ???? (e.g. Assignment 10, Hello World)
* Brother {Cook, Comeau, Falin, Lilya, Honeycutt, Unsicker, Peterson, Phair, Ellsworth}, CS124
* Author:
* your name
* Summary:
* Enter a brief description of your program here! Please note that if
* you do not take the time to fill out this block, YOU WILL LOSE POINTS.
* Before you begin working, estimate the time you think it will
* take you to do the assignment and include it in this header block.
* Before you submit the assignment include the actual time it took.
*
* Estimated: 0.0 hrs
* Actual: 0.0 hrs
* Please describe briefly what was the most difficult part.
************************************************************************/
#include <iostream>
#include <fstream>
using namespace std;
void getFileName(char fileName[]);
float readFile(char fileName[]);
void displayAverage(float sum);
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
int main()
{
char fileName[256];
getFileName(fileName);
float sum = readFile(fileName);
if (sum != -1)
displayAverage(sum);
else
cout << "Error reading file \"" << fileName << "\""
<< endl;
return 0;
}
void getFileName(char fileName[])
{
cout << "Please enter the filename: ";
cin >> fileName;
}
float readFile(char fileName[])
{
ifstream fin(fileName);
if (fin.fail())
{
return -1;
}
float data[10];
float sum = 0;
int count = 0;
while (fin >> data[count])
{
sum += data;
count++;
}
if (count != 10)
{
fin.close();
return -1;
}
fin.close();
cout.precision(0);
cout.setf(ios::fixed);
return sum / 10;
}
void displayAverage(float sum)
{
cout << "Average Grade: " << sum << "%\n";
}
| [
"drew@lundgren.us"
] | drew@lundgren.us |
48dedb912397a01916cd58169e0dd5ada1ede497 | 98157b3124db71ca0ffe4e77060f25503aa7617f | /codeforces/470/c.cpp | f46ccf3e2eb53cd918b4f8761615e823ceb4c394 | [] | no_license | wiwitrifai/competitive-programming | c4130004cd32ae857a7a1e8d670484e236073741 | f4b0044182f1d9280841c01e7eca4ad882875bca | refs/heads/master | 2022-10-24T05:31:46.176752 | 2022-09-02T07:08:05 | 2022-09-02T07:08:35 | 59,357,984 | 37 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,468 | cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
struct trie {
int l, r, cnt;
trie() : l(0), r(0), cnt(0) {}
} node[N * 55];
int p[N], a[N], cntr;
void add(int x) {
int now = 1;
++node[now].cnt;
for (int i = 29; i >= 0; --i) {
if (x & (1 << i)) {
if (node[now].r == 0) node[now].r = cntr++;
now = node[now].r;
}
else {
if (node[now].l == 0) node[now].l = cntr++;
now = node[now].l;
}
++node[now].cnt;
}
}
void remove(int x) {
int now = 1;
--node[now].cnt;
for (int i = 29; i >= 0; --i) {
if (x & (1 << i))
now = node[now].r;
else
now = node[now].l;
if (!now) break;
--node[now].cnt;
}
}
int get(int x) {
int now = 1, ret = 0;
for (int i = 29; i >= 0; --i) {
int il = node[now].l, ir = node[now].r;
if ((x & (1 << i)) == 0) {
if (il > 0 && node[il].cnt > 0) {
now = il;
}
else {
ret |= (1 << i);
now = ir;
}
}
else {
if (ir > 0 && node[ir].cnt > 0) {
now = ir;
}
else {
ret |= (1 << i);
now = il;
}
}
}
return ret;
}
int main() {
int n;
scanf("%d", &n);
cntr = 2;
for (int i = 0; i < n; ++i)
scanf("%d", a+i);
for (int i = 0; i < n; ++i) {
scanf("%d", p+i), add(p[i]);
}
for (int i = 0; i < n; ++i) {
int ans = get(a[i]);
remove(ans^a[i]);
printf("%d ", ans);
}
printf("\n");
return 0;
} | [
"wiwitrifai@gmail.com"
] | wiwitrifai@gmail.com |
d7e454abbaa3ab965ed867ac3cf97a42f17e3eb2 | 37ff29a9a83eafbf0f54e2ce0bf2c0255b1663a1 | /devel/.private/map_msgs/include/map_msgs/GetMapROIResponse.h | 77b136b55ea4b20e5d092b076594262f1cc1801c | [] | no_license | wy7727/husky | f8d9c2a05487f66efbfb58e8fc1c141efc10e177 | 7925bc34ae316639aef88fc3e6a8d36aba12620b | refs/heads/master | 2020-04-09T12:09:41.420418 | 2019-12-01T09:24:24 | 2019-12-01T09:24:24 | 160,337,603 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,838 | h | // Generated by gencpp from file map_msgs/GetMapROIResponse.msg
// DO NOT EDIT!
#ifndef MAP_MSGS_MESSAGE_GETMAPROIRESPONSE_H
#define MAP_MSGS_MESSAGE_GETMAPROIRESPONSE_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 <nav_msgs/OccupancyGrid.h>
namespace map_msgs
{
template <class ContainerAllocator>
struct GetMapROIResponse_
{
typedef GetMapROIResponse_<ContainerAllocator> Type;
GetMapROIResponse_()
: sub_map() {
}
GetMapROIResponse_(const ContainerAllocator& _alloc)
: sub_map(_alloc) {
(void)_alloc;
}
typedef ::nav_msgs::OccupancyGrid_<ContainerAllocator> _sub_map_type;
_sub_map_type sub_map;
typedef boost::shared_ptr< ::map_msgs::GetMapROIResponse_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::map_msgs::GetMapROIResponse_<ContainerAllocator> const> ConstPtr;
}; // struct GetMapROIResponse_
typedef ::map_msgs::GetMapROIResponse_<std::allocator<void> > GetMapROIResponse;
typedef boost::shared_ptr< ::map_msgs::GetMapROIResponse > GetMapROIResponsePtr;
typedef boost::shared_ptr< ::map_msgs::GetMapROIResponse const> GetMapROIResponseConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::map_msgs::GetMapROIResponse_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::map_msgs::GetMapROIResponse_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace map_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'nav_msgs': ['/opt/ros/kinetic/share/nav_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'map_msgs': ['/home/ying/wy_ws/src/navigation_msgs/map_msgs/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< ::map_msgs::GetMapROIResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::map_msgs::GetMapROIResponse_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::map_msgs::GetMapROIResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::map_msgs::GetMapROIResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::map_msgs::GetMapROIResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::map_msgs::GetMapROIResponse_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::map_msgs::GetMapROIResponse_<ContainerAllocator> >
{
static const char* value()
{
return "4d1986519c00d81967d2891a606b234c";
}
static const char* value(const ::map_msgs::GetMapROIResponse_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x4d1986519c00d819ULL;
static const uint64_t static_value2 = 0x67d2891a606b234cULL;
};
template<class ContainerAllocator>
struct DataType< ::map_msgs::GetMapROIResponse_<ContainerAllocator> >
{
static const char* value()
{
return "map_msgs/GetMapROIResponse";
}
static const char* value(const ::map_msgs::GetMapROIResponse_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::map_msgs::GetMapROIResponse_<ContainerAllocator> >
{
static const char* value()
{
return "nav_msgs/OccupancyGrid sub_map\n\
\n\
================================================================================\n\
MSG: nav_msgs/OccupancyGrid\n\
# This represents a 2-D grid map, in which each cell represents the probability of\n\
# occupancy.\n\
\n\
Header header \n\
\n\
#MetaData for the map\n\
MapMetaData info\n\
\n\
# The map data, in row-major order, starting with (0,0). Occupancy\n\
# probabilities are in the range [0,100]. Unknown is -1.\n\
int8[] data\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\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
\n\
================================================================================\n\
MSG: nav_msgs/MapMetaData\n\
# This hold basic information about the characterists of the OccupancyGrid\n\
\n\
# The time at which the map was loaded\n\
time map_load_time\n\
# The map resolution [m/cell]\n\
float32 resolution\n\
# Map width [cells]\n\
uint32 width\n\
# Map height [cells]\n\
uint32 height\n\
# The origin of the map [m, m, rad]. This is the real-world pose of the\n\
# cell (0,0) in the map.\n\
geometry_msgs/Pose origin\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\
";
}
static const char* value(const ::map_msgs::GetMapROIResponse_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::map_msgs::GetMapROIResponse_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.sub_map);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct GetMapROIResponse_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::map_msgs::GetMapROIResponse_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::map_msgs::GetMapROIResponse_<ContainerAllocator>& v)
{
s << indent << "sub_map: ";
s << std::endl;
Printer< ::nav_msgs::OccupancyGrid_<ContainerAllocator> >::stream(s, indent + " ", v.sub_map);
}
};
} // namespace message_operations
} // namespace ros
#endif // MAP_MSGS_MESSAGE_GETMAPROIRESPONSE_H
| [
"wuying277727@gmail.com"
] | wuying277727@gmail.com |
b9774cbe9b1df1babfbc302fb90ad3be3c93b30e | 73dd6869ad9e72ca20efc9c3881c626a08290f58 | /src/client/GameProc/CallGM.h | 44465e66de94d6f88c9bbe2f0f5a98f764a14771 | [] | no_license | rcirca/irose | 76cd50fa223375c67e6db412aea2ab941d4c1934 | 39afb7d253f66c0f5f6661d0cb0c179c64a6e64e | refs/heads/master | 2020-03-19T16:21:58.555061 | 2018-05-23T13:03:18 | 2018-05-23T13:03:18 | 136,712,714 | 4 | 4 | null | 2018-06-09T10:17:04 | 2018-06-09T10:17:04 | null | UHC | C++ | false | false | 317 | h | #ifndef _CALLGM_
#define _CALLGM_
#include <string>
///
/// 유져의 GM 호출 요청을 웹으로 전송( 각 국가별 게시판 )
///
class CCallGM
{
public:
CCallGM(void);
~CCallGM(void);
void CallGM( std::string& strServerName, std::string& strChannelName, std::string& strMsg );
};
#endif //_CALLGM_
| [
"ralphminderhoud@gmail.com"
] | ralphminderhoud@gmail.com |
b17cad2cd536c4dcef182031a32efe6fdd0618a0 | 094cd67dd4904fbb7d7befd32f1684275e994d5b | /src/utilstrencodings.cpp | bca98360b0695d9d73b3cf2a4b0417d01875476c | [
"MIT"
] | permissive | Arinerron/jobecoin | a9219ee50b927fefe657e1844987c69e422fb81f | d6c966cf94c44061c157da77def3e15ecb866a2b | refs/heads/master | 2021-08-20T02:55:06.170471 | 2017-11-28T02:05:06 | 2017-11-28T02:05:06 | 112,209,637 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,962 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Jobecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <utilstrencodings.h>
#include <tinyformat.h>
#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <limits>
static const std::string CHARS_ALPHA_NUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
static const std::string SAFE_CHARS[] =
{
CHARS_ALPHA_NUM + " .,;-_/:?@()", // SAFE_CHARS_DEFAULT
CHARS_ALPHA_NUM + " .,;-_?@", // SAFE_CHARS_UA_COMMENT
CHARS_ALPHA_NUM + ".-_", // SAFE_CHARS_FILENAME
};
std::string SanitizeString(const std::string& str, int rule)
{
std::string strResult;
for (std::string::size_type i = 0; i < str.size(); i++)
{
if (SAFE_CHARS[rule].find(str[i]) != std::string::npos)
strResult.push_back(str[i]);
}
return strResult;
}
const signed char p_util_hexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
signed char HexDigit(char c)
{
return p_util_hexdigit[(unsigned char)c];
}
bool IsHex(const std::string& str)
{
for(std::string::const_iterator it(str.begin()); it != str.end(); ++it)
{
if (HexDigit(*it) < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
bool IsHexNumber(const std::string& str)
{
size_t starting_location = 0;
if (str.size() > 2 && *str.begin() == '0' && *(str.begin()+1) == 'x') {
starting_location = 2;
}
for (auto c : str.substr(starting_location)) {
if (HexDigit(c) < 0) return false;
}
// Return false for empty string or "0x".
return (str.size() > starting_location);
}
std::vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
std::vector<unsigned char> vch;
while (true)
{
while (isspace(*psz))
psz++;
signed char c = HexDigit(*psz++);
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = HexDigit(*psz++);
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
std::vector<unsigned char> ParseHex(const std::string& str)
{
return ParseHex(str.c_str());
}
void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
size_t colon = in.find_last_of(':');
// if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
bool fHaveColon = colon != in.npos;
bool fBracketed = fHaveColon && (in[0]=='[' && in[colon-1]==']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
int32_t n;
if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
in = in.substr(0, colon);
portOut = n;
}
}
if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
hostOut = in.substr(1, in.size()-2);
else
hostOut = in;
}
std::string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string strRet = "";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
std::string EncodeBase64(const std::string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
std::vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
std::string DecodeBase64(const std::string& str)
{
std::vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return std::string((const char*)vchRet.data(), vchRet.size());
}
std::string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
std::string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
std::string EncodeBase32(const std::string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
std::vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
std::string DecodeBase32(const std::string& str)
{
std::vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return std::string((const char*)vchRet.data(), vchRet.size());
}
static bool ParsePrechecks(const std::string& str)
{
if (str.empty()) // No empty string allowed
return false;
if (str.size() >= 1 && (isspace(str[0]) || isspace(str[str.size()-1]))) // No padding allowed
return false;
if (str.size() != strlen(str.c_str())) // No embedded NUL characters allowed
return false;
return true;
}
bool ParseInt32(const std::string& str, int32_t *out)
{
if (!ParsePrechecks(str))
return false;
char *endp = nullptr;
errno = 0; // strtol will not set errno if valid
long int n = strtol(str.c_str(), &endp, 10);
if(out) *out = (int32_t)n;
// Note that strtol returns a *long int*, so even if strtol doesn't report an over/underflow
// we still have to check that the returned value is within the range of an *int32_t*. On 64-bit
// platforms the size of these types may be different.
return endp && *endp == 0 && !errno &&
n >= std::numeric_limits<int32_t>::min() &&
n <= std::numeric_limits<int32_t>::max();
}
bool ParseInt64(const std::string& str, int64_t *out)
{
if (!ParsePrechecks(str))
return false;
char *endp = nullptr;
errno = 0; // strtoll will not set errno if valid
long long int n = strtoll(str.c_str(), &endp, 10);
if(out) *out = (int64_t)n;
// Note that strtoll returns a *long long int*, so even if strtol doesn't report an over/underflow
// we still have to check that the returned value is within the range of an *int64_t*.
return endp && *endp == 0 && !errno &&
n >= std::numeric_limits<int64_t>::min() &&
n <= std::numeric_limits<int64_t>::max();
}
bool ParseUInt32(const std::string& str, uint32_t *out)
{
if (!ParsePrechecks(str))
return false;
if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoul accepts these by default if they fit in the range
return false;
char *endp = nullptr;
errno = 0; // strtoul will not set errno if valid
unsigned long int n = strtoul(str.c_str(), &endp, 10);
if(out) *out = (uint32_t)n;
// Note that strtoul returns a *unsigned long int*, so even if it doesn't report an over/underflow
// we still have to check that the returned value is within the range of an *uint32_t*. On 64-bit
// platforms the size of these types may be different.
return endp && *endp == 0 && !errno &&
n <= std::numeric_limits<uint32_t>::max();
}
bool ParseUInt64(const std::string& str, uint64_t *out)
{
if (!ParsePrechecks(str))
return false;
if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoull accepts these by default if they fit in the range
return false;
char *endp = nullptr;
errno = 0; // strtoull will not set errno if valid
unsigned long long int n = strtoull(str.c_str(), &endp, 10);
if(out) *out = (uint64_t)n;
// Note that strtoull returns a *unsigned long long int*, so even if it doesn't report an over/underflow
// we still have to check that the returned value is within the range of an *uint64_t*.
return endp && *endp == 0 && !errno &&
n <= std::numeric_limits<uint64_t>::max();
}
bool ParseDouble(const std::string& str, double *out)
{
if (!ParsePrechecks(str))
return false;
if (str.size() >= 2 && str[0] == '0' && str[1] == 'x') // No hexadecimal floats allowed
return false;
std::istringstream text(str);
text.imbue(std::locale::classic());
double result;
text >> result;
if(out) *out = result;
return text.eof() && !text.fail();
}
std::string FormatParagraph(const std::string& in, size_t width, size_t indent)
{
std::stringstream out;
size_t ptr = 0;
size_t indented = 0;
while (ptr < in.size())
{
size_t lineend = in.find_first_of('\n', ptr);
if (lineend == std::string::npos) {
lineend = in.size();
}
const size_t linelen = lineend - ptr;
const size_t rem_width = width - indented;
if (linelen <= rem_width) {
out << in.substr(ptr, linelen + 1);
ptr = lineend + 1;
indented = 0;
} else {
size_t finalspace = in.find_last_of(" \n", ptr + rem_width);
if (finalspace == std::string::npos || finalspace < ptr) {
// No place to break; just include the entire word and move on
finalspace = in.find_first_of("\n ", ptr);
if (finalspace == std::string::npos) {
// End of the string, just add it and break
out << in.substr(ptr);
break;
}
}
out << in.substr(ptr, finalspace - ptr) << "\n";
if (in[finalspace] == '\n') {
indented = 0;
} else if (indent) {
out << std::string(indent, ' ');
indented = indent;
}
ptr = finalspace + 1;
}
}
return out.str();
}
std::string i64tostr(int64_t n)
{
return strprintf("%d", n);
}
std::string itostr(int n)
{
return strprintf("%d", n);
}
int64_t atoi64(const char* psz)
{
#ifdef _MSC_VER
return _atoi64(psz);
#else
return strtoll(psz, nullptr, 10);
#endif
}
int64_t atoi64(const std::string& str)
{
#ifdef _MSC_VER
return _atoi64(str.c_str());
#else
return strtoll(str.c_str(), nullptr, 10);
#endif
}
int atoi(const std::string& str)
{
return atoi(str.c_str());
}
/** Upper bound for mantissa.
* 10^18-1 is the largest arbitrary decimal that will fit in a signed 64-bit integer.
* Larger integers cannot consist of arbitrary combinations of 0-9:
*
* 999999999999999999 1^18-1
* 9223372036854775807 (1<<63)-1 (max int64_t)
* 9999999999999999999 1^19-1 (would overflow)
*/
static const int64_t UPPER_BOUND = 1000000000000000000LL - 1LL;
/** Helper function for ParseFixedPoint */
static inline bool ProcessMantissaDigit(char ch, int64_t &mantissa, int &mantissa_tzeros)
{
if(ch == '0')
++mantissa_tzeros;
else {
for (int i=0; i<=mantissa_tzeros; ++i) {
if (mantissa > (UPPER_BOUND / 10LL))
return false; /* overflow */
mantissa *= 10;
}
mantissa += ch - '0';
mantissa_tzeros = 0;
}
return true;
}
bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out)
{
int64_t mantissa = 0;
int64_t exponent = 0;
int mantissa_tzeros = 0;
bool mantissa_sign = false;
bool exponent_sign = false;
int ptr = 0;
int end = val.size();
int point_ofs = 0;
if (ptr < end && val[ptr] == '-') {
mantissa_sign = true;
++ptr;
}
if (ptr < end)
{
if (val[ptr] == '0') {
/* pass single 0 */
++ptr;
} else if (val[ptr] >= '1' && val[ptr] <= '9') {
while (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') {
if (!ProcessMantissaDigit(val[ptr], mantissa, mantissa_tzeros))
return false; /* overflow */
++ptr;
}
} else return false; /* missing expected digit */
} else return false; /* empty string or loose '-' */
if (ptr < end && val[ptr] == '.')
{
++ptr;
if (ptr < end && val[ptr] >= '0' && val[ptr] <= '9')
{
while (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') {
if (!ProcessMantissaDigit(val[ptr], mantissa, mantissa_tzeros))
return false; /* overflow */
++ptr;
++point_ofs;
}
} else return false; /* missing expected digit */
}
if (ptr < end && (val[ptr] == 'e' || val[ptr] == 'E'))
{
++ptr;
if (ptr < end && val[ptr] == '+')
++ptr;
else if (ptr < end && val[ptr] == '-') {
exponent_sign = true;
++ptr;
}
if (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') {
while (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') {
if (exponent > (UPPER_BOUND / 10LL))
return false; /* overflow */
exponent = exponent * 10 + val[ptr] - '0';
++ptr;
}
} else return false; /* missing expected digit */
}
if (ptr != end)
return false; /* trailing garbage */
/* finalize exponent */
if (exponent_sign)
exponent = -exponent;
exponent = exponent - point_ofs + mantissa_tzeros;
/* finalize mantissa */
if (mantissa_sign)
mantissa = -mantissa;
/* convert to one 64-bit fixed-point value */
exponent += decimals;
if (exponent < 0)
return false; /* cannot represent values smaller than 10^-decimals */
if (exponent >= 18)
return false; /* cannot represent values larger than or equal to 10^(18-decimals) */
for (int i=0; i < exponent; ++i) {
if (mantissa > (UPPER_BOUND / 10LL) || mantissa < -(UPPER_BOUND / 10LL))
return false; /* overflow */
mantissa *= 10;
}
if (mantissa > UPPER_BOUND || mantissa < -UPPER_BOUND)
return false; /* overflow */
if (amount_out)
*amount_out = mantissa;
return true;
}
| [
"arinesau@gmail.com"
] | arinesau@gmail.com |
2f46e7d443385f15002c2da7e449317e4657d52b | 12e2e6e9b050f8916bf372ee725c9d1112d6c7ce | /Car/Core.cpp | 5b4fd1fc0d34c3d3c41f8a2932ec27870d39cf6b | [] | no_license | Sozary-zz/Car | 49f6796471f082231e33a87daf15405cd3d5635d | 520bea5519c8bf3b72e2ab13a372b164208c429a | refs/heads/master | 2022-04-30T22:06:36.717325 | 2017-09-27T11:45:20 | 2017-09-27T11:45:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,400 | cpp | #include "core.hpp"
#define GAME_FPS 60.f
#include <iostream>
using namespace std;
using namespace sf;
Core::Core(int w, int h, const string& title) :
m_window(VideoMode(w, h), title, Style::Close, ContextSettings{ 0,0,8 }), TimePerFrame(seconds(1.f / (float)GAME_FPS))
{
m_sim = new Simulation();
}
Core::~Core()
{
delete m_sim;
}
void Core::run()
{
Clock clock;
Time timeSinceLastUpdate;
timeSinceLastUpdate = Time::Zero;
while (m_window.isOpen())
{
processEvent(TimePerFrame);
timeSinceLastUpdate += clock.restart();
while (timeSinceLastUpdate > TimePerFrame)
{
timeSinceLastUpdate -= TimePerFrame;
processEvent(TimePerFrame);
update(TimePerFrame);
}
render();
}
}
void Core::processEvent(Time delta)
{
Event event;
while (m_window.pollEvent(event))
{
switch (event.type)
{
case Event::KeyReleased:
break;
case Event::KeyPressed:
switch (event.key.code)
{
case Keyboard::Left:
break;
case Keyboard::Up:
break;
case Keyboard::Right:
break;
case Keyboard::Escape:
m_window.close();
break;
}
break;
case Event::Closed:
m_window.close();
break;
}
}
}
void Core::update(Time deltaTime)
{
m_sim->update(deltaTime);
m_window.setTitle("Max fitness: " + to_string(m_sim->getMaxFitness()));
}
void Core::render()
{
m_window.clear();
m_window.draw(*m_sim);
m_window.display();
}
| [
"mehdiayache@hotmail.fr"
] | mehdiayache@hotmail.fr |
a2fc52808dc987e41536017958d230f54a3473cc | dbc0e3582d65bcf9d8fba29d872d6407454f9e28 | /HackerRank/game-of-stones.cpp | 4ff3386379bb41c664a0141f9ae92274bd2c0166 | [] | no_license | sirAdarsh/CP-files | 0b7430e2146620535451e0ab8959f70047bd7ea2 | 8d411224293fec547a3caa2708eed351c977ebed | refs/heads/master | 2023-04-05T09:07:21.554361 | 2021-04-08T19:57:33 | 2021-04-08T19:57:33 | 297,582,418 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | cpp | #include<iostream>
using namespace std;
string solve(int n){
if(n%7<=6 && n%7>=2){
return "First";
}
return "Second";
}
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
cout<<solve(n)<<endl;
}
}
| [
"aksinha.dhn@gmail.com"
] | aksinha.dhn@gmail.com |
9d219a15e70b6dd7e9bc9afbc6e83775b8241bdc | ba9322f7db02d797f6984298d892f74768193dcf | /r-kvstore/src/model/ModifyGuardDomainModeRequest.cc | 94827dd2bb9f4cef6a66bb45a3e77f159d937cff | [
"Apache-2.0"
] | permissive | sdk-team/aliyun-openapi-cpp-sdk | e27f91996b3bad9226c86f74475b5a1a91806861 | a27fc0000a2b061cd10df09cbe4fff9db4a7c707 | refs/heads/master | 2022-08-21T18:25:53.080066 | 2022-07-25T10:01:05 | 2022-07-25T10:01:05 | 183,356,893 | 3 | 0 | null | 2019-04-25T04:34:29 | 2019-04-25T04:34:28 | null | UTF-8 | C++ | false | false | 3,396 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/r-kvstore/model/ModifyGuardDomainModeRequest.h>
using AlibabaCloud::R_kvstore::Model::ModifyGuardDomainModeRequest;
ModifyGuardDomainModeRequest::ModifyGuardDomainModeRequest() :
RpcServiceRequest("r-kvstore", "2015-01-01", "ModifyGuardDomainMode")
{}
ModifyGuardDomainModeRequest::~ModifyGuardDomainModeRequest()
{}
std::string ModifyGuardDomainModeRequest::getDomainMode()const
{
return domainMode_;
}
void ModifyGuardDomainModeRequest::setDomainMode(const std::string& domainMode)
{
domainMode_ = domainMode;
setCoreParameter("DomainMode", domainMode);
}
long ModifyGuardDomainModeRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void ModifyGuardDomainModeRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setCoreParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
std::string ModifyGuardDomainModeRequest::getSecurityToken()const
{
return securityToken_;
}
void ModifyGuardDomainModeRequest::setSecurityToken(const std::string& securityToken)
{
securityToken_ = securityToken;
setCoreParameter("SecurityToken", securityToken);
}
std::string ModifyGuardDomainModeRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void ModifyGuardDomainModeRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setCoreParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
std::string ModifyGuardDomainModeRequest::getRegionId()const
{
return regionId_;
}
void ModifyGuardDomainModeRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setCoreParameter("RegionId", regionId);
}
std::string ModifyGuardDomainModeRequest::getOwnerAccount()const
{
return ownerAccount_;
}
void ModifyGuardDomainModeRequest::setOwnerAccount(const std::string& ownerAccount)
{
ownerAccount_ = ownerAccount;
setCoreParameter("OwnerAccount", ownerAccount);
}
std::string ModifyGuardDomainModeRequest::getReplicaId()const
{
return replicaId_;
}
void ModifyGuardDomainModeRequest::setReplicaId(const std::string& replicaId)
{
replicaId_ = replicaId;
setCoreParameter("ReplicaId", replicaId);
}
long ModifyGuardDomainModeRequest::getOwnerId()const
{
return ownerId_;
}
void ModifyGuardDomainModeRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setCoreParameter("OwnerId", std::to_string(ownerId));
}
std::string ModifyGuardDomainModeRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void ModifyGuardDomainModeRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setCoreParameter("AccessKeyId", accessKeyId);
}
| [
"haowei.yao@alibaba-inc.com"
] | haowei.yao@alibaba-inc.com |
d0f0b90d9b4006661d3a985b1a3e28ac6a7eb8f3 | 21ab9b42039e4559a738954680561925d531d9a6 | /pybind11/operators.h | 293d5abd29a9f99f8a2bb041bd9204ed8f4e3dc5 | [
"Apache-2.0"
] | permissive | renesugar/pph-cpp | 9f9db4ac2424873c8b79e911adb5c0dd5399e0c4 | 8df79ebf6b7c7b92af69eec3b7032eb53bbc25af | refs/heads/master | 2023-04-15T00:28:04.526648 | 2020-06-09T21:53:04 | 2020-06-09T21:53:04 | 104,619,261 | 3 | 0 | Apache-2.0 | 2021-04-20T20:08:24 | 2017-09-24T04:41:59 | C++ | UTF-8 | C++ | false | false | 9,049 | h | /*
pybind11/operator.h: Metatemplates for operator overloading
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
*/
#pragma once
#include "pybind11.h"
#if defined(__clang__) && !defined(__INTEL_COMPILER)
# pragma clang diagnostic ignored "-Wunsequenced" // multiple unsequenced modifications to 'self' (when using def(py::self OP Type()))
#elif defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
#endif
NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
NAMESPACE_BEGIN(detail)
/// Enumeration with all supported operator types
enum op_id : int {
op_add, op_sub, op_mul, op_div, op_mod, op_divmod, op_pow, op_lshift,
op_rshift, op_and, op_xor, op_or, op_neg, op_pos, op_abs, op_invert,
op_int, op_long, op_float, op_str, op_cmp, op_gt, op_ge, op_lt, op_le,
op_eq, op_ne, op_iadd, op_isub, op_imul, op_idiv, op_imod, op_ilshift,
op_irshift, op_iand, op_ixor, op_ior, op_complex, op_bool, op_nonzero,
op_repr, op_truediv, op_itruediv, op_hash
};
enum op_type : int {
op_l, /* base type on left */
op_r, /* base type on right */
op_u /* unary operator */
};
struct self_t { };
static const self_t self = self_t();
/// Type for an unused type slot
struct undefined_t { };
/// Don't warn about an unused variable
inline self_t __self() { return self; }
/// base template of operator implementations
template <op_id, op_type, typename B, typename L, typename R> struct op_impl { };
/// Operator implementation generator
template <op_id id, op_type ot, typename L, typename R> struct op_ {
template <typename Class, typename... Extra> void execute(Class &cl, const Extra&... extra) const {
using Base = typename Class::type;
using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>;
using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>;
using op = op_impl<id, ot, Base, L_type, R_type>;
cl.def(op::name(), &op::execute, is_operator(), extra...);
#if PY_MAJOR_VERSION < 3
if (id == op_truediv || id == op_itruediv)
cl.def(id == op_itruediv ? "__idiv__" : ot == op_l ? "__div__" : "__rdiv__",
&op::execute, is_operator(), extra...);
#endif
}
template <typename Class, typename... Extra> void execute_cast(Class &cl, const Extra&... extra) const {
using Base = typename Class::type;
using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>;
using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>;
using op = op_impl<id, ot, Base, L_type, R_type>;
cl.def(op::name(), &op::execute_cast, is_operator(), extra...);
#if PY_MAJOR_VERSION < 3
if (id == op_truediv || id == op_itruediv)
cl.def(id == op_itruediv ? "__idiv__" : ot == op_l ? "__div__" : "__rdiv__",
&op::execute, is_operator(), extra...);
#endif
}
};
#define PYBIND11_BINARY_OPERATOR(id, rid, op, expr) \
template <typename B, typename L, typename R> struct op_impl<op_##id, op_l, B, L, R> { \
static char const* name() { return "__" #id "__"; } \
static auto execute(const L &l, const R &r) -> decltype(expr) { return (expr); } \
static B execute_cast(const L &l, const R &r) { return B(expr); } \
}; \
template <typename B, typename L, typename R> struct op_impl<op_##id, op_r, B, L, R> { \
static char const* name() { return "__" #rid "__"; } \
static auto execute(const R &r, const L &l) -> decltype(expr) { return (expr); } \
static B execute_cast(const R &r, const L &l) { return B(expr); } \
}; \
inline op_<op_##id, op_l, self_t, self_t> op(const self_t &, const self_t &) { \
return op_<op_##id, op_l, self_t, self_t>(); \
} \
template <typename T> op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \
return op_<op_##id, op_l, self_t, T>(); \
} \
template <typename T> op_<op_##id, op_r, T, self_t> op(const T &, const self_t &) { \
return op_<op_##id, op_r, T, self_t>(); \
}
#define PYBIND11_INPLACE_OPERATOR(id, op, expr) \
template <typename B, typename L, typename R> struct op_impl<op_##id, op_l, B, L, R> { \
static char const* name() { return "__" #id "__"; } \
static auto execute(L &l, const R &r) -> decltype(expr) { return expr; } \
static B execute_cast(L &l, const R &r) { return B(expr); } \
}; \
template <typename T> op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \
return op_<op_##id, op_l, self_t, T>(); \
}
#define PYBIND11_UNARY_OPERATOR(id, op, expr) \
template <typename B, typename L> struct op_impl<op_##id, op_u, B, L, undefined_t> { \
static char const* name() { return "__" #id "__"; } \
static auto execute(const L &l) -> decltype(expr) { return expr; } \
static B execute_cast(const L &l) { return B(expr); } \
}; \
inline op_<op_##id, op_u, self_t, undefined_t> op(const self_t &) { \
return op_<op_##id, op_u, self_t, undefined_t>(); \
}
PYBIND11_BINARY_OPERATOR(sub, rsub, operator-, l - r)
PYBIND11_BINARY_OPERATOR(add, radd, operator+, l + r)
PYBIND11_BINARY_OPERATOR(mul, rmul, operator*, l * r)
PYBIND11_BINARY_OPERATOR(truediv, rtruediv, operator/, l / r)
PYBIND11_BINARY_OPERATOR(mod, rmod, operator%, l % r)
PYBIND11_BINARY_OPERATOR(lshift, rlshift, operator<<, l << r)
PYBIND11_BINARY_OPERATOR(rshift, rrshift, operator>>, l >> r)
PYBIND11_BINARY_OPERATOR(and, rand, operator&, l & r)
PYBIND11_BINARY_OPERATOR(xor, rxor, operator^, l ^ r)
PYBIND11_BINARY_OPERATOR(eq, eq, operator==, l == r)
PYBIND11_BINARY_OPERATOR(ne, ne, operator!=, l != r)
PYBIND11_BINARY_OPERATOR(or, ror, operator|, l | r)
PYBIND11_BINARY_OPERATOR(gt, lt, operator>, l > r)
PYBIND11_BINARY_OPERATOR(ge, le, operator>=, l >= r)
PYBIND11_BINARY_OPERATOR(lt, gt, operator<, l < r)
PYBIND11_BINARY_OPERATOR(le, ge, operator<=, l <= r)
//PYBIND11_BINARY_OPERATOR(pow, rpow, pow, std::pow(l, r))
PYBIND11_INPLACE_OPERATOR(iadd, operator+=, l += r)
PYBIND11_INPLACE_OPERATOR(isub, operator-=, l -= r)
PYBIND11_INPLACE_OPERATOR(imul, operator*=, l *= r)
PYBIND11_INPLACE_OPERATOR(itruediv, operator/=, l /= r)
PYBIND11_INPLACE_OPERATOR(imod, operator%=, l %= r)
PYBIND11_INPLACE_OPERATOR(ilshift, operator<<=, l <<= r)
PYBIND11_INPLACE_OPERATOR(irshift, operator>>=, l >>= r)
PYBIND11_INPLACE_OPERATOR(iand, operator&=, l &= r)
PYBIND11_INPLACE_OPERATOR(ixor, operator^=, l ^= r)
PYBIND11_INPLACE_OPERATOR(ior, operator|=, l |= r)
PYBIND11_UNARY_OPERATOR(neg, operator-, -l)
PYBIND11_UNARY_OPERATOR(pos, operator+, +l)
// WARNING: This usage of `abs` should only be done for existing STL overloads.
// Adding overloads directly in to the `std::` namespace is advised against:
// https://en.cppreference.com/w/cpp/language/extending_std
PYBIND11_UNARY_OPERATOR(abs, abs, std::abs(l))
PYBIND11_UNARY_OPERATOR(hash, hash, std::hash<L>()(l))
PYBIND11_UNARY_OPERATOR(invert, operator~, (~l))
PYBIND11_UNARY_OPERATOR(bool, operator!, !!l)
PYBIND11_UNARY_OPERATOR(int, int_, (int) l)
PYBIND11_UNARY_OPERATOR(float, float_, (double) l)
#undef PYBIND11_BINARY_OPERATOR
#undef PYBIND11_INPLACE_OPERATOR
#undef PYBIND11_UNARY_OPERATOR
NAMESPACE_END(detail)
using detail::self;
// Add named operators so that they are accessible via `py::`.
using detail::hash;
NAMESPACE_END(PYBIND11_NAMESPACE)
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
| [
"rene.sugar@gmail.com"
] | rene.sugar@gmail.com |
154834e44163a88ef84289d2b6ced4b3bede1f51 | d7f3d311f9b50740d422678134df3cf171fd95de | /Player.h | 5fc5e3e970637e7b373ee8ccc76b972fdede70cd | [] | no_license | jagdinsky/labirinth_game | 0b0a774232464596143c68106de6d3b7859f1251 | 612dd4993ae7246158b23bf1e84b89c969a0a57a | refs/heads/master | 2023-04-10T02:14:59.799590 | 2021-04-09T19:35:06 | 2021-04-09T19:35:06 | 356,369,320 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 905 | h | #ifndef MAIN_PLAYER_H
#define MAIN_PLAYER_H
#include "Image.h"
struct Point {
int x;
int y;
};
enum class MovementDir {
UP,
DOWN,
LEFT,
RIGHT
};
struct Player {
explicit Player(Point pos = {.x = 400, .y = 400}) : coords(pos),
old_coords(coords) {
};
bool Moved() const;
void ProcessInput(MovementDir dir, char room_buff[25][25], char *curr_room_ch, bool *trap_activated,
bool *win, bool *lose);
void Draw(Image &screen, Image& background, Image& player);
void changePos(char *curr_room_ch);
void ctimeInc(float delta);
private:
float ctime = 0;
Point coords {.x = 10, .y = 10};
Point old_coords {.x = 10, .y = 10};
Pixel color {.r = 255, .g = 255, .b = 0, .a = 255};
int move_speed = 1;
};
#endif //MAIN_PLAYER_H
| [
"jagdinsky@gmail.com"
] | jagdinsky@gmail.com |
77b4ff4fcda9d342922628dc69fa158589930e33 | 464c01e2298eea56e4c78f1c30f65492090b02f3 | /MP3/NachOS-4.0_MP3/code/threads/scheduler.cc | aa68cab86316ca6191fcc129e005afaa11077456 | [
"MIT-Modern-Variant"
] | permissive | lijunhaoabroad/Operating-System-Project-NachOS | bff820b68005550aa55796f2ae4946f7176506bc | 7ccbb19354de953c6f504408ffbe1489c2f5319c | refs/heads/master | 2023-02-22T06:11:12.339265 | 2021-01-23T07:51:56 | 2021-01-23T07:51:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,379 | cc | // scheduler.cc
// Routines to choose the next thread to run, and to dispatch to
// that thread.
//
// These routines assume that interrupts are already disabled.
// If interrupts are disabled, we can assume mutual exclusion
// (since we are on a uniprocessor).
//
// NOTE: We can't use Locks to provide mutual exclusion here, since
// if we needed to wait for a lock, and the lock was busy, we would
// end up calling FindNextToRun(), and that would put us in an
// infinite loop.
//
// Very simple implementation -- no priorities, straight FIFO.
// Might need to be improved in later assignments.
//
// Copyright (c) 1992-1996 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#include "copyright.h"
#include "debug.h"
#include "scheduler.h"
#include "main.h"
//----------------------------------------------------------------------
// Scheduler::Scheduler
// Initialize the list of ready but not running threads.
// Initially, no ready threads.
//----------------------------------------------------------------------
/////////////// 12/12 Added ////////////////////
//----------------------------------------------------------------------
// SchedulingCompare
// Compare to thread's priority and put them in decreasing order.
// First thread should have the highest priority (149)
//----------------------------------------------------------------------
// #define LIST_QUEUE_CONTENTS
// #define DEBUG_QUEUES
// #define DEBUG_PREEMPT
// #define DEBUG_AGING
static int
L1SchedulingCompare (Thread *x, Thread *y)
{
if (x->approx_bursttime < y->approx_bursttime) { return -1; }
else if (x->approx_bursttime > y->approx_bursttime) { return 1; }
else { return 0; }
}
static int
L2SchedulingCompare (Thread *x, Thread *y)
{
if (x->priority < y->priority) { return 1; }
else if (x->priority > y->priority) { return -1; }
else { return 0; }
}
Scheduler::Scheduler()
{
readyList = new List<Thread *>;
toBeDestroyed = NULL;
//////// 12/10 Added ////////
L1List = new SortedList<Thread*>(L1SchedulingCompare);
L2List = new SortedList<Thread*>(L2SchedulingCompare);
// L1List = new List<Thread *>;
// L2List = new List<Thread *>;
L3List = new List<Thread *>; // Just insert, no need to sort!
}
//----------------------------------------------------------------------
// Scheduler::~Scheduler
// De-allocate the list of ready threads.
//----------------------------------------------------------------------
Scheduler::~Scheduler()
{
delete readyList;
delete L1List;
delete L2List;
delete L3List;
}
//----------------------------------------------------------------------
// Scheduler::ReadyToRun
// Mark a thread as ready, but not running.
// Put it on the ready list, for later scheduling onto the CPU.
//
// "thread" is the thread to be put on the ready list.
//----------------------------------------------------------------------
void
Scheduler::ReadyToRun (Thread *thread)
{
ASSERT(kernel->interrupt->getLevel() == IntOff);
DEBUG(dbgThread, "Putting thread on ready list: " << thread->getName());
//cout << "Putting thread on ready list: " << thread->getName() << endl ;
thread->setStatus(READY);
readyList->Append(thread);
}
////////////////// 12/12 ////////////////////////
//----------------------------------------------------------------------
// Scheduler::AddThreadPriority => NO USE!
// For aging mechanism, add priority by 10 to each thread
// Error here. access Item() on NULL list.
// ----------------------------------------------------------------------
void
Scheduler::AddThreadPriority(){
// Thread* first = L1List->first;
ListIterator<Thread*> *iter;
iter = new ListIterator<Thread*>(L1List);
if(!L1List->IsEmpty()){
for (; !iter->IsDone(); iter->Next()) {
// Operation on iter->Item()
// TODO : should prevent >149 case. in DEBUG
if(iter->Item()->priority+10>=149){
DEBUG(dbgZ, "[C] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<iter->Item()->ID<<"} ] changes its priority from [ {"<<iter->Item()->priority<<"} ] to [ {149} ]");
}else{
DEBUG(dbgZ, "[C] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<iter->Item()->ID<<"} ] changes its priority from [ {"<<iter->Item()->priority<<"} ] to [ {"<<iter->Item()->priority+10 <<"} ]");
}
if(iter->Item()->priority +10 <= 149)
iter->Item()->priority += 10;
else iter->Item()->priority = 149;
// first = first->next;
}
}
ListIterator<Thread*> *iter2;
iter2 = new ListIterator<Thread*>(L2List);
if(!L2List->IsEmpty()){
for (; !iter2->IsDone(); iter2->Next()) {
// Operation on iter->Item()
DEBUG(dbgZ, "[C] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<iter2->Item()->ID<<"} ] changes its priority from [ {"<<iter2->Item()->priority<<"} ] to [ {"<<iter2->Item()->priority+10 <<"} ]");
if(iter2->Item()->priority +10 <= 149)
iter2->Item()->priority += 10;
else iter2->Item()->priority = 149;
// first = first->next;
}
}
ListIterator<Thread*> *iter3;
iter3 = new ListIterator<Thread*>(L3List);
if(!L3List->IsEmpty()){
for (; !iter3->IsDone(); iter3->Next()) {
// Operation on iter->Item()
DEBUG(dbgZ, "[C] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<iter3->Item()->ID<<"} ] changes its priority from [ {"<<iter3->Item()->priority<<"} ] to [ {"<<iter3->Item()->priority+10 <<"} ]");
if(iter3->Item()->priority +10 <= 149)
iter3->Item()->priority += 10;
else iter3->Item()->priority = 149;
// first = first->next;
}
}
}
//----------------------------------------------------------------------
// Scheduler::ReArrangeThreads
// For aging mechanism, since a thread(process) might migrate from lower
// level queue to higher level queue due to the increase of its priority,
// the scheduler should re-arrange the queue each thread belongs to.
// Check_Preempt here!
// ----------------------------------------------------------------------
void
Scheduler::ReArrangeThreads(){
Thread* migrate_thread;
// First, check L3List
ListIterator<Thread*> *iter3;
iter3 = new ListIterator<Thread*>(L3List);
// Note: We cannot use this method on L3, since L3 is NOT a SortedList!
// We should just Re-Insert every thread in L3!
for (; !iter3->IsDone(); iter3->Next()) {
// Operation on iter->Item()
migrate_thread = L3List->RemoveFront();
// This case is NOT possible!
if(migrate_thread->priority>=100){
// Insert into L1
DEBUG(dbgZ, "[B] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<migrate_thread->ID<<"} ] is removed from queue L[ {3} ]");
L1List->Insert(migrate_thread);
DEBUG(dbgZ, "[A] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<migrate_thread->ID<<"} ] is inserted into queue L[ {1} ]");
this->Check_Preempt(migrate_thread);
}
else if(migrate_thread->priority >= 50){
// Insert into L2
DEBUG(dbgZ, "[B] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<migrate_thread->ID<<"} ] is removed from queue L[ {3} ]");
L2List->Insert(migrate_thread);
DEBUG(dbgZ, "[A] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<migrate_thread->ID<<"} ] is inserted into queue L[ {2} ]");
this->Check_Preempt(migrate_thread);
}else{
// Insert Back.
DEBUG(dbgZ, "[B] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<migrate_thread->ID<<"} ] is removed from queue L[ {3} ]");
L3List->Append(migrate_thread);
DEBUG(dbgZ, "[B] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<migrate_thread->ID<<"} ] is inserted into queue L[ {3} ]");
// Don't need to check preempt!
}
}
// Then, check L2List
ListIterator<Thread*> *iter2;
iter2 = new ListIterator<Thread*>(L2List);
for (; !iter2->IsDone(); iter2->Next()) {
// Operation on iter->Item()
if(iter2->Item()->priority >=100){
// should move to L1list
migrate_thread = L2List->RemoveFront();
DEBUG(dbgZ, "[B] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<migrate_thread->ID<<"} ] is removed from queue L[ {2} ]");
L1List->Insert(migrate_thread);
DEBUG(dbgZ, "[A] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<migrate_thread->ID<<"} ] is inserted into queue L[ {1} ]");
this->Check_Preempt(migrate_thread);
}
}
}
///////////////////////// 12/12 Updated ///////////////////////////////
//----------------------------------------------------------------------
// Scheduler::Scheduling
// When a thread is added to multi-level feedback queue,
// (Come back from WAITING state or from NEW state)
// The scheduler should schedule which thread can take
// over CPU and be executed.
//
// Three scenario where Scheduling() would be called:
// (1) Thread::Fork() (NEW -> READY)
// (2) Semaphore::V() (WAIT -> READY)
// (3) Thread::Yield() (RUNNING -> READY) // This one I am not sure!
//
//
// 12/13 TODO :
// Originally, we will call ReadyToRun to add threads(proc) into ready-queue (readyList)
// Now, we change them to AddToQueue(thread)
//
// For scheduler->Run(nextThread, finishing)
// We change to scheduler->Scheduling(finishing)
//
//
// For 'aging' mechanism, in every 'yieldOnReturn' from timer interrupt,
// we 'update' the priority of all threads?
//
// For each thread, when they call Sleep(FALSE): update their burst time.
// When they are switching back to CPU : resume accumulating T. (ticks)
//
//----------------------------------------------------------------------
// TODO(1) : Add a scheduling function when a threads is add to ready-queue.(readyList)
// i.e. : When someone calls "kernel->scheduler->ReadyToRun(this)".
// Add to L1List/ L2List / L3List according to its priority (aging).
// TODO : should change the last " accumulated total ticks"
// void
// Scheduler::Scheduling(bool finishing){
// Return the thread to be executed.
Thread*
Scheduler::Scheduling(){
Thread* nextThread;
#ifdef DEBUG_QUEUES
cout<<"\nSb. calls scheduling, current Thread in Running state (holds CPU): "<<kernel->currentThread->getName()<<"\n";
this->List_All_thread();
// cout<< kernel->synchConsoleOut->waitFor->queue->NumInList();
// cout<<"WAIT queue: "<<kernel->synchConsoleOut->waitFor->queue->NumInList() <<" threads\n";
#endif
if(!L1List->IsEmpty()){
// Pick a thread from L1List.
// SFJ
// if(L1List->Front()->priority < kernel->currentThread->priority) return;
nextThread = L1List->RemoveFront();
// cout<<"now t"<<kernel->currentThread->getID()<<", to t"<<nextThread->getID()<<"\n";
nextThread->record_start_ticks(kernel->stats->totalTicks);
DEBUG(dbgZ, "[B] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<nextThread->ID<<"} ] is removed from queue L[ {1} ]");
DEBUG(dbgZ, "[E] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<nextThread->ID<<"} ] is now selected for execution, thread [ {"<<kernel->currentThread->ID<<"} ] is replaced, and it has executed [ {"<<kernel->stats->totalTicks - kernel->currentThread->cpu_start_ticks<<"} ] ticks ");
#ifdef DEBUG_QUEUES
cout<<"Pick: "<<nextThread->getName()<<"\n";
#endif
return nextThread;
// this->Run(nextThread, finishing);
// nextThread->record_start_ticks(kernel->stats->totalTicks);
}
else{
if(!L2List->IsEmpty()){
// if(kernel->currentThread->InWhichQueue()==1) return;// L2 Cannot preempt it.
// Pick a thread from L2List.
nextThread = L2List->RemoveFront();
nextThread->record_start_ticks(kernel->stats->totalTicks);
// cout<<"now t"<<kernel->currentThread->getID()<<", to t"<<nextThread->getID()<<"\n";
DEBUG(dbgZ, "[B] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<nextThread->ID<<"} ] is removed from queue L[ {2} ]");
DEBUG(dbgZ, "[E] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<nextThread->ID<<"} ] is now selected for execution, thread [ {"<<kernel->currentThread->ID<<"} ] is replaced, and it has executed [ {"<<kernel->stats->totalTicks - kernel->currentThread->cpu_start_ticks<<"} ] ticks ");
#ifdef DEBUG_QUEUES
cout<<"Pick: "<<nextThread->getName()<<"\n";
#endif
// this->Run(nextThread, finishing);
return nextThread;
// nextThread->record_start_ticks(kernel->stats->totalTicks);
}
else{
// Pick a thread from L3List.
// Round-Robin
// Run(,FALSE);
// TODO : should change the last " accumulated total ticks"
// if(kernel->currentThread->InWhichQueue()==1 || kernel->currentThread->InWhichQueue()==2) return;
if( !L3List->IsEmpty()){
nextThread = L3List->RemoveFront();
// cout<<"now t"<<kernel->currentThread->getID()<<", to t"<<nextThread->getID()<<"\n";
nextThread->record_start_ticks(kernel->stats->totalTicks);
DEBUG(dbgZ, "[B] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<nextThread->ID<<"} ] is removed from queue L[ {3} ]");
DEBUG(dbgZ, "[E] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<nextThread->ID<<"} ] is now selected for execution, thread [ {"<<kernel->currentThread->ID<<"} ] is replaced, and it has executed [ {"<<kernel->stats->totalTicks - kernel->currentThread->cpu_start_ticks<<"} ] ticks ");
#ifdef DEBUG_QUEUES
cout<<"Pick: "<<nextThread->getName()<<"\n";
#endif
return nextThread;
// this->Run(nextThread, finishing);
}
else{
// cout<<"Error! NULL threads in ready-queue\n";
return NULL;
}
}
}
}
//----------------------------------------------------------------------
// Scheduler::AddToQueue
// Add a thread into L1/L2/L3 queue according to its priority.
//----------------------------------------------------------------------
// TODO(2) : Add a function similar to "ReadyToRun" but with
// arguments: 1. Thread* 2. Its Priority to decide
// which level queue it should be added. (L1, L2, L3)
void
Scheduler::Check_Preempt(Thread* thread){
// cout<<kernel->currentThread->getName()<<"\n";
// Check for Preemption
//========== From RUNNING to READY state ===================//
#ifdef DEBUG_PREEMPT
cout<<"Check Preempt: Cur t: "<<kernel->currentThread->getName()<<" Add t: "<<thread->getName()<<"\n";
#endif
// Case 1: Running L3 but L1 or L2 has threads.
if( kernel->currentThread->InWhichQueue()==3 && (thread->InWhichQueue()==2||thread->InWhichQueue()==1)){
#ifdef DEBUG_PREEMPT
cout<<"\nShould Preempt!\n";
cout<<"cur priority: "<< kernel->currentThread->priority <<"in queue: "<<kernel->currentThread->InWhichQueue()<<"\n";
cout<<"Add priority: "<< thread->priority<<" belongs to queue " <<thread->InWhichQueue()<<"\n";
#endif
kernel->currentThread->True_ticks += kernel->stats->totalTicks - kernel->currentThread->cpu_start_ticks;
#ifdef DEBUG_PREEMPT
cout<<"Current ready-queue contents:\n";
this->List_All_thread();
#endif
Thread* nextThread = this->Scheduling(); // Should retun L1 thread.
#ifdef DEBUG_PREEMPT
cout<<"Thus, pick "<<nextThread->getName()<<"\n";
#endif
this->AddToQueue(kernel->currentThread, kernel->currentThread->priority); // from RUNNING to READY state.
this->Run(nextThread, FALSE);
}
// Case 2: Running L2 but L1 has threads.
else if (kernel->currentThread->InWhichQueue()==2 && thread->InWhichQueue()==1) {
#ifdef DEBUG_PREEMPT
cout<<"\nShould Preempt!\n";
cout<<"cur priority: "<< kernel->currentThread->priority <<"in queue: "<<kernel->currentThread->InWhichQueue()<<"\n";
cout<<"Add priority: "<< thread->priority<<" belongs to queue " <<thread->InWhichQueue()<<"\n";
#endif
kernel->currentThread->True_ticks += kernel->stats->totalTicks - kernel->currentThread->cpu_start_ticks;
#ifdef DEBUG_PREEMPT
cout<<"Current ready-queue contents:\n";
this->List_All_thread();
#endif
Thread* nextThread = this->Scheduling(); // Should retun L1 thread.
#ifdef DEBUG_PREEMPT
cout<<"Thus, pick "<<nextThread->getName()<<"\n";
#endif
// cout<<"\n";
this->AddToQueue(kernel->currentThread, kernel->currentThread->priority); // from RUNNING to READY state.
this->Run(nextThread, FALSE);
}
// Case 3: Running L1 but the thread to be added has
// higher priority (smaller approx_bursttime)
else if (kernel->currentThread->InWhichQueue()==1 && (thread->approx_bursttime < kernel->currentThread->approx_bursttime &&thread->InWhichQueue()==1) ) {
#ifdef DEBUG_PREEMPT
cout<<"\nShould Preempt!\n";
cout<<"cur bursttime: "<< kernel->currentThread->approx_bursttime <<"in queue: "<<kernel->currentThread->InWhichQueue()<<"\n";
cout<<"Add bursstime: "<< thread->approx_bursttime<<" belongs to queue " <<thread->InWhichQueue()<<"\n";
#endif
kernel->currentThread->True_ticks += kernel->stats->totalTicks - kernel->currentThread->cpu_start_ticks;
#ifdef DEBUG_PREEMPT
cout<<"Current ready-queue contents:\n";
this->List_All_thread();
#endif
Thread* nextThread = this->Scheduling(); // Should retun L1 thread.
#ifdef DEBUG_PREEMPT
cout<<"Thus, pick "<<nextThread->getName()<<"\n";
#endif
// cout<<"\n";
this->AddToQueue(kernel->currentThread, kernel->currentThread->priority); // from RUNNING to READY state.
this->Run(nextThread, FALSE);
}
}
// Don't check preempt.
void
Scheduler::AddToQueue2(Thread* thread, int Priority){
// DEBUG(dbgZ, "[A] Tick [ {%d} ]: Thread [ {%d} ] is inserted into queueL[ {L1} ]");
cout<<"AddToQueue2: ";
if(Priority>=100){
// Add to L1 list.
// L1List->Append(thread);
thread->setStatus(READY);
DEBUG(dbgZ, "[A] Tick [ {"<< kernel->stats->totalTicks<<"} ]: Thread [ {"<<thread->ID<<"} ] is inserted into queueL[ {1} ]" );
L1List->Insert(thread);
// DEBUG(dbgZ, "[A] Tick [ {"<< kernel->stats->totalTicks<<"} ]: Thread [ {"<<thread->ID<<"} ] is inserted into queueL[ {1} ]" );
}
else if(Priority >=50){
// L2List->Append(thread);
thread->setStatus(READY);
DEBUG(dbgZ, "[A] Tick [ {"<< kernel->stats->totalTicks<<"} ]: Thread [ {"<<thread->ID<<"} ] is inserted into queueL[ {2} ]" );
L2List->Insert(thread);
// DEBUG(dbgZ, "[A] Tick [ {"<< kernel->stats->totalTicks<<"} ]: Thread [ {"<<thread->ID<<"} ] is inserted into queueL[ {2} ]" );
}
else{
thread->setStatus(READY);
DEBUG(dbgZ, "[A] Tick [ {"<< kernel->stats->totalTicks<<"} ]: Thread [ {"<<thread->ID<<"} ] is inserted into queueL[ {3} ]" );
#ifdef DEBUG_QUEUES
if(!L3List->IsEmpty()){
cout<<"Before: ";
this->List_All_thread();
}
#endif
L3List->Append(thread);
#ifdef DEBUG_QUEUES
if(!L3List->IsEmpty()){
cout<<"After: ";
this->List_All_thread();
}
#endif
// DEBUG(dbgZ, "[A] Tick [ {"<< kernel->stats->totalTicks<<"} ]: Thread [ {"<<thread->ID<<"} ] is inserted into queueL[ {3} ]" );
}
}
void
Scheduler::AddToQueue(Thread* thread, int Priority){
// DEBUG(dbgZ, "[A] Tick [ {%d} ]: Thread [ {%d} ] is inserted into queueL[ {L1} ]");
// set START WAIT time in the ready-queue
thread->set_wait_starttime(kernel->stats->totalTicks); // update reference point.
if(Priority>=100){
// Add to L1 list.
// L1List->Append(thread);
thread->setStatus(READY);
DEBUG(dbgZ, "[A] Tick [ {"<< kernel->stats->totalTicks<<"} ]: Thread [ {"<<thread->ID<<"} ] is inserted into queueL[ {1} ]" );
L1List->Insert(thread);
// DEBUG(dbgZ, "[A] Tick [ {"<< kernel->stats->totalTicks<<"} ]: Thread [ {"<<thread->ID<<"} ] is inserted into queueL[ {1} ]" );
}
else if(Priority >=50){
// L2List->Append(thread);
thread->setStatus(READY);
DEBUG(dbgZ, "[A] Tick [ {"<< kernel->stats->totalTicks<<"} ]: Thread [ {"<<thread->ID<<"} ] is inserted into queueL[ {2} ]" );
L2List->Insert(thread);
// DEBUG(dbgZ, "[A] Tick [ {"<< kernel->stats->totalTicks<<"} ]: Thread [ {"<<thread->ID<<"} ] is inserted into queueL[ {2} ]" );
}
else{
thread->setStatus(READY);
DEBUG(dbgZ, "[A] Tick [ {"<< kernel->stats->totalTicks<<"} ]: Thread [ {"<<thread->ID<<"} ] is inserted into queueL[ {3} ]" );
#ifdef DEBUG_QUEUES
if(!L3List->IsEmpty()){
cout<<"Before: ";
this->List_All_thread();
}
#endif
L3List->Append(thread);
#ifdef DEBUG_QUEUES
if(!L3List->IsEmpty()){
cout<<"After: ";
this->List_All_thread();
}
#endif
// DEBUG(dbgZ, "[A] Tick [ {"<< kernel->stats->totalTicks<<"} ]: Thread [ {"<<thread->ID<<"} ] is inserted into queueL[ {3} ]" );
}
}
// #ifdef DEBUG_QUEUE
// cout<<"AddToQueue: After Add: "<<thread->getName() <<"\n";
// this->List_All_thread();
// #endif
// if(kernel->currentThread->getID()!=0){
// kernel->scheduler->Check_Preempt(thread);
// }
//----------------------------------------------------------------------
// Scheduler::FindNextToRun
// Return the next thread to be scheduled onto the CPU.
// If there are no ready threads, return NULL.
// Side effect:
// Thread is removed from the ready list.
//----------------------------------------------------------------------
Thread *
Scheduler::FindNextToRun ()
{
ASSERT(kernel->interrupt->getLevel() == IntOff);
if (readyList->IsEmpty()) {
return NULL;
} else {
return readyList->RemoveFront();
}
}
Thread*
Scheduler::FindNextToRun2(){
ASSERT(kernel->interrupt->getLevel() == IntOff);
if( ! L1List->IsEmpty()){
return L1List->RemoveFront();
}
else{
if(!L2List->IsEmpty()){
return L2List->RemoveFront();
}
else{
if(!L3List->IsEmpty()){
return L3List->RemoveFront();
}
else return NULL;
}
}
}
/// 12/19 ///
//----------------------------------------------------------------------
// Scheduler::Aging
// Iterate through all threads in multi-level ready-queues
// And check whether to add priorities to each READY thread.
//
//----------------------------------------------------------------------
void
Scheduler::Aging(){
Thread* thread;
int totalTicks = kernel->stats->totalTicks;
// L1 queue : note MAX 149
if(!L1List->IsEmpty()){
ListIterator<Thread*> *iter;
iter = new ListIterator<Thread*>(L1List);
for (; !iter->IsDone(); iter->Next()) {
thread = iter->Item();
// thread->accu_wait_ticks += 100;
thread->accu_wait_ticks += totalTicks - thread->start_wait_ticks;
thread->start_wait_ticks = totalTicks; // update reference point.
#ifdef DEBUG_AGING
cout<<"Ticks: "<<totalTicks<<", thread "<<thread->getID()<<"wait tick: "<<thread->accu_wait_ticks<<"\n";
#endif
if(thread->accu_wait_ticks >= 1500){
if(thread->priority+10>=149){
DEBUG(dbgZ, "[C] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<iter->Item()->ID<<"} ] changes its priority from [ {"<<iter->Item()->priority<<"} ] to [ {149} ]");
thread->priority = 149;
}
else{
DEBUG(dbgZ, "[C] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<iter->Item()->ID<<"} ] changes its priority from [ {"<<iter->Item()->priority<<"} ] to [ {"<<iter->Item()->priority+10 <<"} ]");
thread->priority += 10;
}
// reset wait ticks.
// thread->accu_wait_ticks = 0;
thread->accu_wait_ticks -= 1500; // Should NOT reset!
}
}
}
// L2
if(!L2List->IsEmpty()){
ListIterator<Thread*> *iter;
iter = new ListIterator<Thread*>(L2List);
for (; !iter->IsDone(); iter->Next()) {
thread = iter->Item();
// thread->accu_wait_ticks += 100;
thread->accu_wait_ticks += totalTicks - thread->start_wait_ticks;
thread->start_wait_ticks = totalTicks; // update reference point.
#ifdef DEBUG_AGING
cout<<"Ticks: "<<totalTicks<<", thread "<<thread->getID()<<"wait tick: "<<thread->accu_wait_ticks<<"\n";
#endif
// thread->accu_wait_ticks = totalTicks - thread->start_wait_ticks;
if(thread->accu_wait_ticks >= 1500){
// Print DEBUG message.
DEBUG(dbgZ, "[C] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<iter->Item()->ID<<"} ] changes its priority from [ {"<<iter->Item()->priority<<"} ] to [ {"<<iter->Item()->priority+10 <<"} ]");
thread->priority += 10;
// reset wait ticks.
// thread->set_wait_starttime(totalTicks);
// thread->accu_wait_ticks = 0;
thread->accu_wait_ticks -= 1500; // Should NOT reset!
}
}
}
// L3 queue
if(!L3List->IsEmpty()){
ListIterator<Thread*> *iter;
iter = new ListIterator<Thread*>(L3List);
for (; !iter->IsDone(); iter->Next()) {
thread = iter->Item();
// thread->accu_wait_ticks += 100;
thread->accu_wait_ticks += totalTicks - thread->start_wait_ticks;
thread->start_wait_ticks = totalTicks; // update reference point.
#ifdef DEBUG_AGING
cout<<"Ticks: "<<totalTicks<<", thread "<<thread->getID()<<"wait tick: "<<thread->accu_wait_ticks<<"\n";
#endif
// thread->accu_wait_ticks = totalTicks - thread->start_wait_ticks;
if(thread->accu_wait_ticks >= 1500){
DEBUG(dbgZ, "[C] Tick [ {"<<kernel->stats->totalTicks<<"} ]: Thread [ {"<<iter->Item()->ID<<"} ] changes its priority from [ {"<<iter->Item()->priority<<"} ] to [ {"<<iter->Item()->priority+10 <<"} ]");
thread->priority += 10;
// thread->set_wait_starttime(totalTicks);
// thread->accu_wait_ticks = 0;
thread->accu_wait_ticks -= 1500; // Should NOT reset!
}
}
}
}
////////////////////////// 12/15 ///////////////////
// Display all thread in ready queues.
void
Scheduler::List_All_thread(){
cout<<"L1 queue: ";
if(!L1List->IsEmpty()){
ListIterator<Thread*> *iter;
iter = new ListIterator<Thread*>(L1List);
for (; !iter->IsDone(); iter->Next()) {
// cout<< iter->Item()->getName()<<" id "<<iter->Item()->ID <<" /";
cout<< iter->Item()->getName()<<" ";
}
cout<<" \n";
}
// else cout<< "empty\n";
else cout<< "\n";
cout<<"L2 queue: ";
if(!L2List->IsEmpty()){
ListIterator<Thread*> *iter;
iter = new ListIterator<Thread*>(L2List);
for (; !iter->IsDone(); iter->Next()) {
// cout<< iter->Item()->getName()<<" id "<<iter->Item()->ID <<" /";
cout<< iter->Item()->getName()<<" ";
}
cout<<" \n";
}
// else cout<< "empty\n";
else cout<< "\n";
cout<<"L3 queue: ";
if(!L3List->IsEmpty()){
ListIterator<Thread*> *iter;
iter = new ListIterator<Thread*>(L3List);
for (; !iter->IsDone(); iter->Next()) {
// cout<< iter->Item()->getName()<<" id "<<iter->Item()->ID <<" /";
cout<< iter->Item()->getName()<<" ";
}
cout<<" \n";
}
// else cout<< "empty\n";
else cout<< "\n";
}
//----------------------------------------------------------------------
// Scheduler::StillHasThreadToRun
// Return the next thread to be scheduled onto the CPU.
// If there are no ready threads, return NULL.
// Side effect:
// Thread is removed from the ready list.
//----------------------------------------------------------------------
bool
Scheduler::StillHasThreadToRun ()
{
ASSERT(kernel->interrupt->getLevel() == IntOff);
if( ! L1List->IsEmpty()){
#ifdef LIST_QUEUE_CONTENTS
cout<<"L1 queue: ";
ListIterator<Thread*> *iter;
iter = new ListIterator<Thread*>(L1List);
for (; !iter->IsDone(); iter->Next()) {
// cout<< iter->Item()->getName()<<" id "<<iter->Item()->ID <<" /";
cout<< iter->Item()->getName()<<" /";
}
cout<<" \n";
#endif
return TRUE;
}
else{
if(!L2List->IsEmpty()){
#ifdef LIST_QUEUE_CONTENTS
cout<<"L2 queue: ";
ListIterator<Thread*> *iter;
iter = new ListIterator<Thread*>(L2List);
for (; !iter->IsDone(); iter->Next()) {
// cout<< iter->Item()->getName()<<" id "<<iter->Item()->ID <<" /";
cout<< iter->Item()->getName()<<" /";
}
cout<<" \n";
#endif
return TRUE;
}
else{
if(!L3List->IsEmpty()){
#ifdef LIST_QUEUE_CONTENTS
cout<<"L3 queue: ";
ListIterator<Thread*> *iter;
iter = new ListIterator<Thread*>(L3List);
for (; !iter->IsDone(); iter->Next()) {
// cout<< iter->Item()->getName()<<" id "<<iter->Item()->ID <<" /";
cout<< iter->Item()->getName()<<" /";
}
cout<<" \n";
#endif
return TRUE;
}
else return FALSE;
}
}
// if (readyList->IsEmpty()) {
// return NULL;
// } else {
// return readyList->RemoveFront();
// }
}
// // Return kernel->currentThread and remove it from
// Thread*
// Scheduler::ReturnCurrentThread(){
// }
//----------------------------------------------------------------------
// Scheduler::Run
// Dispatch the CPU to nextThread. Save the state of the old thread,
// and load the state of the new thread, by calling the machine
// dependent context switch routine, SWITCH.
//
// Note: we assume the state of the previously running thread has
// already been changed from running to blocked or ready (depending).
// Side effect:
// The global variable kernel->currentThread becomes nextThread.
//
// "nextThread" is the thread to be put into the CPU.
// "finishing" is set if the current thread is to be deleted
// once we're no longer running on its stack
// (when the next thread starts running)
//----------------------------------------------------------------------
void
Scheduler::Run (Thread *nextThread, bool finishing)
{
Thread *oldThread = kernel->currentThread;
ASSERT(kernel->interrupt->getLevel() == IntOff);
if (finishing) { // mark that we need to delete current thread
ASSERT(toBeDestroyed == NULL);
toBeDestroyed = oldThread;
}
if (oldThread->space != NULL) { // if this thread is a user program,
oldThread->SaveUserState(); // save the user's CPU registers
oldThread->space->SaveState();
}
oldThread->CheckOverflow(); // check if the old thread
// had an undetected stack overflow
///////// 12/15 /////////
// Should UPDATE BURST TIME when call thread->Sleep(FALSE)!!!
// Update approx. burst time for OLD thread.
// Get current ticks. (Update this thread's approx. cpu burst ticks)
// oldThread->update_burst_time(kernel->stats->totalTicks);
kernel->currentThread = nextThread; // switch to the next thread
nextThread->setStatus(RUNNING); // nextThread is now running
DEBUG(dbgThread, "Switching from: " << oldThread->getName() << " to: " << nextThread->getName());
// This is a machine-dependent assembly language routine defined
// in switch.s. You may have to think
// a bit to figure out what happens after this, both from the point
// of view of the thread and from the perspective of the "outside world".
SWITCH(oldThread, nextThread);
// we're back, running oldThread
///////// 12/10 /////////
// Resume accumulating CPU burst ticks.
// kernel->currentThread->record_start_ticks(kernel->stats->totalTicks);
// cout<<"thread "<<kernel->currentThread->getID()<<" update start ticks: "<< kernel->currentThread->cpu_start_ticks<<std::endl;
// // interrupts are off when we return from switch!
ASSERT(kernel->interrupt->getLevel() == IntOff);
DEBUG(dbgThread, "Now in thread: " << oldThread->getName());
CheckToBeDestroyed(); // check if thread we were running
// before this one has finished
// and needs to be cleaned up
if (oldThread->space != NULL) { // if there is an address space
oldThread->RestoreUserState(); // to restore, do it.
oldThread->space->RestoreState();
}
}
//----------------------------------------------------------------------
// Scheduler::CheckToBeDestroyed
// If the old thread gave up the processor because it was finishing,
// we need to delete its carcass. Note we cannot delete the thread
// before now (for example, in Thread::Finish()), because up to this
// point, we were still running on the old thread's stack!
//----------------------------------------------------------------------
void
Scheduler::CheckToBeDestroyed()
{
if (toBeDestroyed != NULL) {
delete toBeDestroyed;
toBeDestroyed = NULL;
}
}
//----------------------------------------------------------------------
// Scheduler::Print
// Print the scheduler state -- in other words, the contents of
// the ready list. For debugging.
//----------------------------------------------------------------------
void
Scheduler::Print()
{
cout << "Ready list contents:\n";
readyList->Apply(ThreadPrint);
}
| [
"jennyyeh56789@gmail.com"
] | jennyyeh56789@gmail.com |
5b9767761cd213187ceee6246ecafa08e53b88a8 | cdbce8b09cf43bf2e66e5e3437ae591262a55270 | /D2Ex2-master/ExListBox.h | 5cf2b600eac90b426fb0b73c350afbc5ded9db15 | [] | no_license | tokenok/Visual-Studio-Projects | b82a53f141eff01eef69f119f55dabd8b52e803e | c3947dda48fdccdba01a21b0e5052b12a18fe2a6 | refs/heads/master | 2022-05-02T11:06:46.201991 | 2018-10-28T22:07:24 | 2018-10-28T22:07:24 | 89,531,738 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | h | #ifndef __EXLISTBOX_H__
#define __EXLISTBOX_H__
#include "ExControl.h"
#include "ExTextBox.h"
#include "ExScrollBar.h"
#include <vector>
class ExListBox : public ExControl
{
public:
ExListBox(int X, int Y, int Width, int Height, int Color, int Font);
void AddToList(wstring Member);
void RemoveFromList(wstring Member);
void Sort();
void Draw();
~ExListBox(void);
int aColor;
int MsgOffset;
void GfxMove(vector<ExTextBox*>::size_type Offset);
private:
vector<ExTextBox*> Members;
ExScrollBar aScrollBar;
};
#endif | [
"mrjack.is.minty@gmail.com"
] | mrjack.is.minty@gmail.com |
d1125603f97352ea79a82c531b35dee0bb844598 | 30a34b3503decf1b4516039df3106cd152631819 | /4AL17IS024_MAYURESH_KUNDER/PradeepSir_Coding_Challenge/Coding_Challenge_3/SumSeries.cpp | 107e6aa1348b1515e209676fbb16056d68561335 | [] | no_license | alvas-education-foundation/ISE_3rd_Year_Coding_challenge | 8ddb6c325bf6ab63e2f73d16573fa0b6e2484136 | b4074cab4a47aad07ed0fa426eacccbfafdef7f8 | refs/heads/master | 2022-11-23T20:52:19.204693 | 2020-07-23T11:28:15 | 2020-07-23T11:28:15 | 265,195,514 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 247 | cpp | //sum
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
long i,n,x,sum=1;
cout<<“1+x+x^2+……+x^n”;
cout<<“nnEnter the value of x and n:”;
cin>>x>>n;
for(i=1;i<=n;++i)
sum+=pow(x,i);
cout<<“nSum=”<<sum;
} | [
"kundermayuresh249@gmail.com"
] | kundermayuresh249@gmail.com |
13d6112e4064d1ae87c5f97ad7dac5b82c976a19 | 881f7c1b2ffc0e292c50385e2c202fde10fbb301 | /include/thectci/factory.hpp | 0aa01a783110b5fae6238bbfc340dc6c3d9e4006 | [
"MIT"
] | permissive | PeterHajdu/thectci | 322b64236564d77856d04c903a9a6ab50dbdf8df | 7ffe4c7d8ccbf55490e155f93ef8637d6f9c4119 | refs/heads/master | 2021-01-23T17:32:11.156279 | 2015-04-29T10:20:40 | 2015-04-29T10:20:40 | 21,159,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,543 | hpp | #pragma once
#include <thectci/id.hpp>
#include <memory>
#include <cassert>
#include <functional>
#include <unordered_map>
namespace the
{
namespace ctci
{
template < typename Base >
class Creator
{
public:
typedef std::unique_ptr< Base > base_pointer;
virtual ~Creator() {}
virtual base_pointer create() = 0;
};
template < typename Base, typename Child >
class ExactCreator : public Creator< Base >
{
public:
typedef std::unique_ptr< Base > base_pointer;
base_pointer create() override
{
return std::unique_ptr< Base >( new Child() );
}
};
template < typename Base >
class Factory
{
public:
typedef std::unique_ptr< Base > base_pointer;
typedef Creator< Base > BaseCreator;
void register_creator( Id class_id, BaseCreator& base_creator )
{
assert( !is_registered( class_id ) );
m_creators.emplace( std::make_pair( class_id, std::ref( base_creator ) ) );
}
base_pointer create( Id class_id ) const
{
typename Creators::const_iterator creator_iterator( m_creators.find( class_id ) );
if ( creator_iterator == end( m_creators ) )
{
return base_pointer( nullptr );
}
return creator_iterator->second.get().create();
}
bool is_registered( Id class_id ) const
{
return m_creators.find( class_id ) != m_creators.end();
}
private:
typedef std::reference_wrapper< BaseCreator > CreatorReference;
typedef std::unordered_map< Id, CreatorReference > Creators;
Creators m_creators;
};
}
}
| [
"peter.ferenc.hajdu@gmail.com"
] | peter.ferenc.hajdu@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.