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
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 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
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
a3b2ad9f6073fe88b77954d5c7d6763dc2341020
ab97a8915347c76d05d6690dbdbcaf23d7f0d1fd
/fuchsia/engine/context_provider_impl.cc
33398c9ac7a2414fc56a4dc73111e5f539cdd090
[ "BSD-3-Clause" ]
permissive
laien529/chromium
c9eb243957faabf1b477939e3b681df77f083a9a
3f767cdd5c82e9c78b910b022ffacddcb04d775a
refs/heads/master
2022-11-28T00:28:58.669067
2020-08-20T08:37:31
2020-08-20T08:37:31
288,961,699
1
0
BSD-3-Clause
2020-08-20T09:21:57
2020-08-20T09:21:56
null
UTF-8
C++
false
false
20,796
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "fuchsia/engine/context_provider_impl.h" #include <fuchsia/sys/cpp/fidl.h> #include <lib/async/default.h> #include <lib/fdio/directory.h> #include <lib/fdio/fd.h> #include <lib/fdio/io.h> #include <lib/zx/job.h> #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <zircon/processargs.h> #include <string> #include <utility> #include <vector> #include "base/base_paths_fuchsia.h" #include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_file.h" #include "base/fuchsia/default_job.h" #include "base/fuchsia/fuchsia_logging.h" #include "base/json/json_reader.h" #include "base/logging.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/stl_util.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/values.h" #include "build/build_config.h" #include "cc/base/switches.h" #include "components/viz/common/features.h" #include "content/public/common/content_switches.h" #include "fuchsia/base/config_reader.h" #include "fuchsia/base/string_util.h" #include "fuchsia/engine/common/web_engine_content_client.h" #include "fuchsia/engine/switches.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "gpu/config/gpu_finch_features.h" #include "media/base/key_system_names.h" #include "media/base/media_switches.h" #include "net/http/http_util.h" #include "sandbox/policy/fuchsia/sandbox_policy_fuchsia.h" #include "services/network/public/cpp/features.h" #include "third_party/blink/public/common/switches.h" #include "third_party/widevine/cdm/widevine_cdm_common.h" #include "ui/gfx/switches.h" #include "ui/gl/gl_switches.h" #include "ui/ozone/public/ozone_switches.h" namespace { // Use a constexpr instead of the existing base::Feature, because of the // additional dependencies required. constexpr char kMixedContentAutoupgradeFeatureName[] = "AutoupgradeMixedContent"; constexpr char kDisableMixedContentAutoupgradeOrigin[] = "disable-mixed-content-autoupgrade"; // Returns the underlying channel if |directory| is a client endpoint for a // |fuchsia::io::Directory| protocol. Otherwise, returns an empty channel. zx::channel ValidateDirectoryAndTakeChannel( fidl::InterfaceHandle<fuchsia::io::Directory> directory_handle) { fidl::SynchronousInterfacePtr<fuchsia::io::Directory> directory = directory_handle.BindSync(); zx_status_t status = ZX_ERR_INTERNAL; std::vector<uint8_t> entries; directory->ReadDirents(0, &status, &entries); if (status == ZX_OK) { return directory.Unbind().TakeChannel(); } // Not a directory. return zx::channel(); } // Populates a CommandLine with content directory name/handle pairs. bool SetContentDirectoriesInCommandLine( std::vector<fuchsia::web::ContentDirectoryProvider> directories, base::CommandLine* command_line, base::LaunchOptions* launch_options) { DCHECK(command_line); DCHECK(launch_options); std::vector<std::string> directory_pairs; for (size_t i = 0; i < directories.size(); ++i) { fuchsia::web::ContentDirectoryProvider& directory = directories[i]; if (directory.name().find('=') != std::string::npos || directory.name().find(',') != std::string::npos) { DLOG(ERROR) << "Invalid character in directory name: " << directory.name(); return false; } if (!directory.directory().is_valid()) { DLOG(ERROR) << "Service directory handle not valid for directory: " << directory.name(); return false; } uint32_t directory_handle_id = base::LaunchOptions::AddHandleToTransfer( &launch_options->handles_to_transfer, directory.mutable_directory()->TakeChannel().release()); directory_pairs.emplace_back( base::StrCat({directory.name().c_str(), "=", base::NumberToString(directory_handle_id)})); } command_line->AppendSwitchASCII(switches::kContentDirectories, base::JoinString(directory_pairs, ",")); return true; } base::Value LoadConfig() { const base::Optional<base::Value>& config = cr_fuchsia::LoadPackageConfig(); if (!config) { DLOG(WARNING) << "Configuration data not found. Using default " "WebEngine configuration."; return base::Value(base::Value::Type::DICTIONARY); } return config->Clone(); } void AppendFeature(base::StringPiece features_flag, base::StringPiece feature_string, base::CommandLine* command_line) { if (!command_line->HasSwitch(features_flag)) { command_line->AppendSwitchNative(features_flag.as_string(), feature_string.as_string()); return; } std::string new_feature_string = command_line->GetSwitchValueASCII(features_flag); new_feature_string.append(",").append(feature_string.as_string()); command_line->RemoveSwitch(features_flag); command_line->AppendSwitchNative(features_flag.as_string(), new_feature_string); } // Returns false if the config is present but has invalid contents. bool MaybeAddCommandLineArgsFromConfig(const base::Value& config, base::CommandLine* command_line) { const base::Value* args = config.FindDictKey("command-line-args"); if (!args) return true; static const base::StringPiece kAllowedArgs[] = { blink::switches::kGpuRasterizationMSAASampleCount, blink::switches::kMinHeightForGpuRasterTile, cc::switches::kEnableGpuBenchmarking, switches::kDisableFeatures, switches::kDisableGpuWatchdog, // TODO(crbug.com/1082821): Remove this switch from the allow-list. switches::kEnableCastStreamingReceiver, switches::kEnableFeatures, switches::kEnableLowEndDeviceMode, switches::kForceGpuMemAvailableMb, switches::kForceGpuMemDiscardableLimitMb, switches::kForceMaxTextureSize, switches::kMaxDecodedImageSizeMb, switches::kRendererProcessLimit, switches::kWebglAntialiasingMode, switches::kWebglMSAASampleCount, }; for (const auto& arg : args->DictItems()) { if (!base::Contains(kAllowedArgs, arg.first)) { // TODO(https://crbug.com/1032439): Increase severity and return false // once we have a mechanism for soft transitions of supported arguments. LOG(WARNING) << "Unknown command-line arg: '" << arg.first << "'. Config file and WebEngine version may not match."; continue; } DCHECK(!command_line->HasSwitch(arg.first)); if (arg.second.is_none()) { command_line->AppendSwitch(arg.first); } else if (arg.second.is_string()) { command_line->AppendSwitchNative(arg.first, arg.second.GetString()); } else { LOG(ERROR) << "Config command-line arg must be a string: " << arg.first; return false; } // TODO(https://crbug.com/1023012): enable-low-end-device-mode currently // fakes 512MB total physical memory, which triggers RGB4444 textures, // which // we don't yet support. if (arg.first == switches::kEnableLowEndDeviceMode) command_line->AppendSwitch(blink::switches::kDisableRGBA4444Textures); } return true; } // Returns true if DRM is supported in current configuration. Currently we // assume that it is supported on ARM64, but not on x64. // // TODO(crbug.com/1013412): Detect support for all features required for // FuchsiaCdm. Specifically we need to verify that protected memory is supported // and that mediacodec API provides hardware video decoders. bool IsFuchsiaCdmSupported() { #if defined(ARCH_CPU_ARM64) return true; #else return false; #endif } } // namespace const uint32_t ContextProviderImpl::kContextRequestHandleId = PA_HND(PA_USER0, 0); ContextProviderImpl::ContextProviderImpl() = default; ContextProviderImpl::~ContextProviderImpl() = default; void ContextProviderImpl::Create( fuchsia::web::CreateContextParams params, fidl::InterfaceRequest<fuchsia::web::Context> context_request) { if (!context_request.is_valid()) { DLOG(ERROR) << "Invalid |context_request|."; return; } if (!params.has_service_directory()) { DLOG(ERROR) << "Missing argument |service_directory| in CreateContextParams."; context_request.Close(ZX_ERR_INVALID_ARGS); return; } fidl::InterfaceHandle<::fuchsia::io::Directory> service_directory = std::move(*params.mutable_service_directory()); if (!service_directory) { DLOG(ERROR) << "Invalid |service_directory| in CreateContextParams."; context_request.Close(ZX_ERR_INVALID_ARGS); return; } base::LaunchOptions launch_options; launch_options.process_name_suffix = ":context"; sandbox::policy::SandboxPolicyFuchsia sandbox_policy( sandbox::policy::SandboxType::kWebContext); sandbox_policy.SetServiceDirectory(std::move(service_directory)); sandbox_policy.UpdateLaunchOptionsForSandbox(&launch_options); // SandboxPolicyFuchsia should isolate each Context in its own job. DCHECK_NE(launch_options.job_handle, ZX_HANDLE_INVALID); // Transfer the ContextRequest handle to a well-known location in the child // process' handle table. launch_options.handles_to_transfer.push_back( {kContextRequestHandleId, context_request.channel().get()}); // Bind |data_directory| to /data directory, if provided. if (params.has_data_directory()) { zx::channel data_directory_channel = ValidateDirectoryAndTakeChannel( std::move(*params.mutable_data_directory())); if (data_directory_channel.get() == ZX_HANDLE_INVALID) { DLOG(ERROR) << "Invalid argument |data_directory| in CreateContextParams."; context_request.Close(ZX_ERR_INVALID_ARGS); return; } base::FilePath data_path; if (!base::PathService::Get(base::DIR_APP_DATA, &data_path)) { DLOG(ERROR) << "Failed to get data directory service path."; context_request.Close(ZX_ERR_INTERNAL); return; } launch_options.paths_to_transfer.push_back( base::PathToTransfer{data_path, data_directory_channel.release()}); } base::CommandLine launch_command = *base::CommandLine::ForCurrentProcess(); std::vector<zx::channel> devtools_listener_channels; base::Value web_engine_config = config_for_test_.is_none() ? LoadConfig() : std::move(config_for_test_); if (!MaybeAddCommandLineArgsFromConfig(web_engine_config, &launch_command)) { context_request.Close(ZX_ERR_INTERNAL); return; } if (params.has_remote_debugging_port()) { launch_command.AppendSwitchNative( switches::kRemoteDebuggingPort, base::NumberToString(params.remote_debugging_port())); } if (devtools_listeners_.size() != 0) { // Connect DevTools listeners to the new Context process. std::vector<std::string> handles_ids; for (auto& devtools_listener : devtools_listeners_.ptrs()) { fidl::InterfaceHandle<fuchsia::web::DevToolsPerContextListener> client_listener; devtools_listener.get()->get()->OnContextDevToolsAvailable( client_listener.NewRequest()); devtools_listener_channels.emplace_back(client_listener.TakeChannel()); handles_ids.push_back( base::NumberToString(base::LaunchOptions::AddHandleToTransfer( &launch_options.handles_to_transfer, devtools_listener_channels.back().get()))); } launch_command.AppendSwitchNative(switches::kRemoteDebuggerHandles, base::JoinString(handles_ids, ",")); } fuchsia::web::ContextFeatureFlags features = {}; if (params.has_features()) features = params.features(); const bool is_headless = (features & fuchsia::web::ContextFeatureFlags::HEADLESS) == fuchsia::web::ContextFeatureFlags::HEADLESS; if (is_headless) { launch_command.AppendSwitchNative(switches::kOzonePlatform, switches::kHeadless); launch_command.AppendSwitch(switches::kHeadless); } if ((features & fuchsia::web::ContextFeatureFlags::LEGACYMETRICS) == fuchsia::web::ContextFeatureFlags::LEGACYMETRICS) { launch_command.AppendSwitch(switches::kUseLegacyMetricsService); } const bool enable_vulkan = (features & fuchsia::web::ContextFeatureFlags::VULKAN) == fuchsia::web::ContextFeatureFlags::VULKAN; bool enable_widevine = (features & fuchsia::web::ContextFeatureFlags::WIDEVINE_CDM) == fuchsia::web::ContextFeatureFlags::WIDEVINE_CDM; bool enable_playready = params.has_playready_key_system(); // VULKAN is required for DRM-protected video playback. Allow DRM to also be // enabled for HEADLESS Contexts, since Vulkan is never required for audio. if ((enable_widevine || enable_playready) && !enable_vulkan && !is_headless) { DLOG(ERROR) << "WIDEVINE_CDM and PLAYREADY_CDM features require VULKAN or " "HEADLESS."; context_request.Close(ZX_ERR_NOT_SUPPORTED); return; } // If the system doesn't actually support DRM then disable it. This may result // in the Context being able to run without using protected buffers. if (enable_playready && !IsFuchsiaCdmSupported()) { LOG(WARNING) << "PlayReady is not supported on this device."; enable_playready = false; } if (enable_widevine && !IsFuchsiaCdmSupported()) { LOG(WARNING) << "Widevine is not supported on this device."; enable_widevine = false; } bool allow_protected_graphics = web_engine_config.FindBoolPath("allow-protected-graphics") .value_or(false); bool force_protected_graphics = web_engine_config.FindBoolPath("force-protected-graphics") .value_or(false); bool enable_protected_graphics = ((enable_playready || enable_widevine) && allow_protected_graphics) || force_protected_graphics; if (enable_protected_graphics) { launch_command.AppendSwitch(switches::kEnforceVulkanProtectedMemory); launch_command.AppendSwitch(switches::kEnableProtectedVideoBuffers); bool force_protected_video_buffers = web_engine_config.FindBoolPath("force-protected-video-buffers") .value_or(false); if (force_protected_video_buffers) { launch_command.AppendSwitch(switches::kForceProtectedVideoOutputBuffers); } } if (enable_vulkan) { if (is_headless) { DLOG(ERROR) << "VULKAN and HEADLESS features cannot be used together."; context_request.Close(ZX_ERR_NOT_SUPPORTED); return; } VLOG(1) << "Enabling Vulkan GPU acceleration."; // Vulkan requires use of SkiaRenderer, configured to a use Vulkan context. launch_command.AppendSwitch(switches::kUseVulkan); const std::vector<base::StringPiece> enabled_features = { features::kUseSkiaRenderer.name, features::kVulkan.name}; AppendFeature(switches::kEnableFeatures, base::JoinString(enabled_features, ","), &launch_command); // SkiaRenderer requires out-of-process rasterization be enabled. launch_command.AppendSwitch(switches::kEnableOopRasterization); launch_command.AppendSwitchASCII(switches::kUseGL, gl::kGLImplementationANGLEName); } else { VLOG(1) << "Disabling GPU acceleration."; // Disable use of Vulkan GPU, and use of the software-GL rasterizer. The // Context will still run a GPU process, but will not support WebGL. launch_command.AppendSwitch(switches::kDisableGpu); launch_command.AppendSwitch(switches::kDisableSoftwareRasterizer); } if (enable_widevine) { launch_command.AppendSwitch(switches::kEnableWidevine); } if (enable_playready) { const std::string& key_system = params.playready_key_system(); if (key_system == kWidevineKeySystem || media::IsClearKey(key_system)) { LOG(ERROR) << "Invalid value for CreateContextParams/playready_key_system: " << key_system; context_request.Close(ZX_ERR_INVALID_ARGS); return; } launch_command.AppendSwitchNative(switches::kPlayreadyKeySystem, key_system); } bool disable_software_video_decoder = (features & fuchsia::web::ContextFeatureFlags::HARDWARE_VIDEO_DECODER_ONLY) == fuchsia::web::ContextFeatureFlags::HARDWARE_VIDEO_DECODER_ONLY; bool enable_hardware_video_decoder = (features & fuchsia::web::ContextFeatureFlags::HARDWARE_VIDEO_DECODER) == fuchsia::web::ContextFeatureFlags::HARDWARE_VIDEO_DECODER; if (disable_software_video_decoder) { if (!enable_hardware_video_decoder) { LOG(ERROR) << "Software video decoding may only be disabled if hardware " "video decoding is enabled."; context_request.Close(ZX_ERR_INVALID_ARGS); return; } launch_command.AppendSwitch(switches::kDisableSoftwareVideoDecoders); } // Validate embedder-supplied product, and optional version, and pass it to // the Context to include in the UserAgent. if (params.has_user_agent_product()) { if (!net::HttpUtil::IsToken(params.user_agent_product())) { LOG(ERROR) << "Invalid embedder product."; context_request.Close(ZX_ERR_INVALID_ARGS); return; } std::string product_tag(params.user_agent_product()); if (params.has_user_agent_version()) { if (!net::HttpUtil::IsToken(params.user_agent_version())) { LOG(ERROR) << "Invalid embedder version."; context_request.Close(ZX_ERR_INVALID_ARGS); return; } product_tag += "/" + params.user_agent_version(); } launch_command.AppendSwitchNative(switches::kUserAgentProductAndVersion, std::move(product_tag)); } else if (params.has_user_agent_version()) { LOG(ERROR) << "Embedder version without product."; context_request.Close(ZX_ERR_INVALID_ARGS); return; } if (params.has_content_directories() && !SetContentDirectoriesInCommandLine( std::move(*params.mutable_content_directories()), &launch_command, &launch_options)) { LOG(ERROR) << "Invalid content directories specified."; context_request.Close(ZX_ERR_INVALID_ARGS); return; } if (params.has_unsafely_treat_insecure_origins_as_secure()) { const std::vector<std::string>& insecure_origins = params.unsafely_treat_insecure_origins_as_secure(); for (auto origin : insecure_origins) { if (origin == switches::kAllowRunningInsecureContent) launch_command.AppendSwitch(switches::kAllowRunningInsecureContent); if (origin == kDisableMixedContentAutoupgradeOrigin) { AppendFeature(switches::kDisableFeatures, kMixedContentAutoupgradeFeatureName, &launch_command); } } // TODO(crbug.com/1023510): Pass the rest of the list to the Context // process. } if (params.has_cors_exempt_headers()) { std::vector<base::StringPiece> cors_exempt_headers; for (const auto& header : params.cors_exempt_headers()) { cors_exempt_headers.push_back(cr_fuchsia::BytesAsString(header)); } launch_command.AppendSwitchNative( switches::kCorsExemptHeaders, base::JoinString(cors_exempt_headers, ",")); } base::Process context_process; if (launch_for_test_) { context_process = launch_for_test_.Run(launch_command, launch_options); } else { context_process = base::LaunchProcess(launch_command, launch_options); } if (context_process.IsValid()) { // Set |context_process| termination to teardown its job and sub-processes. zx_status_t result = zx_job_set_critical(launch_options.job_handle, 0, context_process.Handle()); ZX_CHECK(ZX_OK == result, result) << "zx_job_set_critical"; } // |context_request| and any DevTools channels were transferred (not copied) // to the Context process. ignore_result(context_request.TakeChannel().release()); for (auto& channel : devtools_listener_channels) ignore_result(channel.release()); } void ContextProviderImpl::SetLaunchCallbackForTest( LaunchCallbackForTest launch) { launch_for_test_ = std::move(launch); } void ContextProviderImpl::EnableDevTools( fidl::InterfaceHandle<fuchsia::web::DevToolsListener> listener, EnableDevToolsCallback callback) { devtools_listeners_.AddInterfacePtr(listener.Bind()); callback(); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
725bd3486f554f2ce056bd693f749e7645c892a5
eb6bf119dccddd3bb9709378ca14a856e9305850
/src/scene.h
470386620ec659ce4fe4db66a23827f8615d48b7
[]
no_license
tackyattack/pathFire
b8734277688a04771eaaf5b52652509be74b0a5c
94636c5d117cb72cb55b5d93ac3fd610cf3329ed
refs/heads/master
2020-12-02T06:45:12.721139
2017-07-11T12:55:07
2017-07-11T12:55:07
87,378,723
0
0
null
null
null
null
UTF-8
C++
false
false
1,021
h
// // scene.h // pathTrace // // Created by HENRY BERGIN on 3/2/17. // Holds all the data for a scene // #ifndef scene_h #define scene_h #include <iostream> #include "3dTypes.h" using namespace std; struct materialNode { }; struct meshNode { materialNode *material; Tri3D **triangles; int triangleCount = 0; int triangleFill = 0; meshNode(int triCnt) { // constructor triangleCount = triCnt; triangles = new Tri3D*[triangleCount]; // allocate memory for the triangle pointers // for triangles that belong to this mesh } void addTriangle(Tri3D *triangle) { // adds a triangle to the mesh node if(triangleFill > (triangleCount-1)) { cout << "error: trying to fill past limit of mesh" << endl; return; } triangles[triangleFill] = triangle; triangleFill++; // increment fill line } }; class scene { }; #endif /* scene_h */
[ "tackyattack@gmail.com" ]
tackyattack@gmail.com
ad2ef3b37b34ce3e5d6ea4e8a0d332e88665151e
8c7cfbb9d8268f2c1cb49e1f4f154458cf56d3e9
/Homework/Development of Applications on Operating System/Cocos - HelloCocos/Classes/AppDelegate.cpp
c020c53732984c3ab253274fedf58fff1509b8d8
[]
no_license
MegaShow/college-programming
bde5c83f353f727f9bc84426b8c16534848965dd
dc3351e0811b4c3b0738e599c014176c845bd21c
refs/heads/master
2021-07-10T03:57:18.254204
2019-10-26T16:07:21
2019-10-26T16:07:21
114,732,791
3
7
null
2019-10-26T16:07:22
2017-12-19T07:23:03
Jupyter Notebook
UTF-8
C++
false
false
4,312
cpp
#include "AppDelegate.h" #include "HelloWorldScene.h" // #define USE_AUDIO_ENGINE 1 // #define USE_SIMPLE_AUDIO_ENGINE 1 #if USE_AUDIO_ENGINE && USE_SIMPLE_AUDIO_ENGINE #error "Don't use AudioEngine and SimpleAudioEngine at the same time. Please just select one in your game!" #endif #if USE_AUDIO_ENGINE #include "audio/include/AudioEngine.h" using namespace cocos2d::experimental; #elif USE_SIMPLE_AUDIO_ENGINE #include "audio/include/SimpleAudioEngine.h" using namespace CocosDenshion; #endif USING_NS_CC; static cocos2d::Size designResolutionSize = cocos2d::Size(480, 320); static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320); static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768); static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536); AppDelegate::AppDelegate() {} AppDelegate::~AppDelegate() { #if USE_AUDIO_ENGINE AudioEngine::end(); #elif USE_SIMPLE_AUDIO_ENGINE SimpleAudioEngine::end(); #endif } // if you want a different context, modify the value of glContextAttrs // it will affect all platforms void AppDelegate::initGLContextAttrs() { // set OpenGL context attributes: red,green,blue,alpha,depth,stencil GLContextAttrs glContextAttrs = { 8, 8, 8, 8, 24, 8 }; GLView::setGLContextAttrs(glContextAttrs); } // if you want to use the package manager to install more packages, // don't modify or remove this function static int register_all_packages() { return 0; //flag for packages manager } bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if (!glview) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) glview = GLViewImpl::createWithRect("HelloCocos", cocos2d::Rect(0, 0, designResolutionSize.width, designResolutionSize.height)); #else glview = GLViewImpl::create("HelloCocos"); #endif director->setOpenGLView(glview); } // turn on display FPS director->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0f / 60); // director->setClearColor(Color4F::WHITE); // Set the design resolution glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER); auto frameSize = glview->getFrameSize(); // if the frame's height is larger than the height of medium size. if (frameSize.height > mediumResolutionSize.height) { director->setContentScaleFactor(MIN(largeResolutionSize.height / designResolutionSize.height, largeResolutionSize.width / designResolutionSize.width)); } // if the frame's height is larger than the height of small size. else if (frameSize.height > smallResolutionSize.height) { director->setContentScaleFactor(MIN(mediumResolutionSize.height / designResolutionSize.height, mediumResolutionSize.width / designResolutionSize.width)); } // if the frame's height is smaller than the height of medium size. else { director->setContentScaleFactor(MIN(smallResolutionSize.height / designResolutionSize.height, smallResolutionSize.width / designResolutionSize.width)); } register_all_packages(); // create a scene. it's an autorelease object auto scene = HelloWorld::createScene(); // run director->runWithScene(scene); return true; } // This function will be called when the app is inactive. Note, when receiving a phone call it is invoked. void AppDelegate::applicationDidEnterBackground() { Director::getInstance()->stopAnimation(); #if USE_AUDIO_ENGINE AudioEngine::pauseAll(); #elif USE_SIMPLE_AUDIO_ENGINE SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); SimpleAudioEngine::getInstance()->pauseAllEffects(); #endif } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { Director::getInstance()->startAnimation(); #if USE_AUDIO_ENGINE AudioEngine::resumeAll(); #elif USE_SIMPLE_AUDIO_ENGINE SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); SimpleAudioEngine::getInstance()->resumeAllEffects(); #endif }
[ "MegaXiu@outlook.com" ]
MegaXiu@outlook.com
dc8168edbc9f6cf128ac8f5c5c7b551783549ffa
80d17f09c98be69e75c3de23e157d6f4eba22f69
/config.h
ffc89c9e0436920cde3d2885e73797767e218fc4
[]
no_license
xiao004/chat_geloutingyu
d50cd623789edee9dba4d7528f1f58a511af7731
c3382f87265303898498ee0a476be14d27069a6e
refs/heads/master
2020-06-04T18:40:44.815172
2019-06-16T04:41:09
2019-06-16T04:41:09
192,148,569
0
0
null
null
null
null
UTF-8
C++
false
false
1,045
h
#ifndef CONFIG_H #define CONFIG_H class config { private: // static 成员类内初始化则赋的值必须为常量 // 且对于非 const int 类型的 static 成员要类内初始化的化要加 constexpr 关键字 constexpr static const char* db_name = "chat_geloutingyu"; constexpr static const char* db_ip = "localhost"; constexpr static const char* db_user = "root"; constexpr static const char* db_passwd = "mysql"; constexpr static const char* db_charset = "utf8"; static const int db_port = 3306; // mysql 连接池的大小 static const int max_size = 10; public: config() { } ~config() { } static const int get_max_size() { return max_size; } static const char* get_db_name() { return db_name; } static const char* get_db_ip() { return db_ip; } static const char* get_db_user() { return db_user; } static const char* get_db_passwd() { return db_passwd; } static const char* get_db_charset() { return db_charset; } static const int get_db_port() { return db_port; } }; #endif
[ "371293374@qq.com" ]
371293374@qq.com
69616ced4b300d89efc97693f0c36f3337014780
fa823d1aefead6e3f374fe92405f45a4fd5aa257
/graph_theory/dag_dfs_order.cpp
90c664491a3c9d828b38d7f0ed14f7752c78ecd8
[]
no_license
xaero7/hgoi_cpp_code
497fb9fb0691463b90a38a360e77b66096d3c0e3
4e91cb1b5eb12327076ccc064c13b54a553290a7
refs/heads/master
2020-03-24T09:53:19.805352
2018-09-28T01:19:11
2018-09-28T01:19:11
142,640,817
6
0
null
null
null
null
UTF-8
C++
false
false
999
cpp
/* * DAG(有向无环图)的深度优先搜索标记 * INIT:edge[][]邻接矩阵;pre[], post[], tag全置0 * CALL:dfsTag(i, n); pre/post:开始/结束时间 */ const int V = 1010; int edge[V][V]; int pre[V]; int post[V]; int tag; void dfsTag(int cur, int n) { //vertex:0 ~ n - 1 pre[cur] = ++tag; for (int i = 0; i < n; i++) { if (edge[cur][i]) { if (0 == pre[i]) { std::cout << "Three Edge!" << '\n'; dfsTag(i, n); } else { if (0 == post[i]) { std::cout << "Back Edge!" << '\n'; } else if (pre[i] > pre[cur]) { std::cout << "Down Edge!" << '\n'; } else { std::cout << "Cross Edge!" << '\n'; } } } } post[cur] = ++tag; return ; }
[ "setoy@qq.com" ]
setoy@qq.com
445aa49344568b4915f495de9b951b6fe0e0bae3
4f21bf73c0e9b2de11f08c5be1247140ea56dd5b
/Code/Libraries/Core/src/simplestring.h
33c21cf554416664a56b7d30d89f0daf95ea0a45
[ "Zlib" ]
permissive
BMG-Software/mEldritch
f3acf8c13a5195a566753ce1453443cfe9afdabe
7d07a845b3f04242ddf1f0abbad606c830ac8f20
refs/heads/master
2021-07-12T20:23:42.320087
2019-01-15T20:12:08
2019-01-15T20:12:08
164,134,410
1
0
null
null
null
null
UTF-8
C++
false
false
3,615
h
#ifndef SIMPLESTRING_H #define SIMPLESTRING_H #include "array.h" typedef uint32 unicode_t; // Represents a single Unicode code point in 4 bytes class SimpleString { public: explicit SimpleString( bool NoInit ); // To prevent static scope strings from being initialized with the wrong allocator SimpleString( const char* pString = "" ); SimpleString( const char* pNonTerminatedString, uint Length ); SimpleString( const SimpleString& String ); SimpleString( const Array<char>& String ); // Be careful, the array must be null-terminated ~SimpleString(); SimpleString& operator=( const SimpleString& String ); SimpleString& operator=( const char* pString ); SimpleString& operator=( const Array< char >& String ); // Be careful that the array might not be null-terminated SimpleString operator+( const SimpleString& String ) const; SimpleString& operator+=( const SimpleString& String ); bool operator==( const SimpleString& String ) const; bool operator!=( const SimpleString& String ) const; bool operator<( const SimpleString& String ) const; bool StrICmp( const SimpleString& String ) const; bool StrILt( const SimpleString& String ) const; const char* CStr() const; char* MutableCStr(); uint Length() const; // Doesn't include the terminating null char GetChar( uint Index ) const { ASSERT( Index < m_Length ); return m_String[ Index ]; } bool Contains( const SimpleString& String ) const; bool BeginsWith( const SimpleString& String ) const; void Replace( const char Char, const char ReplaceChar ) const; SimpleString Replace( const char* const Find, const char* const Replace ) const; SimpleString Replace( uint Index, const char* const Replace ) const; void SplitFind( const char Delimiter, SimpleString& Left, SimpleString& Right ) const; // Split at the first instance of Delimiter void Split( uint Index, SimpleString& Left, SimpleString& Right ) const; uint Find( const char* Find ) const; bool AsBool() const; int AsInt() const; float AsFloat() const; void FillArray( Array<char>& OutArray, bool WithNull = false ) const; // Clears and fills given array, optionally including terminating null void UTF8ToUnicode( Array<unicode_t>& OutUnicode ) const; // Converts string (assumed in UTF-8 form without BOM) to an array of Unicode code points static SimpleString SetUTF8( const Array<unicode_t>& Unicode ); // Converts array of Unicode code points to UTF-8 form unicode_t GetCodePoint() const; // Converts string (assumed in "U+xxxx" form) to a Unicode code point static SimpleString GetCodePointString( const unicode_t CodePoint ); // Returns "U+xxxx" form SimpleString EscapeSequenceEncode() const; SimpleString URLEncode() const; SimpleString URLEncodeUTF8() const; SimpleString ToLower() const; static SimpleString PrintF( const char* FormatString, ... ); static SimpleString PrintF( const SimpleString FormatString, ... ); static void InitializeAllocator( uint Size ); static void ShutDownAllocator(); static void ReportAllocator( const SimpleString& Filename ); private: void Initialize( const char* pString ); void InitializeNonTerminated( const char* pString, uint Length ); static char* Allocate( uint Size ); static Allocator& GetAllocator( uint Size ); char* m_String; uint m_Length; // Doesn't include the terminating null! static Allocator m_AllocatorSmall; static Allocator m_AllocatorLarge; static bool m_UsingAllocator; }; #endif // SIMPLESTRING_H
[ "merc96github@gmail.com" ]
merc96github@gmail.com
ef80a9f2b8c335e74a6637611b57f5a077e6e9e5
38f5b7ef3ce514a970db6b404f5635628867a999
/OItemTorch3.h
4a40c94d634094b48f313d700b2039417313795e
[]
no_license
Shinyj/Crypt-of-the-NecroDancer
3465ff02ec131253d7e5941d508ba1845fe2f415
8760a7b9adc9b0f9aca258e12f5e7d73d067ebaa
refs/heads/master
2020-03-30T08:25:21.481320
2018-10-01T00:01:55
2018-10-01T00:01:55
151,013,897
0
0
null
null
null
null
UTF-8
C++
false
false
238
h
#pragma once #include "ItemBase.h" class OItemTorch3 : public ItemBase { public: OItemTorch3(); ~OItemTorch3(); HRESULT Init(string key, int pos, ITEMKIND kind); void Release(); void Update(); void Render(); void ShowInfo(); };
[ "shinyj25@naver.com" ]
shinyj25@naver.com
39a3d6111f5ea0c6d90243d53f12c381b8454451
f80d19d58816c14cf51b6457d017ccb1b01918ea
/src/game/gameState.cpp
8f695999d7a9b09bc172879d2912f24b67c140f9
[]
no_license
piochelepiotr/minecraftClone
378a277d88d35ab36f1ef517598800b99355e6c5
c4389f5f4f7a8164658e7943050119a0508dcd00
refs/heads/master
2021-05-11T02:53:44.298323
2018-11-03T02:24:20
2018-11-03T02:24:20
117,897,006
0
1
null
null
null
null
UTF-8
C++
false
false
200
cpp
#include "gameState.h" GameState::GameState() : m_paused(false) { } GameState::~GameState() { } void GameState::pause() { m_paused = true; } void GameState::play() { m_paused = false; }
[ "piotr.wolski@telecom-paristech.fr" ]
piotr.wolski@telecom-paristech.fr
c8f0b55eff498aa480971b4f1f177ae8d672bb2a
473fc28d466ddbe9758ca49c7d4fb42e7d82586e
/app/src/main/java/com/syd/source/aosp/cts/tests/sensor/jni/nativeTestHelper.cpp
3c7df9a3186242342c3c36af2a17f334fd1da870
[]
no_license
lz-purple/Source
a7788070623f2965a8caa3264778f48d17372bab
e2745b756317aac3c7a27a4c10bdfe0921a82a1c
refs/heads/master
2020-12-23T17:03:12.412572
2020-01-31T01:54:37
2020-01-31T01:54:37
237,205,127
4
2
null
null
null
null
UTF-8
C++
false
false
1,555
cpp
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "nativeTestHelper.h" #include <cstdlib> #include <cstring> extern int register_android_hardware_cts_SensorNativeTest(JNIEnv* env); extern int register_android_hardware_cts_SensorDirectReportTest(JNIEnv* env); void fail(JNIEnv* env, const char* format, ...) { va_list args; va_start(args, format); char *msg; vasprintf(&msg, format, args); va_end(args); jclass exClass; const char *className = "java/lang/AssertionError"; exClass = env->FindClass(className); env->ThrowNew(exClass, msg); free(msg); } jint JNI_OnLoad(JavaVM *vm, void *) { JNIEnv *env = NULL; if (vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK) { return JNI_ERR; } if (register_android_hardware_cts_SensorNativeTest(env)) { return JNI_ERR; } if (register_android_hardware_cts_SensorDirectReportTest(env)) { return JNI_ERR; } return JNI_VERSION_1_4; }
[ "997530783@qq.com" ]
997530783@qq.com
dfcb580e94498a90b27120ceca22a453eb4fee67
9472221ec7da4395f0cd3845e56fee58e785a2be
/Dungeon Game.cc
b3022f84245fc0b8b0689da68d5634c307c353d0
[]
no_license
TraceBundy/leetcode
cf31cb1bb792ee07ab55c2bf659bf478a653343f
5f44e97ccf4c2c36b412adc2a3410deb68fc0aa9
refs/heads/master
2020-06-29T03:04:22.254725
2015-06-28T14:23:12
2015-06-28T14:23:12
32,430,048
0
0
null
null
null
null
UTF-8
C++
false
false
722
cc
class Solution { public: int calculateMinimumHP(vector<vector<int>>& dungeon) { int n = dungeon.size(); int m = dungeon[0].size(); dungeon[n-1][m-1] = max(1, -dungeon[n-1][m-1]+1); for (int i = m-2; i >= 0; --i){ dungeon[n-1][i] = max(1, -dungeon[n-1][i] + dungeon[n-1][i+1]); } for (int j = n-2; j >= 0; --j){ dungeon[j][m-1] = max(1, -dungeon[j][m-1] + dungeon[j+1][m-1]); } for (int i = n-2; i >= 0; --i){ for (int j = m-2; j >= 0; --j){ dungeon[i][j] = max(1, -dungeon[i][j] + min(dungeon[i+1][j], dungeon[i][j+1])); } } return dungeon[0][0]; } };
[ "yangzhou221@gmail.com" ]
yangzhou221@gmail.com
f688bfcd71dd8abf79837e0d8e9613a382ec5560
426be981352881138c26492c0cdc1107a9c0afa4
/arbi/src/main.cpp
dea037a492fffe368efc4bad6d1c242f74574137
[]
no_license
OverfittingStudyRoom/x-trader
491910f7284913330c4afac767c3c00893a9b9ba
247d1043bbb98ee7d53b5de447904ebde186093c
refs/heads/master
2023-03-31T13:01:38.097797
2020-03-12T12:29:37
2020-03-12T12:29:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,426
cpp
#include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <dlfcn.h> #include <string> #include <signal.h> /* signal */ #include "vrt_value_obj.h" #include "l1md_producer.h" #include "fulldepthmd_producer.h" #include "tunn_rpt_producer.h" #include "uni_consumer.h" #include "pos_calcu.h" /* Note that the parameter for queue size is a power of 2. */ #define QUEUE_SIZE 32768 UniConsumer *uniConsumer = NULL; FullDepthMDProducer *fulldepth_md_producer = NULL; L1MDProducer *l1_md_producer = NULL; TunnRptProducer *tunnRptProducer = NULL; static void SIG_handler(int s) { uniConsumer->Stop(); //exit(0); /* call exit for the signal */ } int main(/*int argc, const char **argv*/) { // clog setting CLOG_LEVEL_WARNING clog_set_minimum_level(CLOG_LEVEL_INFO); FILE *fp;/*文件指针*/ fp=fopen("./x-trader.log","w+"); Log::fp = fp; struct clog_handler *clog_handler = clog_stream_handler_new_fp(fp, true, "%l %m"); clog_handler_push_process(clog_handler); #ifdef LATENCY_MEASURE clog_warning("latency measure on"); #else clog_warning("latency measure off"); #endif #ifdef COMPLIANCE_CHECK clog_warning("COMPLIANCE_CHECK on"); #else clog_warning("COMPLIANCE_CHECK off"); #endif #ifdef PERSISTENCE_ENABLED clog_warning("PERSISTENCE_ENABLED on"); #else clog_warning("PERSISTENCE_ENABLEDon off"); #endif struct sigaction SIGINT_act; SIGINT_act.sa_handler = SIG_handler; sigemptyset(&SIGINT_act.sa_mask); SIGINT_act.sa_flags = 0; sigaction(SIGUSR2, &SIGINT_act, NULL); // version clog_warning("version:arbi_2019-2-17_r"); clog_warning("max contract count:%d",MAX_CONTRACT_COUNT ); struct vrt_queue *queue; int64_t result; rip_check(queue = vrt_queue_new("x-trader queue", vrt_hybrid_value_type(), QUEUE_SIZE)); tunnRptProducer = new TunnRptProducer(queue); fulldepth_md_producer = new FullDepthMDProducer(queue); l1_md_producer = new L1MDProducer(queue); uniConsumer = new UniConsumer (queue, fulldepth_md_producer, l1_md_producer, tunnRptProducer); uniConsumer->Start(); fflush (fp); // free vrt_queue vrt_queue_free(queue); delete uniConsumer; delete tunnRptProducer; delete l1_md_producer; delete fulldepth_md_producer; // clog: free resources pos_calc::destroy_instance(); clog_handler_free(clog_handler); return 0; }
[ "17199883@qq.com" ]
17199883@qq.com
05cf9e9202304b0cc7f0383efcb9425168622a2f
85077dea5952092816634cd992378180d95f1135
/src/Objects3D/Objects3D.h
8a5bfd3b54edbfdeea80f6578c788d49d60e0b56
[ "MIT" ]
permissive
aurelijusb/webcam-games
e4a7f1bf089238e9ddc581e00c11433142d38410
cced15d3decdba637c41d1620a97e0a4f8ec3cb0
refs/heads/master
2021-01-13T14:05:43.121609
2017-02-03T13:34:42
2017-02-03T13:34:42
76,173,651
3
0
null
null
null
null
UTF-8
C++
false
false
2,292
h
#ifndef OBJECTS3D_H #define OBJECTS3D_H #include <string> #include <vector> #define RANGE(variable, min, max) {if ((variable) < (min)) (variable) = (min); if ((variable > max)) (variable) = max; } using namespace std; /* * OpenGl related objects. */ namespace Objects3D { enum applyType { FRONT, BACK, FRONT_AND_BACK }; class Material { public: Material(const string &name, float ambient[], float diffuse[], float specular[], float emition[], float shininess = 0); const string &name(); const void apply(applyType type = FRONT_AND_BACK); ~Material(); static const Material *getMaterialByName(const vector<Material*> &materialStorage, const string &name); protected: string materialName; float ambient[4]; float diffuse[4]; float specular[4]; float emition[4]; float shininess; }; class Object3D { public: Object3D(const string &name, float *vertixes, int nv, float *facesNormals, int nfn, int *triangles, int nf, int *normals, Material *material, bool freeVertixDataOnDestruct = true); const string &name(); void render(); ~Object3D(); protected: string modelName; float *vertixes; int nv; float *facesNormals; int nfn; int *triangles; int nf; int *normals; Material *material; bool freeVertixDataOnDestruct; }; void importFromObj(const string directory, const string fileName, vector<Object3D*> &objectStorage, vector<Material*> &materialStorage); void importFromMtl(const string directory, const string fileName, vector<Material*> &materialStorage); Material *getMaterialByName(const vector<Material*> &materialStorage, const string &name); } #endif /* OBJECTS3D_H */
[ "aurelijus@banelis.lt" ]
aurelijus@banelis.lt
a089546bdad1e4c2272860effb377b0b14083140
8bd30da01c1f22f9c360153311b429b7ce65980b
/PortSIPUC/db/AVCodec.cpp
e210bdb7ec278b2cdd69774532adb403dd83d1fc
[ "BSD-2-Clause" ]
permissive
jiaojian8063868/portsip-softphone-windows
33adf93c21b97a684219d4cc3bf5cad3ea14b008
df1b6391ff5d074cbc98cb559e52b181ef8e1b17
refs/heads/master
2022-11-19T20:22:40.519351
2020-07-24T04:06:23
2020-07-24T04:06:23
282,122,371
1
2
BSD-2-Clause
2020-07-24T04:26:24
2020-07-24T04:26:23
null
UTF-8
C++
false
false
267
cpp
#include "stdafx.h" #include "AVCodec.h" CAVCodec::CAVCodec() { m_nAVCodecID = 0; m_nItemIndex = 0 ; m_nCodecCode = 0; m_nAVCodecType= ENUM_VA_CODEC_VIDEO; m_strCodecName=""; m_strReserved=""; m_bAVCodecOpen = false; } CAVCodec::~CAVCodec() { }
[ "122019077@qq.com" ]
122019077@qq.com
2cd7fe3d9d62f57f04d89ec20c1f33fe8e01445c
f5cd4aa57470c77530f83ae0fdad58c9ceb865b4
/tests/performance_tests/is_out_to_acc.h
18d69cd2fb6af4599e1997f737fbea5554c4e37b
[ "BSD-3-Clause" ]
permissive
weirdboy79/fonero
4ff23ddeb4b53cb8f4d5029e85b31ee07685648d
80d5aa64b4a7329222954d504e5d99e3fdd48159
refs/heads/master
2020-03-10T07:38:57.850114
2018-04-11T15:31:50
2018-04-11T15:31:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,309
h
// Copyright (c) 2017-2018, The Fonero Project. // Copyright (c) 2014-2017 The Fonero Project. // Portions Copyright (c) 2012-2013 The Cryptonote developers. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #pragma once #include "cryptonote_basic/account.h" #include "cryptonote_basic/cryptonote_basic.h" #include "cryptonote_core/cryptonote_tx_utils.h" #include "single_tx_test_base.h" class test_is_out_to_acc : public single_tx_test_base { public: static const size_t loop_count = 1000; bool test() { const cryptonote::txout_to_key& tx_out = boost::get<cryptonote::txout_to_key>(m_tx.vout[0].target); return cryptonote::is_out_to_acc(m_bob.get_keys(), tx_out, m_tx_pub_key, 0); } };
[ "dev@fonero.org" ]
dev@fonero.org
7bc8b28812abe8f34c341a4941605252dee6f2b3
977c82ec23f2f8f2b0da5c57984826e16a22787d
/src/IceRay/main/interface/python/core/light/type_Spot.cpp
fe8b16884536fd8584c49e37a2b48eb99ea3a948
[ "MIT-0" ]
permissive
dmilos/IceRay
47ce08e2920171bc20dbcd6edcf9a6393461c33e
84fe8d90110c5190c7f58c4b2ec3cdae8c7d86ae
refs/heads/master
2023-04-27T10:14:04.743094
2023-04-20T14:33:45
2023-04-20T15:07:18
247,471,987
2
1
null
null
null
null
UTF-8
C++
false
false
1,942
cpp
#include "../../def_submodule.hpp" #include "../../../../../light/_pure.hpp" typedef GS_DDMRM::S_IceRay::S_type::GT_scalar GTs_scalar; typedef GS_DDMRM::S_IceRay::S_type::S_color::GT_scalar GTs_color; typedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_scalar3D GTs_coord3D; typedef GS_DDMRM::S_IceRay::S_light::S_type::GC_spot GTs_spot; void expose_IceRay_light_type_Spot() { //MAKE_SUBMODULE( IceRay ); MAKE_SUBMODULE( core ); MAKE_SUBMODULE( light ); MAKE_SUBMODULE( type ); typedef GTs_coord3D const& (GTs_spot::*Tf_getCenter )(void) const; typedef bool (GTs_spot::*Tf_setCenter )(GTs_coord3D const&); Tf_getCenter I_getCenter = &GTs_spot::F_center; Tf_setCenter I_setCenter = &GTs_spot::F_center; typedef GTs_color const& (GTs_spot::*Tf_getColor )(void) const; typedef bool (GTs_spot::*Tf_setColor )(GTs_color const&); Tf_getColor I_get0 = &GTs_spot::F_0; Tf_setColor I_set0 = &GTs_spot::F_0; Tf_getColor I_get1 = &GTs_spot::F_1; Tf_setColor I_set1 = &GTs_spot::F_1; Tf_getColor I_get2 = &GTs_spot::F_2; Tf_setColor I_set2 = &GTs_spot::F_2; boost::python::class_<GTs_spot> ( "LightTypeSpot" ) .def( boost::python::init<>() ) .def( boost::python::init<GTs_coord3D>() ) .def( boost::python::init<GTs_coord3D,GTs_color,GTs_color,GTs_color>() ) .def( "center", I_getCenter, boost::python::return_value_policy<boost::python::copy_const_reference>() ) .def( "center", I_setCenter ) .def( "_0", I_get0, boost::python::return_value_policy<boost::python::copy_const_reference>() ) .def( "_0", I_set0 ) .def( "_1", I_get1, boost::python::return_value_policy<boost::python::copy_const_reference>() ) .def( "_1", I_set1 ) .def( "_2", I_get2, boost::python::return_value_policy<boost::python::copy_const_reference>() ) .def( "_2", I_set2 ) ; }
[ "dmilos@gmail.com" ]
dmilos@gmail.com
f60a8f600dd407be246b139992835eaf7bf65211
1d93e125bcdbe8997c8f2a0490c470d607a96e3f
/ivf_pq/ivf_assign.h
5da5498a285903ae412a7cab548e01ff2f0cdcad
[]
no_license
FernandesAff/ppqanns-server
6b3089854f3ea8a306f6cca7d6513d00a4a6f2f2
3e1e69f32544f3c635087956d23c06ea42f0b8a5
refs/heads/master
2022-11-22T15:26:04.281058
2020-07-30T00:54:58
2020-07-30T00:54:58
283,633,813
0
0
null
null
null
null
UTF-8
C++
false
false
698
h
#ifndef H_IVFASSIGN #define H_IVFASSIGN #include <stdio.h> #include <stdlib.h> #include <mpi.h> extern "C"{ #include "../yael/nn.h" } #include "../pq-utils/pq_test_load_vectors.h" #include "../pq-utils/pq_new.h" #include "myIVF.h" #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <cstdint> #define MAX_BUF 1024 #define PORT 8001 #define SA struct sockaddr void parallel_assign (char *dataset, int w, int comm_sz, MPI_Comm search_comm, int threads); void bsxfunMINUS(float *mout, mat vin, float* vin2, int nq, int* qcoaidx, int ncoaidx); mat pq_test_receive_query(char *dataset, int sockfd); #endif
[ "andrefernandesf@gmail.com" ]
andrefernandesf@gmail.com
8b68e8d47e9c0f08dbe7d7f35cf1733d9a6d9786
2fa31ae8d02cd92bf24bd8cf0f2a611a02a28519
/since2018/integrated_algorithm/2015.cpp
6efab38f67670a05a48043618cf19cb5756f3c09
[]
no_license
dlftls38/algorithms
3619186d8d832cda695dfbf985e5d86ef6f2f06e
18ab96bbb3c8512a2da180477e4cc36a25edd30d
refs/heads/master
2021-07-10T06:09:53.211350
2020-10-17T00:04:43
2020-10-17T00:04:43
206,953,967
0
0
null
null
null
null
UTF-8
C++
false
false
585
cpp
#include <stdio.h> #include <iostream> #include <string.h> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <map> #include <limits.h> #include <functional> #include <math.h> #include <fstream> using namespace std; int psum[200000]; int main(){ int n,k; scanf("%d%d",&n,&k); int i,j; for(i=0;i<n;i++){ int x; scanf("%d",&x); psum[i]=x; if(i>0){ psum[i]+=psum[i-1]; } } map<int,int>m; long long ans=0; for(i=0;i<n;i++){ if(psum[i]==k){ ans++; } ans+=m[psum[i]-k]; m[psum[i]]++; } printf("%lld",ans); }
[ "dlftls38@naver.com" ]
dlftls38@naver.com
6a79379c89a0c8d909ec2a425b2ae935bd910469
d16985a72e39109c30b1e975007cc1cabe8a6ac8
/Server/Server/Item/HumanItemContainer.h
b020aa20553b801cdc19b052accceac58c1dd946
[]
no_license
uvbs/wx2Server
e878c3c5c27715a0a1044f6b3229960d36eff4b4
78a4b693ac018a4ae82e7919f6e29c97b92554ab
refs/heads/master
2021-01-18T00:06:34.770227
2013-12-13T09:18:54
2013-12-13T09:18:54
43,288,843
2
3
null
2015-09-28T08:24:45
2015-09-28T08:24:44
null
UTF-8
C++
false
false
4,781
h
// 增加了处理宝石镶嵌以及物品属性加减的函数,fancy #ifndef _HUMAN_ITEM_CONTAINER_H_ #define _HUMAN_ITEM_CONTAINER_H_ #include "ItemContainer.h" class HumanDB; struct _HUMAN_ITEMCONTAINER_INIT: public _ITEMCONTAINER_INIT { HumanDB* m_pHumanDB; ITEM_CONTAINER_TYPE m_ICTType; UINT m_DBOffSet; }; class Obj_Human; class HumanItemContainer:public ItemContainer { HumanDB* m_pHumanDB; ITEM_CONTAINER_TYPE m_ICTType; UINT m_DBOffSet; public: virtual BOOL Init( const _ITEMCONTAINER_INIT* pInit ) ;//初始化容器 //容器编号到Bag编号 virtual UINT ConIndex2BagIndex(UINT uConIndex); //背包编号到容器编号 virtual UINT BagIndex2ConIndex(UINT uBagIndex); //测试传入的一个值是不是能够在这个Con的范围之中 virtual BOOL IsInContainer(UINT uBagIndex); //扩展大小 virtual BOOL ExpandContainerSize(UINT uSzie); //设置大小 virtual BOOL SetContainerSize(UINT uSzie); virtual INT GetContainerType(); protected : /* * 物品 使用方法 */ //设置物品的属性 virtual BOOL SetItem( const INT nIndex, const Item* pItem ); //设置物品重叠数量 virtual BOOL SetItemLayCount(INT nIndex, INT nCount) ; //减少物品重叠数量 virtual BOOL DecItemLayCount(INT nIndex, INT nCount=1) ; //增加物品重叠数量 virtual BOOL IncItemLayCount(INT nIndex, INT nCount=1); //删除物品 virtual BOOL EraseItem(UINT uIndex); //设置物品耐久度 virtual BOOL SetItemDur(INT nIndex, INT nDur); //设置物品损伤点 virtual BOOL SetItemDamagePoint(INT nIndex, INT nPoint); //设置物品最大耐久度 virtual BOOL SetItemMaxDur(INT nIndex, INT nDur); //设置物品耐久度 virtual BOOL SetItemCurMaxDur(INT nIndex, INT nDur); //设置物品属性 virtual BOOL SetItemValue(INT nIndex,_ITEM* pItem); //设置物品帮定 virtual BOOL SetItemBind(INT nIndex); //设置物品鉴定信息 virtual BOOL SetItemIdent(INT nIndex); //设置制造者信息 virtual BOOL SetItemCreator(INT nIndex,const CHAR* CreatorName); //增加物品属性 virtual BOOL AddItemAttr(INT nIndex,_ITEM_ATTR iA); //删除物品属性 virtual BOOL DelItemAttr(INT nIndex,_ITEM_ATTR iA); //删除宝石信息 virtual BOOL DelGemInfo(INT nIndex,INT GemIndex); //添加宝石信息 virtual BOOL AddGemInfo(INT nIndex,INT& GemIndex,UINT GemType); protected : /* * PET 使用方法 */ virtual INT GetIndexByGUID( const PET_GUID_t* pGuid ); //设置物品GUID virtual BOOL SetItemGuid(INT nIndex,PET_GUID_t* pGUID); //设置PET 属性 //设置物品属性 virtual BOOL SetItemValue(INT nIndex,const _PET_DB_LOAD* pPet); virtual BOOL SetPetGUID(INT nIndex,PET_GUID_t GUID) ; //设置宠物GUID virtual BOOL SetSpouseGUID(INT nIndex,PET_GUID_t GUID) ; //设置宠物配偶GUID virtual BOOL SetDataID(INT nIndex,INT ID); //设置宠物模型 virtual BOOL SetName(INT nIndex,const CHAR* pName); //设置名字 virtual BOOL SetNick(INT nIndex,const CHAR* pNick); //设置昵称 virtual BOOL SetLevel(INT nIndex,INT level); //设置等级 virtual BOOL SetTakeLevel(INT nIndex,INT takeLevel); //设置携带等级 virtual BOOL SetAttackType(INT nIndex,INT attackType); //设置进攻类型(物/法) virtual BOOL SetAIType(INT nIndex,INT AIType); //设置AI类型 virtual BOOL SetCampData(INT nIndex,const _CAMP_DATA* pCamp); //设置阵营 virtual BOOL SetPetType(INT nIndex,BYTE PetType); //宝宝,变异,野生 virtual BOOL SetGeneration(INT nIndex,BYTE Gen); //几代宠 virtual BOOL SetHappiness(INT nIndex,BYTE byHappiness); //快乐度 virtual BOOL SetStrengthPer(INT nIndex,INT strper); //力量资质 virtual BOOL SetSmartnessPer(INT nIndex,INT conper); //敏捷资质 virtual BOOL SetMindPer(INT nIndex,INT dexper); //智力资质 virtual BOOL SetConstitutionPer(INT nIndex,INT intper); //体质资质 virtual BOOL SetGenGu(INT nIndex,INT gengu); //根骨 virtual BOOL SetSavvy(INT nIndex,INT iSavvy); //悟性 virtual BOOL SetGrowRate(INT nIndex,FLOAT rate); //成长率 virtual BOOL SetRemainPoint(INT nIndex,INT rPoint); //一级属性剩余点数 virtual BOOL SetExp(INT nIndex,INT exp) ; //经验值 virtual BOOL SetLvl1Attr(INT nIndex,CHAR_ATTR_LEVEL1 type,INT value);//基础一级战斗属性(不包括技能和装备增加的部分) virtual BOOL SetSkill(INT nIndex,UINT SkillIndex,_PET_SKILL skill); //宠物技能 private: BOOL SetDBDirty(INT OffSet); }; #endif
[ "tangming032@outlook.com" ]
tangming032@outlook.com
27d4af3dd15bae0250a27e576ba3a4d60f669e95
f4db3fa275cf032eaa0c1db657c23a36d7e62577
/engine/src/PhysicsFacet.hpp
f323a33ade858b1d8af50842d69db40073207533
[ "MIT" ]
permissive
skryabiin/core
0e5f7af0c08ebd0118466b5b21023914820eb442
13bcdd0c9f3ebcc4954b9ee05ea95db0f77e16f7
refs/heads/master
2016-09-05T14:46:03.261125
2016-03-02T16:01:56
2016-03-02T16:01:56
34,462,571
0
0
null
null
null
null
UTF-8
C++
false
false
639
hpp
#ifndef CORE_PHYSICS_FACET_HPP #define CORE_PHYSICS_FACET_HPP #include "PositionFacet.hpp" #include "Geometry.hpp" #include "CollisionState.hpp" namespace core { struct PhysicsFacet : public PositionFacet { PhysicsFacet() : PositionFacet{}, velocity{ 0.0f, 0.0f }, acceleration{ 0.0f, 0.0f }, mass{ 1.0f }, proposedMove{ 0, 0, 0 }, microMove{ 0.0f, 0.0f }, blocking{ false }, fixed{ true } { _typeInfo = &typeid(*this); }; Vec2 velocity; Vec2 acceleration; float mass; bool blocking; bool fixed; Pixel proposedMove; Vec2 microMove; CollisionState collisionState; }; } //end namespace core #endif
[ "jlynem@gmail.com" ]
jlynem@gmail.com
85bfc9c41498f355483a3e08af6c28463f1b3fa2
805e83058e2cb1c4042fe31a0c5f2aacf76eca63
/Glanda/PagePublishFinished.cpp
cd0f25c5e0b9e168d2253f917c39195c5c5f40d2
[]
no_license
progmalover/vc-stgld
70ee037f3f27857fcdbb344b5ee8533c724b43b9
96055b2a2deca44eed5bb2c6e1e3f6cb1aff3a6b
refs/heads/master
2021-01-12T05:17:05.334966
2017-01-12T14:49:44
2017-01-12T14:49:44
77,895,327
0
0
null
null
null
null
UTF-8
C++
false
false
978
cpp
// PagePublishFinished.cpp : implementation file // #include "stdafx.h" #include "Glanda.h" #include "PagePublishFinished.h" #include ".\pagepublishfinished.h" // CPagePublishFinished dialog IMPLEMENT_DYNAMIC(CPagePublishFinished, CPropertyPageFixed) CPagePublishFinished::CPagePublishFinished() : CPropertyPageFixed(CPagePublishFinished::IDD) { Construct(IDD, IDS_PUBLISH, IDS_PUBLISH_FINISHED, 0); } CPagePublishFinished::~CPagePublishFinished() { } void CPagePublishFinished::DoDataExchange(CDataExchange* pDX) { CPropertyPageFixed::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CPagePublishFinished, CPropertyPageFixed) END_MESSAGE_MAP() // CPagePublishFinished message handlers BOOL CPagePublishFinished::OnSetActive() { // TODO: Add your specialized code here and/or call the base class ((CPropertySheet *)GetParent())->SetWizardButtons(PSWIZB_FINISH); CancelToClose(); return CPropertyPageFixed::OnSetActive(); }
[ "zhangxiangyang@os-easy.com" ]
zhangxiangyang@os-easy.com
e3296d6b5239a19280955341696e100e793a77e2
af90747e92927adeb0104aa2a120fed8a0c2545e
/cs231/C++ Programs/CString Trial.cpp
14a3f68f8ced737bb864ffa027028ecc611a0651
[]
no_license
SuchFNS/kettering
0952f745f9becad2a7945b6300ae99fad8217a6d
0398af4d11dfe0bc1a52adb8676311126288dd50
refs/heads/master
2023-08-16T02:44:12.697423
2021-09-30T17:05:49
2021-09-30T17:05:49
388,840,514
0
0
null
null
null
null
UTF-8
C++
false
false
1,483
cpp
#include <iostream> using namespace std; //prototypes int length(char[]); void capitals(char[]); void findVowels(char[], int, int&, int&, int&, int&, int&); int main(){ int a, e, i, o, u; const int SIZE = 51; char sentence[SIZE]; //ask for input cout << "Please input a sentence no longer than 50 characters.\n"; cin.getline(sentence, SIZE); //call for sentence character length int count = length(sentence); cout << count << " characters long\n"; //call for capitalizing each letter //calls to find the vowels findVowels(sentence, count, a, e, i, o, u); cout << a << " times entered 'A\n"; cout << e << " times entered 'E'\n"; cout << i << " times entered 'I'\n"; cout << o << " times entered 'O'\n"; cout << u << " times entered 'U'\n"; return 0; } //finds the length of the array int length(char sentence[]){ int i = 0; while (sentence[i] != '\0'){ i++; } return i; } //capitalizes every letter void capitals(char sentence[]){ int i = 0; while (sentence != '\0'){ if (sentence[i] >= 97 && sentence[i] <= 122) i++; } } //Finds the vowels void findVowels(char sentence[], int count, int& a, int& e, int& i, int& o, int& u){ int c = 0; while (sentence != '\0'){ if (sentence[c] == 'a'){ a++; }else if (sentence[c] == 'e'){ e++; }else if (sentence[c] == 'i'){ i++; }else if (sentence[c] == 'o'){ o++; }else if (sentence[c] == 'u'){ u++; } } }
[ "colinq613@gmail.com" ]
colinq613@gmail.com
a4c3e4620ccb9528821c0f89f8e27c1e2e7ed650
d3dd666a9823e0df316804b5422c10050e796a57
/Server/src/Ressource/NoMovement.cpp
11120ecf375c19e83af3e8ab07940638aca0dee2
[]
no_license
Surrog/airtipe
0b1d3bc8a8705ef93af35b0b9ddfb72f3e938aa6
a44043df83f8be3f5b116d262af9818fdadee562
refs/heads/master
2021-01-15T19:22:41.519880
2010-07-20T16:11:49
2010-07-20T16:11:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
545
cpp
/*! * \file NoMovement.cpp * \brief Implementation of NoMovement class * \author Francois Ancel - ancel_a@epitech.eu * \version 0.1 * \date July 16, 2010 1:41 PM */ #include "NoMovement.h" NoMovement::NoMovement(const Position& init, const Position&, const int) : MovementPolicy(init) { } const MovementType NoMovement::GetMovementType() const { return ::NoMovement; } const Position NoMovement::GetPositionAt(mtime&) const { return _posInit; } const Position NoMovement::GetPosition() const { return _posInit; }
[ "FrancoisAncel@32e6bcfa-9e84-7d95-9935-f22b4b10203c" ]
FrancoisAncel@32e6bcfa-9e84-7d95-9935-f22b4b10203c
2abd7ee171ecf2387ae2430a5ba20ee176b4212b
807a97a8137b9cb99a56a9756e1b7e47acf99361
/FCCmdSmartLayerBase.h
be805b09c054d41a52b0146d400712328579eb77
[]
no_license
lupnfer/camc
f54a11b9545c46467aee82a3151107eb57ff2b5a
baf09c4d8a81fdbc2d9362aab384b4d71bf924de
refs/heads/master
2021-01-10T07:42:09.063247
2013-03-05T03:08:15
2013-03-05T03:08:15
null
0
0
null
null
null
null
GB18030
C++
false
false
891
h
#pragma once #include "Objbase.h" #include "ObjImage.h" class FCObjLayer ; class FCCmdSmartLayerBase : public FCCmdArtPrider { public : FCCmdSmartLayerBase () : m_pLayer(NULL), m_pCanvas(NULL), m_bSaveAll(TRUE) {} virtual void Execute (FCObjCanvas & canvas, FCObjProgress * Percent = NULL) ; virtual void Undo () ; virtual void Redo () ; virtual void Implement (FCObjImage & img, FCObjProgress * Percent = NULL) {} protected : virtual void QuerySaveRect (RECT * prcSave) const ; virtual void OnPrepareBlockRect (const RECT & rcBlock) {} // 收到block位于图层的位置 virtual void OnAfterGrowLayer (int nLeft, int nTop, int nRight, int nBottom) {} ; public: FCObjLayer * m_pLayer ; protected : FCObjCanvas * m_pCanvas ; FCObjImage m_Undo ; FCObjImage m_Redo ; BOOL m_bSaveAll ; // 是否保存了整个图层 RECT m_rcSave ; // m_pLayer保存的区域 };
[ "lupnfer@yahoo.com.cn" ]
lupnfer@yahoo.com.cn
5575388b308dd29c23019f467dd4eadb15543147
7e91191b5b45f2e3d189abb8b7fbcd7f3fcc06c4
/gecode/minimodel/int-rel.cpp
340da1ace2b4d6a486186b84857498c2c5ba87f8
[ "MIT" ]
permissive
eatstreet/gecode
dbed8eb132d2dc5d667950cb1e27b52ffcecb58f
b16d00b209bba8602233a087be50d2d11ddba5fa
refs/heads/master
2021-09-05T21:56:54.799005
2017-05-18T17:33:08
2017-05-18T17:33:08
79,236,291
1
0
NOASSERTION
2021-08-05T22:46:03
2017-01-17T14:37:18
C++
UTF-8
C++
false
false
10,461
cpp
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Christian Schulte <schulte@gecode.org> * * Copyright: * Christian Schulte, 2005 * * Last modified: * $Date$ by $Author$ * $Revision$ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * 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 <gecode/minimodel.hh> namespace Gecode { /* * Construction of linear relations * */ LinIntRel operator ==(int l, const IntVar& r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(int l, const BoolVar& r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(int l, const LinIntExpr& r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(const IntVar& l, int r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(const BoolVar& l, int r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(const LinIntExpr& l, int r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(const IntVar& l, const IntVar& r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(const IntVar& l, const BoolVar& r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(const BoolVar& l, const IntVar& r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(const BoolVar& l, const BoolVar& r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(const IntVar& l, const LinIntExpr& r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(const BoolVar& l, const LinIntExpr& r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(const LinIntExpr& l, const IntVar& r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(const LinIntExpr& l, const BoolVar& r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator ==(const LinIntExpr& l, const LinIntExpr& r) { return LinIntRel(l,IRT_EQ,r); } LinIntRel operator !=(int l, const IntVar& r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(int l, const BoolVar& r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(int l, const LinIntExpr& r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(const IntVar& l, int r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(const BoolVar& l, int r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(const LinIntExpr& l, int r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(const IntVar& l, const IntVar& r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(const IntVar& l, const BoolVar& r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(const BoolVar& l, const IntVar& r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(const BoolVar& l, const BoolVar& r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(const IntVar& l, const LinIntExpr& r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(const BoolVar& l, const LinIntExpr& r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(const LinIntExpr& l, const IntVar& r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(const LinIntExpr& l, const BoolVar& r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator !=(const LinIntExpr& l, const LinIntExpr& r) { return LinIntRel(l,IRT_NQ,r); } LinIntRel operator <(int l, const IntVar& r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(int l, const BoolVar& r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(int l, const LinIntExpr& r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(const IntVar& l, int r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(const BoolVar& l, int r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(const LinIntExpr& l, int r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(const IntVar& l, const IntVar& r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(const IntVar& l, const BoolVar& r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(const BoolVar& l, const IntVar& r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(const BoolVar& l, const BoolVar& r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(const IntVar& l, const LinIntExpr& r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(const BoolVar& l, const LinIntExpr& r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(const LinIntExpr& l, const IntVar& r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(const LinIntExpr& l, const BoolVar& r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <(const LinIntExpr& l, const LinIntExpr& r) { return LinIntRel(l,IRT_LE,r); } LinIntRel operator <=(int l, const IntVar& r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(int l, const BoolVar& r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(int l, const LinIntExpr& r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(const IntVar& l, int r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(const BoolVar& l, int r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(const LinIntExpr& l, int r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(const IntVar& l, const IntVar& r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(const IntVar& l, const BoolVar& r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(const BoolVar& l, const IntVar& r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(const BoolVar& l, const BoolVar& r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(const IntVar& l, const LinIntExpr& r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(const BoolVar& l, const LinIntExpr& r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(const LinIntExpr& l, const IntVar& r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(const LinIntExpr& l, const BoolVar& r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator <=(const LinIntExpr& l, const LinIntExpr& r) { return LinIntRel(l,IRT_LQ,r); } LinIntRel operator >(int l, const IntVar& r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(int l, const BoolVar& r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(int l, const LinIntExpr& r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(const IntVar& l, int r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(const BoolVar& l, int r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(const LinIntExpr& l, int r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(const IntVar& l, const IntVar& r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(const IntVar& l, const BoolVar& r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(const BoolVar& l, const IntVar& r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(const BoolVar& l, const BoolVar& r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(const IntVar& l, const LinIntExpr& r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(const BoolVar& l, const LinIntExpr& r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(const LinIntExpr& l, const IntVar& r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(const LinIntExpr& l, const BoolVar& r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >(const LinIntExpr& l, const LinIntExpr& r) { return LinIntRel(l,IRT_GR,r); } LinIntRel operator >=(int l, const IntVar& r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(int l, const BoolVar& r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(int l, const LinIntExpr& r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(const IntVar& l, int r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(const BoolVar& l, int r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(const LinIntExpr& l, int r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(const IntVar& l, const IntVar& r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(const IntVar& l, const BoolVar& r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(const BoolVar& l, const IntVar& r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(const BoolVar& l, const BoolVar& r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(const IntVar& l, const LinIntExpr& r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(const BoolVar& l, const LinIntExpr& r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(const LinIntExpr& l, const IntVar& r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(const LinIntExpr& l, const BoolVar& r) { return LinIntRel(l,IRT_GQ,r); } LinIntRel operator >=(const LinIntExpr& l, const LinIntExpr& r) { return LinIntRel(l,IRT_GQ,r); } } // STATISTICS: minimodel-any
[ "schulte@gecode.org" ]
schulte@gecode.org
4d5bee182d5b1428926605aedff2aecb77638b13
3d2031186b655842a7a0d93a99b72af4ecddc0a5
/src/weapon/weapon_utility/health_pack.h
2925d8e3639318888f97ccfc1bbe8b3b5312a5df
[]
no_license
achau6/zombie-game
9572c471f05ab7f2f7d47ce005af58be0969b610
64bf89fd80f5f908f75ccdf5ab02d288e745dd90
refs/heads/master
2022-10-26T06:31:11.584255
2020-06-11T06:04:51
2020-06-11T06:04:51
256,340,445
1
1
null
null
null
null
UTF-8
C++
false
false
806
h
#ifndef HEALTH_PACK_H #define HEALTH_PACK_H #include "Entities/entity.h" #include <iostream> #include "player/player.h" /* Why I didn't make a class that Ammo and Health can inherit from. Double inheritance is probably not a good idea. */ class Health : public Entity { public: //constructors Health(); Entity h; //Mutators void Draw(sf::RenderWindow& window); void spawn_pack(sf::Vector2f position); void delete_health_pack(Player& player); bool collisionCheck(sf::RectangleShape rect, sf::RectangleShape pool); //accessors int GetSize(){return health_pack.size();} private: /* Made a pair that hold both a sprite and a shape. Map was not needed as we don't need a key */ std::vector<std::pair<sf::Sprite, sf::RectangleShape>> health_pack; sf::Texture texture; }; #endif // HEALTH_PACK_H
[ "phatpazy9@gmail.com" ]
phatpazy9@gmail.com
161fce7e9419729bc7a47d84681ba26c5893f5b2
96d0785777976c2b839b0eb93b3f8261b057d460
/Training/36.ttwo.cpp
d18ba7d8e18f5b3abea5d59fd83ba2043a497053
[ "MIT" ]
permissive
felikjunvianto/kfile-usaco-submissions
452b23ca82cd2c99d742d98124faadda580cc451
d4afdc0cbde7e19f09afc70c4b02d4bc5992696d
refs/heads/master
2020-05-29T08:50:56.764064
2016-10-06T19:21:17
2016-10-06T19:21:17
70,185,253
0
0
null
null
null
null
UTF-8
C++
false
false
2,484
cpp
/* ID: felikju1 PROG: ttwo LANG: C++ */ #include <cstdio> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <stack> #include <queue> #define fi first #define se second #define pb push_back #define mp make_pair using namespace std; typedef struct { int x,y,arah; } gerak; int hor[]={0,1,0,-1}; int ver[]={-1,0,1,0}; int x,y,z,waktu,waktu_loop[2],total; bool pos[2][15][15][5]={0}; bool loop[2],ketemu; char peta[15][15],gps[2]={'C','F'}; gerak objek[2],temp_objek[2];//0 itu sapi,1 itu orang int main() { freopen ("ttwo.in","r",stdin); freopen ("ttwo.out","w",stdout); waktu=0; for(y=0;y<10;y++) { scanf("%s",peta[y]); if(waktu<2) for(z=0;z<2;z++) for(x=0;x<10;x++) if(peta[y][x]==gps[z]) { temp_objek[z].x=x; temp_objek[z].y=y; temp_objek[z].arah=0; peta[y][x]='.'; waktu++; } } for(x=0;x<2;x++) { objek[x]=temp_objek[x]; waktu_loop[x]=0; while(1) { if(!pos[x][objek[x].x][objek[x].y][objek[x].arah]) pos[x][objek[x].x][objek[x].y][objek[x].arah]=true; else break; if((objek[x].y+ver[objek[x].arah]<0)||(objek[x].y+ver[objek[x].arah]>9)|| (objek[x].x+hor[objek[x].arah]<0)||(objek[x].x+hor[objek[x].arah]>9)|| (peta[objek[x].y+ver[objek[x].arah]][objek[x].x+hor[objek[x].arah]]=='*')) objek[x].arah=(objek[x].arah+1)%4; else { objek[x].x+=hor[objek[x].arah]; objek[x].y+=ver[objek[x].arah]; } waktu_loop[x]++; } } total=(waktu_loop[0]*waktu_loop[1])/__gcd(waktu_loop[0],waktu_loop[1]); waktu=0; for(x=0;x<2;x++) objek[x]=temp_objek[x]; ketemu=false; while(waktu<=total) { //printf("%d %d %d %d %d %d %d\n",objek[0].x,objek[0].y,objek[0].arah,objek[1].x,objek[1].y,objek[1].arah,waktu); if((objek[0].x==objek[1].x)&&(objek[0].y==objek[1].y)) { ketemu=true; break; } for(x=0;x<2;x++) { if((objek[x].y+ver[objek[x].arah]<0)||(objek[x].y+ver[objek[x].arah]>9)|| (objek[x].x+hor[objek[x].arah]<0)||(objek[x].x+hor[objek[x].arah]>9)|| (peta[objek[x].y+ver[objek[x].arah]][objek[x].x+hor[objek[x].arah]]=='*')) objek[x].arah=(objek[x].arah+1)%4; else { objek[x].x+=hor[objek[x].arah]; objek[x].y+=ver[objek[x].arah]; } } waktu++; } if(ketemu) printf("%d\n",waktu); else printf("0\n"); fclose(stdin); fclose(stdout); return 0; }
[ "felikjunvianto@yahoo.co.id" ]
felikjunvianto@yahoo.co.id
952282a80bec8009e68ed8f586d221e02db4342e
fd6d4decb99fbc15ab95bae6955e0947c65560fb
/devel/rxdisp/MainWindow.h
0388a334cd71ece7065eef40b739b8588a4213de
[]
no_license
gotomypc/livepro
5a254ae56dd6ca6be438be3e260aac0fd5a0ecec
eedc23695a81e0f445acd0467f3bf29f154294c6
refs/heads/master
2021-01-22T03:06:24.685545
2013-02-17T23:04:04
2013-02-17T23:04:04
39,391,551
0
0
null
null
null
null
UTF-8
C++
false
false
379
h
#ifndef MainWindow_H #define MainWindow_H #include <QtGui> class GLWidget; class VideoReceiver; class GLImageHttpDrawable; class MainWindow : public QWidget { Q_OBJECT public: MainWindow(); protected slots: void customSignal(QString key, QVariant value); void videoReceiverChanged(VideoReceiver *); protected: GLWidget *m_glw; GLImageHttpDrawable *m_drw; }; #endif
[ "josiahbryan@6f7359d6-f641-0324-569b-6f61136d9b6b" ]
josiahbryan@6f7359d6-f641-0324-569b-6f61136d9b6b
7e78f0aff35daf293fff6d380c193896dc51fb7d
2a4b3cfc9ff17bdc1cfe9c3e159d2d902908d0bb
/Ybt/双精度除法.cpp
149a7b8815b1fa426446cf702444a7b84a0684df
[]
no_license
dddql/cpp
afd45bc6c4e37fdeec92eca2e9092c113bcc2658
6c209a4eeda5ec32afe31aafeaf216ed482234a3
refs/heads/master
2023-02-19T11:26:51.273363
2022-09-26T14:20:06
2022-09-26T14:20:06
298,593,978
1
0
null
null
null
null
UTF-8
C++
false
false
155
cpp
#include<bits/stdc++.h> using namespace std; int main(){ float a,b; cin>>a>>b; cout<<fixed<<setprecision(9)<<a/b<<endl; system("pause"); return 0; }
[ "1514670771@qq.com" ]
1514670771@qq.com
902f37f011de1c454049c05c8ec51e233cd168ba
002bab85098749a89ce253b3b3cd5a6fdfba6b6c
/src/Runtime.h
92e3fd57d785e70509f50415c969539657c9291f
[ "BSD-3-Clause" ]
permissive
buresm11/mirunInterpreter
bad6eb6b1acad386dc4e09c304429fa74594f995
c8d1e3d104cadfd6e99c07075c9ec2f7accfe93b
refs/heads/master
2021-09-06T22:32:42.283313
2018-02-12T16:56:55
2018-02-12T16:56:55
115,793,774
0
0
null
null
null
null
UTF-8
C++
false
false
6,145
h
#pragma once #include <map> #include <iostream> #include <fstream> #include <string> #include "Obj.h" #include "IntObj.h" #include "StringObj.h" #include "BoolObj.h" #include "Environment.h" #include "Scope.h" #include "Function.h" #include "Array.h" #define HEAP_SIZE 500 #define HEAP_THRESHOLD 400 class Visitor; class Runtime { Array ** heap; int allocated_records; std::map<std::string, Function *> functions; Scope * scope; public: Runtime() { this->heap = new Array*[HEAP_SIZE]; for(int i=0;i<HEAP_SIZE;i++) { this->heap[i] = NULL; } this->allocated_records = 0; this->scope = NULL; } ~Runtime() { sweep(); std::map<std::string, Function *>::iterator it; for (it = functions.begin(); it != functions.end(); it++) { delete it->second; } delete [] heap; delete scope; } ContextValue * allocate_on_heap(Array * array) { int slot = find_empty_slot(); if(slot < 0) { return new ContextValue(NULL, new Error(25, "Heap full" )); } allocated_records++; heap[slot] = array; return new ContextValue(); } int find_empty_slot() { if(allocated_records > HEAP_THRESHOLD) { clean(); } for(int i=0;i<HEAP_SIZE;i++) { if(heap[i] == NULL) return i; } return -1; } void clean() { mark(); sweep(); } void mark() { scope->mark(); } void sweep() { for(int i=0;i<HEAP_SIZE;i++) { if(heap[i] != NULL) { if(!heap[i]->is_marked()) { for(int j=0;j<heap[i]->get_array_size();j++) { delete heap[i]->get_array()[j]; } delete [] heap[i]->get_array(); delete heap[i]; heap[i] = NULL; } } } } Scope * create_new_scope() { Scope * new_scope = new Scope(scope); this->scope = new_scope; return this->scope; } Scope * get_current_scope() { return scope; } void remove_top_scope() { if(scope->get_parent() != NULL) { Scope * tmp = this->scope; this->scope = scope->get_parent(); delete tmp; } } ContextValue * create_new_function(std::string name, Function * function) { if (this->functions.insert(std::pair<std::string, Function *>(name, function)).second == false) { return new ContextValue(NULL, new Error(15, "Function " + name + " is already defined in current scope" )); } else { return new ContextValue(); } } ContextValue * invoke_function (std::string name, Obj ** params, int params_count); void * print(Obj * obj, bool newline) { if(obj->get_type() == IntType) print((IntObj*)obj, newline); else if(obj->get_type() == StringType) print((StringObj*)obj, newline); else if(obj->get_type() == BoolType) print((BoolObj*)obj, newline); else if(obj->get_type() == ArrayType) print((ArrayObj*)obj, newline); } void print(IntObj* int_obj, bool newline) { std::cout << int_obj->get_value(); if(newline)std::cout << std::endl; } void print(StringObj* string_obj, bool newline) { std::cout << string_obj->get_value(); if(newline)std::cout << std::endl; } void print(BoolObj* bool_obj, bool newline) { if(bool_obj->get_value()) { std::cout << "True"; } else { std::cout << "False"; } if(newline)std::cout << std::endl; } void * print(ArrayObj* array_obj, bool newline) { Obj ** array = array_obj->get_value(); int array_size = array_obj->get_array_size(); std::cout << "["; for(int i=0; i<array_size; i++) { print(array[i], false); if(i < array_size-1) std::cout << ","; } std::cout << "]"; if(newline)std::cout << std::endl; } ContextValue * scan(std::string name, Scope * scope) { ContextValue * context_value = scope->current_environment()->look_up_scan_variable(name); if(context_value->has_error()) { return context_value; } Obj * obj = context_value->get_obj(); delete context_value; return scan_variable(obj); } ContextValue * scan(std::string name, int index, Scope * scope) { ContextValue * context_value = scope->current_environment()->look_up_array_scan_variable(name, index); if(context_value->has_error()) { return context_value; } ContextValue * context_value_scan = scan_variable(context_value->get_obj()); delete context_value; return context_value_scan; } ContextValue * scan_variable(Obj * obj) { if(obj->get_type() == IntType) return scan((IntObj*)obj); else if(obj->get_type() == StringType) return scan((StringObj*)obj); else if(obj->get_type() == BoolType) return scan((BoolObj*)obj); else { return new ContextValue(NULL, new Error(13, "Unknown type")); } } ContextValue * scan(IntObj * int_obj) { int val; if (std::cin >> val) { int_obj->set_value(val); return new ContextValue(NULL, NULL); } else if (std::cin.bad()) { return new ContextValue(NULL, new Error(16, "IO error" )); } else if (std::cin.eof()) { return new ContextValue(NULL, new Error(17, "EOF reached" )); } else { return new ContextValue(NULL, new Error(18, "Format problem" )); } } ContextValue * scan(StringObj * string_obj) { std::string val; if (std::cin >> val) { string_obj->set_value(val); return new ContextValue(NULL, NULL); } else if (std::cin.bad()) { return new ContextValue(NULL, new Error(16, "IO error" )); } else if (std::cin.eof()) { return new ContextValue(NULL, new Error(17, "EOF reached" )); } else { return new ContextValue(NULL, new Error(18, "Format problem" )); } } ContextValue * scan(BoolObj * bool_obj) { bool val; if (std::cin >> std::boolalpha >> val) { bool_obj->set_value(val); return new ContextValue(NULL, NULL); } else if (std::cin.bad()) { return new ContextValue(NULL, new Error(16, "IO error" )); } else if (std::cin.eof()) { return new ContextValue(NULL, new Error(17, "EOF reached" )); } else { return new ContextValue(NULL, new Error(18, "Format problem" )); } } void delete_args(Obj ** args, int args_size) { for(int i=0; i < args_size; i++) { delete args[i]; } delete [] args; } };
[ "buresm11@fit.cvut.cz" ]
buresm11@fit.cvut.cz
854ffa5a94d1a6c6da30a3a62f905eee7d06d88c
d199b019d2edd5c415f8d1982b53ff645489728e
/Gurtozytok/Campus2/human/Manager.h
0ea9742093194c25741ec4cde9b7712f5926c345
[]
no_license
azozello/resque
b4163690c9e03d1e8650e6c2b5bcb4e780f9de6b
6af44031d623d87a4253fc0115460ac2d4bb7adc
refs/heads/master
2021-01-19T12:10:06.267807
2017-10-04T16:10:12
2017-10-04T16:10:12
82,289,884
1
0
null
null
null
null
UTF-8
C++
false
false
696
h
// // Created by azozello on 09.05.17. // #ifndef CAMPUS2_MANAGER_H #define CAMPUS2_MANAGER_H #include <vector> #include "Human.h" #include "../area/Room.h" #include "Student.h" #include "Staff.h" class Manager : public Human{ private: string password; public: Manager(bool sex, const string &name, const string &password); Manager(); const string &getPassword() const; void setPassword(const string &password); vector<Room> loadRooms(); vector<Student> loadStudents(); vector<Staff> loadStaff(); vector<Room> freeRooms(); void addRoom(Room room); void addStudent(Student student); void addStaff(Staff staff); }; #endif //CAMPUS2_MANAGER_H
[ "noreply@github.com" ]
azozello.noreply@github.com
09befb9464f0e6bc5052449424bc00b769acce63
7bdf2fb15f93eb4801debedc709eeb04b67ff74f
/Coordinate.h
fcbc6c3ed2c31189bfd7862d2cf98826dbc4dce4
[]
no_license
yakiramar/Drawing-board
44779b3a488de31da3fd72d12a7d91527314d80d
78a3f88953060d761080e583a5439218252c86af
refs/heads/master
2020-03-18T18:03:44.243644
2019-06-18T14:10:28
2019-06-18T14:10:28
135,069,328
0
0
null
null
null
null
UTF-8
C++
false
false
273
h
#pragma once #include <iostream> using namespace std; class Coordinate{ public: int x; int y; Coordinate(int x2,int y2); Coordinate(uint x2,uint y2); friend ostream& operator<< (ostream& os, const Coordinate& p); };
[ "noreply@github.com" ]
yakiramar.noreply@github.com
68dbe27b9f74c5c1785715836cb444c712b1f58b
48da3cf76d6932e643824e8538bfad5529cf335a
/branches/20180201/game_server/business_activity/sevenday_login.hpp
5f16395e9bf11cc4cf26350a8a3b918312ce89ae
[]
no_license
daxingyou/sg_server
932c84317210f7096b97f06c837e9e15e73809bd
2bd0a812f0baeb31dc09192d0e88d47fde916a2b
refs/heads/master
2021-09-19T16:01:37.630704
2018-07-28T09:27:09
2018-07-28T09:27:09
null
0
0
null
null
null
null
GB18030
C++
false
false
966
hpp
#ifndef _SEVENDAY_LOGIN_HPP_ #define _SEVENDAY_LOGIN_HPP_ #include "macros.hpp" #include "protos_fwd.hpp" #include <set> class role_t; typedef boost::shared_ptr<role_t> role_ptr; class sevenday_login_t { public: sevenday_login_t(uint64_t role_id); void load_data(const proto::common::sevenday_login_save_data& data); void peek_data(proto::common::sevenday_login_save_data &data); void save_data(); void oneday(); void init_newbie(); public: uint32_t get_sevenday_list_info( proto::client::gc_get_7d_login_reply &reply ); uint32_t get_sevenday_list_prize( uint32_t index, proto::client::gc_get_7d_login_prize_reply &reply ); void on_login(); uint32_t get_prize_status(uint32_t day); uint32_t get_red_num(); private: std::string m_key = ""; uint64_t m_role_uid = 0; uint8_t m_login_flag = 0; //计数标记 uint32_t m_day = 0; std::set<uint32_t>m_sevenday_list; //七日登录奖励数据 }; #endif
[ "major@fun2" ]
major@fun2
edfd6c77c1c4f28aebbe731f960b7413a1d34bef
f2339e85157027dada17fadd67c163ecb8627909
/Cluster/RedisTest/Src/ListOpTest.h
fc4878f60510ae5e085465a45a5e99453dd6628a
[]
no_license
fynbntl/Titan
7ed8869377676b4c5b96df953570d9b4c4b9b102
b069b7a2d90f4d67c072e7c96fe341a18fedcfe7
refs/heads/master
2021-09-01T22:52:37.516407
2017-12-29T01:59:29
2017-12-29T01:59:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
247
h
#pragma once #include "IRedisTest.h" struct IListOp; class ListOpTest : public IRedisTest { public: ListOpTest(Redis::IListOp* pOp); virtual const char* GetName() override; virtual bool Run() override; private: Redis::IListOp* m_pOp; };
[ "85789685@qq.com" ]
85789685@qq.com
86b71285645010a3f60447d7f544daf207aff5a9
0ac3a5cabcbf72683a6fb08232df1b4817ce54ab
/Code/Functions.h
3af89f4e66d6efe9855b920108c27e087485158b
[]
no_license
wagnereATWIT/ProgrammingConcepts
211fe4145f9ac0af59ebbb65e74ff5201a7929cf
746abedc047000c56a6189e6f9523fcb5af99dbf
refs/heads/main
2023-07-02T15:22:00.204216
2021-07-30T21:15:40
2021-07-30T21:15:40
372,336,282
0
0
null
null
null
null
UTF-8
C++
false
false
570
h
#ifndef FUNCTIONS_H #define FUNCTIONS_H #include <iostream> #include <stdio.h> #include <sqlite3.h> #include <vector> #include <string> #include <sstream> #include "Course.h" // Call back functions int callback(void*, int, char**, char**); int callback_store(void*, int, char**, char**); void StudentDB(sqlite3*); void InstructorDB(sqlite3*); void AdminDB(sqlite3*); void CourseDB(sqlite3*); void ResetDB(sqlite3*); // Create vector with all courses in it std::vector<Course> create_courselist(std::vector<std::string>, sqlite3*); #endif
[ "noreply@github.com" ]
wagnereATWIT.noreply@github.com
d75b2cadef3841d717e92c2bf3bb42ff3f8b7bb7
df182b90f70d0a5eee100db57a82df6ca56d10e4
/src/utiltime.cpp
a92ca9fc4b52099c176c4009082583c1a003dfea
[ "MIT" ]
permissive
congstarcoin/congstar-core
83a1f28aed9b0093e8f4812583d0491d3db2f991
4d14841103ba1610ef02e594995fd11cc07676b8
refs/heads/master
2020-08-20T00:09:08.569610
2019-10-23T02:43:19
2019-10-23T02:43:19
215,966,895
0
0
null
null
null
null
UTF-8
C++
false
false
2,470
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/csr-config.h" #endif #include "tinyformat.h" #include "utiltime.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/thread.hpp> using namespace std; static int64_t nMockTime = 0; //! For unit testing int64_t GetTime() { if (nMockTime) return nMockTime; return time(NULL); } void SetMockTime(int64_t nMockTimeIn) { nMockTime = nMockTimeIn; } int64_t GetTimeMillis() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))) .total_milliseconds(); } int64_t GetTimeMicros() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))) .total_microseconds(); } void MilliSleep(int64_t n) { /** * Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50 * until fixed in 1.52. Use the deprecated sleep method for the broken case. * See: https://svn.boost.org/trac/boost/ticket/7238 */ #if defined(HAVE_WORKING_BOOST_SLEEP_FOR) boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #elif defined(HAVE_WORKING_BOOST_SLEEP) boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #else //should never get here #error missing boost sleep implementation #endif } std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime) { // std::locale takes ownership of the pointer std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat)); std::stringstream ss; ss.imbue(loc); ss << boost::posix_time::from_time_t(nTime); return ss.str(); } std::string DurationToDHMS(int64_t nDurationTime) { int seconds = nDurationTime % 60; nDurationTime /= 60; int minutes = nDurationTime % 60; nDurationTime /= 60; int hours = nDurationTime % 24; int days = nDurationTime / 24; if (days) return strprintf("%dd %02dh:%02dm:%02ds", days, hours, minutes, seconds); if (hours) return strprintf("%02dh:%02dm:%02ds", hours, minutes, seconds); return strprintf("%02dm:%02ds", minutes, seconds); }
[ "congstarcoin@gmail.com" ]
congstarcoin@gmail.com
d66344c9735faa7c03776c18a611ea6a906eddb1
15383b87591d6f8f116eaab30ee2b71b0a82ec57
/dlib-19.22/tools/python/src/conversion.h
9a46f4a3abba6c0a487aaff84509a8abab8a6a8d
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
kwkim5/Studio_Prj_Arch2021
d54aec7739fd9166859b156228a3909148def8cd
d0e8d6f05d2f3412b6698259e488204c15e77135
refs/heads/main
2023-06-10T05:07:23.934614
2021-06-16T05:01:05
2021-06-16T05:01:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,244
h
// Copyright (C) 2014 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_PYTHON_CONVERSION_H__ #define DLIB_PYTHON_CONVERSION_H__ #include "opaque_types.h" #include <dlib/python.h> #include <dlib/pixel.h> #include <dlib/python/numpy_image.h> using namespace dlib; using namespace std; namespace py = pybind11; template <typename image_array, typename param_type> void images_and_nested_params_to_dlib( const py::object& pyimages, const py::object& pyparams, image_array& images, std::vector<std::vector<param_type>>& params ) { // Now copy the data into dlib based objects. py::iterator image_it = pyimages.begin(); py::iterator params_it = pyparams.begin(); for (unsigned long image_idx = 0; image_it != pyimages.end() && params_it != pyparams.end(); ++image_it, ++params_it, ++image_idx) { for (py::iterator param_it = params_it->begin(); param_it != params_it->end(); ++param_it) params[image_idx].push_back(param_it->cast<param_type>()); assign_image(images[image_idx], image_it->cast<py::array>()); } } #endif // DLIB_PYTHON_CONVERSION_H__
[ "windheim@nowhere.com" ]
windheim@nowhere.com
9d1bcd8e97cc9dde060d9eaaba9ae2f228b99278
92e07f2755bc10e5bdfad4f82ce19c280d3485f6
/src/deps/inih.h
85f31d055a600dcc2f355e93d31dc155e91d74a9
[]
no_license
trevnorris/planetary_motion
f9d840183e7f93b0549a98740bdf27801ea9f701
337d592d60115760034b12f7f087bb474ab368d6
refs/heads/master
2022-09-23T10:56:08.283653
2022-09-06T19:16:25
2022-09-06T19:16:25
204,767,428
2
0
null
null
null
null
UTF-8
C++
false
false
13,309
h
/* inih -- simple .INI file parser inih is released under the New BSD license (see LICENSE.txt). Go to the project home page for more info: https://github.com/benhoyt/inih */ #ifndef __INI_H__ #define __INI_H__ /* Make this header file easier to include in C++ code */ #ifdef __cplusplus extern "C" { #endif #include <stdio.h> /* Typedef for prototype of handler function. */ typedef int (*ini_handler)(void* user, const char* section, const char* name, const char* value); /* Typedef for prototype of fgets-style reader function. */ typedef char* (*ini_reader)(char* str, int num, void* stream); /* Parse given INI-style file. May have [section]s, name=value pairs (whitespace stripped), and comments starting with ';' (semicolon). Section is "" if name=value pair parsed before any section heading. name:value pairs are also supported as a concession to Python's configparser. For each name=value pair parsed, call handler function with given user pointer as well as section, name, and value (data only valid for duration of handler call). Handler should return nonzero on success, zero on error. Returns 0 on success, line number of first error on parse error (doesn't stop on first error), -1 on file open error, or -2 on memory allocation error (only when INI_USE_STACK is zero). */ int ini_parse(const char* filename, ini_handler handler, void* user); /* Same as ini_parse(), but takes a FILE* instead of filename. This doesn't close the file when it's finished -- the caller must do that. */ int ini_parse_file(FILE* file, ini_handler handler, void* user); /* Same as ini_parse(), but takes an ini_reader function pointer instead of filename. Used for implementing custom or string-based I/O. */ int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler, void* user); /* Nonzero to allow multi-line value parsing, in the style of Python's configparser. If allowed, ini_parse() will call the handler with the same name for each subsequent line parsed. */ #ifndef INI_ALLOW_MULTILINE #define INI_ALLOW_MULTILINE 1 #endif /* Nonzero to allow a UTF-8 BOM sequence (0xEF 0xBB 0xBF) at the start of the file. See http://code.google.com/p/inih/issues/detail?id=21 */ #ifndef INI_ALLOW_BOM #define INI_ALLOW_BOM 1 #endif /* Nonzero to allow inline comments (with valid inline comment characters specified by INI_INLINE_COMMENT_PREFIXES). Set to 0 to turn off and match Python 3.2+ configparser behaviour. */ #ifndef INI_ALLOW_INLINE_COMMENTS #define INI_ALLOW_INLINE_COMMENTS 1 #endif #ifndef INI_INLINE_COMMENT_PREFIXES #define INI_INLINE_COMMENT_PREFIXES ";" #endif /* Nonzero to use stack, zero to use heap (malloc/free). */ #ifndef INI_USE_STACK #define INI_USE_STACK 1 #endif /* Stop parsing on first error (default is to keep parsing). */ #ifndef INI_STOP_ON_FIRST_ERROR #define INI_STOP_ON_FIRST_ERROR 0 #endif /* Maximum line length for any line in INI file. */ #ifndef INI_MAX_LINE #define INI_MAX_LINE 200 #endif #ifdef __cplusplus } #endif /* inih -- simple .INI file parser inih is released under the New BSD license (see LICENSE.txt). Go to the project home page for more info: https://github.com/benhoyt/inih */ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include <stdio.h> #include <ctype.h> #include <string.h> #if !INI_USE_STACK #include <stdlib.h> #endif #define MAX_SECTION 50 #define MAX_NAME 50 /* Strip whitespace chars off end of given string, in place. Return s. */ inline static char* rstrip(char* s) { char* p = s + strlen(s); while (p > s && isspace((unsigned char)(*--p))) *p = '\0'; return s; } /* Return pointer to first non-whitespace char in given string. */ inline static char* lskip(const char* s) { while (*s && isspace((unsigned char)(*s))) s++; return (char*)s; } /* Return pointer to first char (of chars) or inline comment in given string, or pointer to null at end of string if neither found. Inline comment must be prefixed by a whitespace character to register as a comment. */ inline static char* find_chars_or_comment(const char* s, const char* chars) { #if INI_ALLOW_INLINE_COMMENTS int was_space = 0; while (*s && (!chars || !strchr(chars, *s)) && !(was_space && strchr(INI_INLINE_COMMENT_PREFIXES, *s))) { was_space = isspace((unsigned char)(*s)); s++; } #else while (*s && (!chars || !strchr(chars, *s))) { s++; } #endif return (char*)s; } /* Version of strncpy that ensures dest (size bytes) is null-terminated. */ inline static char* strncpy0(char* dest, const char* src, size_t size) { strncpy(dest, src, size); dest[size - 1] = '\0'; return dest; } /* See documentation in header file. */ inline int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler, void* user) { /* Uses a fair bit of stack (use heap instead if you need to) */ #if INI_USE_STACK char line[INI_MAX_LINE]; #else char* line; #endif char section[MAX_SECTION] = ""; char prev_name[MAX_NAME] = ""; char* start; char* end; char* name; char* value; int lineno = 0; int error = 0; #if !INI_USE_STACK line = (char*)malloc(INI_MAX_LINE); if (!line) { return -2; } #endif /* Scan through stream line by line */ while (reader(line, INI_MAX_LINE, stream) != NULL) { lineno++; start = line; #if INI_ALLOW_BOM if (lineno == 1 && (unsigned char)start[0] == 0xEF && (unsigned char)start[1] == 0xBB && (unsigned char)start[2] == 0xBF) { start += 3; } #endif start = lskip(rstrip(start)); if (*start == ';' || *start == '#') { /* Per Python configparser, allow both ; and # comments at the start of a line */ } #if INI_ALLOW_MULTILINE else if (*prev_name && *start && start > line) { #if INI_ALLOW_INLINE_COMMENTS end = find_chars_or_comment(start, NULL); if (*end) *end = '\0'; rstrip(start); #endif /* Non-blank line with leading whitespace, treat as continuation of previous name's value (as per Python configparser). */ if (!handler(user, section, prev_name, start) && !error) error = lineno; } #endif else if (*start == '[') { /* A "[section]" line */ end = find_chars_or_comment(start + 1, "]"); if (*end == ']') { *end = '\0'; strncpy0(section, start + 1, sizeof(section)); *prev_name = '\0'; } else if (!error) { /* No ']' found on section line */ error = lineno; } } else if (*start) { /* Not a comment, must be a name[=:]value pair */ end = find_chars_or_comment(start, "=:"); if (*end == '=' || *end == ':') { *end = '\0'; name = rstrip(start); value = lskip(end + 1); #if INI_ALLOW_INLINE_COMMENTS end = find_chars_or_comment(value, NULL); if (*end) *end = '\0'; #endif rstrip(value); /* Valid name[=:]value pair found, call handler */ strncpy0(prev_name, name, sizeof(prev_name)); if (!handler(user, section, name, value) && !error) error = lineno; } else if (!error) { /* No '=' or ':' found on name[=:]value line */ error = lineno; } } #if INI_STOP_ON_FIRST_ERROR if (error) break; #endif } #if !INI_USE_STACK free(line); #endif return error; } /* See documentation in header file. */ inline int ini_parse_file(FILE* file, ini_handler handler, void* user) { return ini_parse_stream((ini_reader)fgets, file, handler, user); } /* See documentation in header file. */ inline int ini_parse(const char* filename, ini_handler handler, void* user) { FILE* file; int error; file = fopen(filename, "r"); if (!file) return -1; error = ini_parse_file(file, handler, user); fclose(file); return error; } #endif /* __INI_H__ */ #ifndef __INIREADER_H__ #define __INIREADER_H__ #include <map> #include <set> #include <string> // Read an INI file into easy-to-access name/value pairs. (Note that I've gone // for simplicity here rather than speed, but it should be pretty decent.) class INIReader { public: // Empty Constructor INIReader() {}; // Construct INIReader and parse given filename. See ini.h for more info // about the parsing. INIReader(std::string filename); // Construct INIReader and parse given file. See ini.h for more info // about the parsing. INIReader(FILE *file); // Return the result of ini_parse(), i.e., 0 on success, line number of // first error on parse error, or -1 on file open error. int ParseError() const; // Return the list of sections found in ini file const std::set<std::string>& Sections() const; // Get a string value from INI file, returning default_value if not found. std::string Get(std::string section, std::string name, std::string default_value) const; // Get an integer (long) value from INI file, returning default_value if // not found or not a valid integer (decimal "1234", "-1234", or hex "0x4d2"). long GetInteger(std::string section, std::string name, long default_value) const; // Get a real (floating point double) value from INI file, returning // default_value if not found or not a valid floating point value // according to strtod(). double GetReal(std::string section, std::string name, double default_value) const; // Get a boolean value from INI file, returning default_value if not found or if // not a valid true/false value. Valid true values are "true", "yes", "on", "1", // and valid false values are "false", "no", "off", "0" (not case sensitive). bool GetBoolean(std::string section, std::string name, bool default_value) const; protected: int _error; std::map<std::string, std::string> _values; std::set<std::string> _sections; static std::string MakeKey(std::string section, std::string name); static int ValueHandler(void* user, const char* section, const char* name, const char* value); }; #endif // __INIREADER_H__ #ifndef __INIREADER__ #define __INIREADER__ #include <algorithm> #include <cctype> #include <cstdlib> inline INIReader::INIReader(std::string filename) { _error = ini_parse(filename.c_str(), ValueHandler, this); } inline INIReader::INIReader(FILE *file) { _error = ini_parse_file(file, ValueHandler, this); } inline int INIReader::ParseError() const { return _error; } inline const std::set<std::string>& INIReader::Sections() const { return _sections; } inline std::string INIReader::Get(std::string section, std::string name, std::string default_value) const { std::string key = MakeKey(section, name); return _values.count(key) ? _values.at(key) : default_value; } inline long INIReader::GetInteger(std::string section, std::string name, long default_value) const { std::string valstr = Get(section, name, ""); const char* value = valstr.c_str(); char* end; // This parses "1234" (decimal) and also "0x4D2" (hex) long n = strtol(value, &end, 0); return end > value ? n : default_value; } inline double INIReader::GetReal(std::string section, std::string name, double default_value) const { std::string valstr = Get(section, name, ""); const char* value = valstr.c_str(); char* end; double n = strtod(value, &end); return end > value ? n : default_value; } inline bool INIReader::GetBoolean(std::string section, std::string name, bool default_value) const { std::string valstr = Get(section, name, ""); // Convert to lower case to make string comparisons case-insensitive std::transform(valstr.begin(), valstr.end(), valstr.begin(), ::tolower); if (valstr == "true" || valstr == "yes" || valstr == "on" || valstr == "1") return true; else if (valstr == "false" || valstr == "no" || valstr == "off" || valstr == "0") return false; else return default_value; } inline std::string INIReader::MakeKey(std::string section, std::string name) { std::string key = section + "=" + name; // Convert to lower case to make section/name lookups case-insensitive std::transform(key.begin(), key.end(), key.begin(), ::tolower); return key; } inline int INIReader::ValueHandler(void* user, const char* section, const char* name, const char* value) { INIReader* reader = (INIReader*)user; std::string key = MakeKey(section, name); if (reader->_values[key].size() > 0) reader->_values[key] += "\n"; reader->_values[key] += value; reader->_sections.insert(section); return 1; } #endif // __INIREADER__
[ "trev.norris@gmail.com" ]
trev.norris@gmail.com
784787ecc2412de84b30bbe50292626d376a460d
d88972c760ef8e78c28eb078df77bea8cea3d204
/source/resources/AudioLoader.cpp
76a8d1b04e748bcf733d2074a15ab02d843b8b20
[]
no_license
Stifyz/Indie_Studio
3dddd6eb76fefb0c1f0c6841bcb551f83f346572
dada91fa63a73fe396c0ed0947a99807d5f7836f
refs/heads/master
2021-09-10T00:16:42.836505
2017-06-18T21:03:17
2017-06-21T14:04:43
125,994,079
0
0
null
null
null
null
UTF-8
C++
false
false
1,345
cpp
/* * ===================================================================================== * * Filename: AudioLoader.cpp * * Description: * * Created: 14/01/2015 00:34:26 * * Author: Quentin Bazin, <gnidmoo@gmail.com> * * ===================================================================================== */ #include "AudioLoader.hpp" #include "BackgroundMusic.hpp" #include "SoundEffect.hpp" #include "XMLFile.hpp" void AudioLoader::load(const char *xmlFilename, ResourceHandler &handler) { XMLFile doc(xmlFilename); tinyxml2::XMLElement *musicElement = doc.FirstChildElement("audio").FirstChildElement("music").ToElement(); while(musicElement) { std::string name = musicElement->Attribute("name"); std::string filename = "res/audio/music/" + name + ".ogg"; handler.add<BackgroundMusic>("bgm-" + name, filename); musicElement = musicElement->NextSiblingElement("music"); } tinyxml2::XMLElement *soundEffectElement = doc.FirstChildElement("audio").FirstChildElement("soundeffect").ToElement(); while(soundEffectElement) { std::string name = soundEffectElement->Attribute("name"); std::string filename = "res/audio/effects/" + name + ".wav"; handler.add<SoundEffect>("sfx-" + name, filename); soundEffectElement = soundEffectElement->NextSiblingElement("soundeffect"); } }
[ "quent42340@gmail.com" ]
quent42340@gmail.com
e3c02fe22ce6aaa8600f178d2764ef9b6fe80daf
fc6a7d9358f008f6b331234b1f5b4b283f5425bd
/firstGitCpp.cpp
00fe058c47e32f653fa87fcb730c191578fd84a9
[]
no_license
shikonc/myFirstRepository
a6217994b43f7b1cbe0da2a9d244d5b61baa3d57
d5897727195376d6b69a22aeb97929e3fec67adb
refs/heads/master
2021-04-09T11:34:56.513776
2018-03-16T03:11:23
2018-03-16T03:11:23
125,457,175
0
0
null
null
null
null
UTF-8
C++
false
false
128
cpp
#include <iostream> #include <cstdio> #include <iomanip> using namespace std; int main() { cout<<"this is a test "<<endl; }
[ "35677379+shikonc@users.noreply.github.com" ]
35677379+shikonc@users.noreply.github.com
044927e45ae3022c7072317aee3e264b88c26f34
e843c36a3493be1c43774f34caa49012a8f7c2a2
/Uebung5/pictureView.h
e0abf3e6b761a0274ecc8a93c6f8395fecbd0773
[]
no_license
cpetry/Mustererkennung
82edb26f0d251f7e47ff1a0d5ee25432481d5459
1b21a3f34fe76c3ef29d40ab35d197c71dbde288
refs/heads/master
2020-08-05T23:43:35.643415
2014-11-14T13:20:23
2014-11-14T13:20:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
960
h
/** * @Copyright 2014 * @Author Petry Christian * @FHWS */ #pragma once #include <QtWidgets/QApplication> #include <QtWidgets/QWidget> #include <QtWidgets/QGraphicsView> class pictureView : public QGraphicsView { public: pictureView(); void setOtherView(pictureView* pV); void setPixmap(QPixmap pixmap); void clear(); void scaleToFit(bool toFit); void mousePressEvent ( QMouseEvent * event ); void mouseReleaseEvent ( QMouseEvent * event ); void mouseMoveEvent ( QMouseEvent * event ); void wheelEvent ( QWheelEvent * event ); void setDraging(bool draging); void setLastPosition(int x, int y); void movePictureBy(int x, int y); void scaleByAt(int delta, int x, int y); void resetPosAndScale(); private: QGraphicsScene scene; bool scene_is_empty; pictureView *otherView; QGraphicsItem* pictureItem; int pic_pos_x = 0; int pic_pos_y = 0; bool is_draging; bool scaled_to_fit; int last_pos_x, last_pos_y; float scale_factor; };
[ "petry2christian@gmail.com" ]
petry2christian@gmail.com
10ba58576c5eeb9180033fd50421a1ed76c3fc80
aeb0367615f6d73757e8a9f43990b87a1eacc2b9
/geeksforgeeks/recursion/Number of paths.cpp
931bc0ac22a04e6f1c75796f8ff6dfe99a20dca9
[]
no_license
jai-singhal/dsa
b003c216f436a05ebac3babb24e5a20af17bc456
10c8a69958e5587a930f3c65b0993e905d18d301
refs/heads/master
2021-01-24T11:44:56.624307
2020-09-16T10:15:47
2020-09-16T10:15:47
123,097,497
2
0
null
null
null
null
UTF-8
C++
false
false
390
cpp
#include<iostream> using namespace std; int NumberOfPaths(int i, int j, int m, int n){ if(i >= m || j >= n) return 0; return 1 + NumberOfPaths(i+1, j, m, n) + NumberOfPaths(i, j+1, m, n); } int main(){ const char matrix[3][3] = { {'A', 'B', 'C'}, {'D', 'E', 'F'}, {'G', 'H', 'I'} }; cout << NumberOfPaths(3, 3, 0, 0) << endl; }
[ "jaisinghal48@gmail.com" ]
jaisinghal48@gmail.com
cb063c19c5b6745125f9fb51c8f5b3b511e45224
7627c6ebac8435870a7c689ade9932edf63c3158
/src/ViewLevelMeter.cpp
cab60b76025c35e59da6c108e8aa71dfd3e5966d
[]
no_license
westlicht/teensy-template
8e545749746eb39a72c79e50425d8c3c9535b922
7a0f2682ca0eaee531feda565d6c42f30a0f421a
refs/heads/master
2021-01-09T07:40:40.927018
2018-09-29T19:26:51
2018-09-29T19:26:51
64,962,616
0
0
null
2016-08-04T19:47:19
2016-08-04T19:47:19
null
UTF-8
C++
false
false
2,079
cpp
#include "ViewLevelMeter.h" #include "Voltage.h" #include "TextWidget.h" ViewLevelMeter::ViewLevelMeter(App &app) : ViewLevel(app), _stats({2, 2}), _widget(Point(0,0), Point(0,0), Painter::HAlignment::Center, Painter::VAlignment::Center, Painter::Font::Default, WHITE, BLACK) { } ViewLevelMeter::~ViewLevelMeter() { } void ViewLevelMeter::drawStatic() { clearContent(); _painter.drawFastHLine(0, 16, 128, _theme.seperator); _painter.drawFastHLine(0, 80, 128, _theme.seperator); _painter.drawFastHLine(0, 145, 128, _theme.seperator); _painter.setFont(Painter::Font::Large); _painter.setTextColor(WHITE); // _painter.drawRect(0, 16, 16, 64, WHITE); // _painter.drawRect(0, 80, 16, 64, WHITE); _painter.printAligned(0, 16, 16, 64, Painter::HAlignment::Center, Painter::VAlignment::Center, "1"); _painter.printAligned(0, 80, 16, 64, Painter::HAlignment::Center, Painter::VAlignment::Center, "2"); _painter.setFont(Painter::Font::Default); _painter.setTextColor(WHITE); _painter.setCursor(32, 16+4); _painter.print("Low"); _painter.setCursor(32, 16+4+12); _painter.print("High"); _painter.setCursor(32, 16+4+12+12); _painter.print("P-P"); _painter.setCursor(32, 16+4+12+12+12); _painter.print("Avg."); _painter.printAt(64, 16+4, 1); _painter.printAt(64, 16+4+12, 1); _painter.printAt(64, 16+4+12+12, 1); _painter.printAt(64, 16+4+12+12+12, 1); _painter.setCursor(32, 80+4); _painter.print("Low"); _painter.setCursor(32, 80+4+12); _painter.print("High"); _painter.setCursor(32, 80+4+12+12); _painter.print("P-P"); _painter.setCursor(32, 80+4+12+12+12); _painter.print("Avg."); // _painter.setCursor(32, 16+4+12+12+12); } void drawDynamic() { } void ViewLevelMeter::process(const ProcessContext &ctx) { int index = ctx.begin; while (index != ctx.end) { _stats[0].update(_engine.channel(0).read(index)); _stats[1].update(_engine.channel(1).read(index)); index = _engine.wrap(index + 1); } }
[ "simon.kallweit@gmail.com" ]
simon.kallweit@gmail.com
66b9ba6a8682b72edfd5cf83dada45f58b2db6c5
d6bb54215e44e94a1f29d2c2a2d6c24f129edd8c
/CIELRCPT.cpp
d3a250396e850ef78c8872b3607f2173ec352662
[]
no_license
subarnaChat/Codechef-submissions
df864061e01c6b00cc4525be689fe1079a8d27a9
119ff33e1e6426f8cd085698319b69237400bae9
refs/heads/main
2023-01-12T18:55:22.623077
2020-11-04T14:52:53
2020-11-04T14:52:53
310,031,735
0
0
null
null
null
null
UTF-8
C++
false
false
594
cpp
#include <stdio.h> #include<iostream> using namespace std; int main() { int a[] = {1,2,4,8,16,32,64,128,256,512,1024,2048}; int t, n, i,c, currPrice, divideTimes; cin>>t; while(t--) { i = 11; c = 0; cin>>n; while(i >= 0) { currPrice = a[i]; if (n >= currPrice) { divideTimes = n / currPrice; c += divideTimes; n = n - (divideTimes * currPrice); } i--; } cout<<c<<endl; } return 0; }
[ "noreply@github.com" ]
subarnaChat.noreply@github.com
9791fe03d35a79aba47422e5275468166086d157
e7e497b20442a4220296dea1550091a457df5a38
/main_project/OceCxxAdapter/src/ZhanFeedCacheReplicaAdapter.h
9e45104b5e025092d14daa2441bf294bb864f151
[]
no_license
gunner14/old_rr_code
cf17a2dedf8dfcdcf441d49139adaadc770c0eea
bb047dc88fa7243ded61d840af0f8bad22d68dee
refs/heads/master
2021-01-17T18:23:28.154228
2013-12-02T23:45:33
2013-12-02T23:45:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
918
h
#ifndef ZHAN_FEED_CACHE_ADAPTER_H_ #define ZHAN_FEED_CACHE_ADAPTER_H_ #include "Singleton.h" #include "AdapterI.h" #include "FeedCache.h" namespace xce{ namespace feed{ using namespace MyUtil; class ZhanFeedCacheAdapter: public MyUtil::ReplicatedClusterAdapterI<FeedCachePrx>, public MyUtil::Singleton<ZhanFeedCacheAdapter> { public: ZhanFeedCacheAdapter(): MyUtil::ReplicatedClusterAdapterI <FeedCachePrx> ("ControllerZhanFeedCacheR", 120, 260, new ZhanFeedChannel()) { } void put(const FeedItem& feed, const Int2IntMap& userWeight); FeedItemSeq get(int userId); void remove(int userId, Ice::Long feedId); void removeAll(int userId); protected: virtual size_t cluster() { return 10; } FeedCachePrx getManager(int id, int timeout=260); FeedCachePrx getManagerOneway(int id); }; }; }; #endif /*RESTMEDIATORADAPTER_H_*/
[ "liyong19861014@gmail.com" ]
liyong19861014@gmail.com
35fa56e9505c2f0fe49a1118a0bfc21a18f93556
589da5c248495666ef8152373a2adc7e61bee7d0
/room.h
b8a9a6874ff7782bb336314470b7793176c33e3c
[]
no_license
castlez/ZombieSurvive
5c7fc5e0bcfe2e87ce9254dd54b7add66fed192d
fadef6bc4ae46ddabc6368ba31870269b0ed67c9
refs/heads/master
2021-06-10T09:53:48.504099
2017-05-21T22:29:35
2017-05-21T22:29:35
27,954,117
0
0
null
null
null
null
UTF-8
C++
false
false
444
h
//ZOMBIE SURVIVE //Jonny Castle // //Interface for the room class //hold information about a single room //of dynamic size and content // #include "mat.h" class room{ friend class dungeon; public: room(); ~room(); private: matrix *area; //physical places in the room, arrange in a matrix char * description; //simple description of the room //directions room * n; room * s; room * w; room * e; };
[ "castlez93@gmail.com" ]
castlez93@gmail.com
cbc6e991f7e02ea21397df0cceb75033f11fa0ad
b862f6f4fd20066e3f25ea4ceb54a5fe22accd3f
/cpp/fdu-qstl/src/stl-code-copy-reverse.cpp
c95c3ef885d967d5d94b760b0f47c6844398b84d
[]
no_license
okertanov/functional
4cbd67beebdd99cb2d82f4b87674e172928d9cf8
e191c6f8c123828efa86bf47f41348e15f37097c
refs/heads/master
2023-03-06T16:22:22.457201
2023-02-26T17:13:33
2023-02-26T17:13:33
1,440,909
0
0
null
null
null
null
UTF-8
C++
false
false
1,663
cpp
/* Oleg Kertanov (c) 2005 */ #include <string> #include <cstdlib> #include <cstring> #include <cassert> #include <iostream> #include <algorithm> #include "benchmark.h" #define _() do { std::cout << std::endl << __FILE__ << ":" << __LINE__ << " in " << __FUNCTION__ << "()" << std::endl; } while (0) char* reverse(const char *src) { assert(src != 0); int len = strlen(src); char *dst = new char[len + 1]; assert(dst != 0); char *from = const_cast<char*>(&src[0]), *to = &dst[len - 1]; while( (*(to--) = *(from++)) ) { } dst[len] = 0; return dst; } void rev_test() { _(); std::string orig = "abcdefghijklmnopqrstuvwxyz1234567890"; std::string reversed1(""); std::string reversed2(""); std::string reversed3(""); { benchmark::timer::PerfTimer timer("Calibrate"); #if defined(WIN32) Sleep(1000); #else sleep(1); #endif } { benchmark::timer::PerfTimer timer("std::copy"); std::copy(orig.rbegin(), orig.rend(), std::back_inserter(reversed1)); } std::cout << "reversed1: " << reversed1 << std::endl; { benchmark::timer::PerfTimer timer("std::reverse_copy"); std::reverse_copy(orig.begin(), orig.end(), std::back_inserter(reversed2)); } std::cout << "reversed2: " << reversed2 << std::endl; char *rs = 0; { benchmark::timer::PerfTimer timer("plain reverse"); rs = reverse(orig.c_str()); } std::cout << "reversed3: " << rs << std::endl; delete[] rs; } int main(int argc, char** argv) { _(); rev_test(); return EXIT_SUCCESS; }
[ "okertanov@gmail.com" ]
okertanov@gmail.com
f77f37464c67ad24fc62fd73b8ee12c320ee808d
2b21c935a46dd51ad3b61544fc3ec4477fd78667
/common/io/FileUtil.h
7a41f8364fe9de1940028369c1b43a338cdfff61
[]
no_license
Horadrim-TalRasha/MazeExplorer
69a20fccdc5113daeb2830f362ccca22a5d4a416
7fdc756aea88a2813a70d1d41a422a7e7ec3d4ff
refs/heads/master
2021-05-27T04:43:51.603273
2014-07-07T10:01:25
2014-07-07T10:01:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,473
h
#ifndef _FILE_UTIL_H_ #define _FILE_UTIL_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <dirent.h> #include <fcntl.h> #include <sys/file.h> #include <sys/stat.h> #include <sys/types.h> #include <utime.h> #include <time.h> #include "BaseCommon.h" #define UNFLOCK(fd) close(fd) enum ECfgError { E_Cfg_EOF, E_Cfg_Comment, E_Cfg_Blank, E_Cfg_Error, E_Cfg_Content }; enum EFileLockError { E_File_Lock_Success, //锁成功 E_File_Lock_Failed, //锁失败 E_File_Lock_None //文件打不开 }; class FileUtil { public: FileUtil(); ~FileUtil(); static int CreateDir(char *szpBasePath, char *szpDirName); static int DeleteDir(char *szpBasePath, char *szpDirName); static int GetFileNumOfDir(char *szpDirName, unsigned int &uiFileNum); static int GetFirstFileOfDir(char *szpDirName, char *szpExtName, unsigned int uiExtLen, char *szpFirstFile); static int GetMinNumFileNameOfDir(char *szpDirName, char *szpExtName, char *szpFirstFile); static int SetNoBlock(int fd); static int SetBlock(int fd); static int CheckFilePath(char *szpFilePath, unsigned int &uiPathLen); static int GetPathDepth(char *szpFilePath); static ECfgError GetCfgKey(FILE *fp, char *szpKey, unsigned int uiIOLen, char *&szpValue); static ECfgError GetLine(FILE *fp, char *szpKey, unsigned int uiIOLen); static EFileLockError NonBlockFLock(char *szpLockFile, int &fd); static int SwitchFile(char *szpBakFile, char *szpOldFile, char *szpNewFile); static int ResumeFile(char *szpBakFile, char *szpOldFile, char *szpNewFile); static int IsDirOfFileExist(char *szpFileName, unsigned char ucIsCreate = 0); static int CreateFile(char *szpFileName); static int CreateNewFile(char *szpFileName); static void RemoveFile(char *szpFileName); static int LoadFile(char *szpFileName, char *szpBuf, unsigned int uiBufLen); static int SaveFile(char *szpFileName, char *szpBuf, unsigned int uiBufLen); static int WriteFile(char *szpFileName, unsigned long long u64FilePos, char *szpBuf, unsigned int uiBufLen); static int ReadFile(char** szpData, unsigned int* uiDataLen, const char *szpFileNmae); static int GetDiskSz7OldTm(char *szpDatPath, unsigned long long &u64CurSize, time_t &tMin, char *szpOldFile); //获取访问时间最老的 static int RefreshFile(char *szpFileName, unsigned long long &u64AccessTime); //修改访问时间 private: }; #endif
[ "524948250@qq.com" ]
524948250@qq.com
7f79ea0f73c4ee0f4ccac3ea4fb6b8484dcfad82
51ecd22a1a469aa0249e19ce886551b0872e677a
/915/2016t3.cpp
5d8a62a3b962558946e75e4565797da6b61f0179
[]
no_license
Leo-778/wangdao
d039e0d3e17362ae10ed4491400949dce1453339
a1e3180968ea64363ac66632133ebd6e17c86a66
refs/heads/master
2023-08-23T10:16:15.401165
2021-11-03T12:38:58
2021-11-03T12:38:58
395,994,013
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
/* * @Description: 统计某个学生的到客情况 * @Author: Leo * @Date: 2021-10-24 18:44:03 * @LastEditTime: 2021-10-24 19:15:22 */ #include <stdio.h> #include<algorithm> using namespace std; #define max 128 struct student { char name[128]; }; int main(int argc, char const *argv[]) { /* code */ return 0; }
[ "1357078925@qq.com" ]
1357078925@qq.com
7f808f730849cbbaba02af0fdc8e86f58cc2e6b7
a953eb527cd119f2ddc7097fd9cb7c49123adc47
/src/opengl2-skins/gl/shader_configuration.hpp
081b18dc142225d36a2d750f5c15210287bf3466
[]
no_license
maghoff/snygg
7657a4d41fa55df2263e8c1962424ef9fa6fab23
3f83863fd9c49acd06974a2f8672431441b2d864
refs/heads/master
2023-03-11T10:11:52.406117
2018-03-30T08:52:55
2018-03-30T08:52:55
211,388,679
0
0
null
null
null
null
UTF-8
C++
false
false
872
hpp
#ifndef SHADER_CONFIGURATION_HPP #define SHADER_CONFIGURATION_HPP #include <memory> #include <matrix.hpp> #include "opengl_resource.hpp" struct uniform_setter; class shader_program; class shader_configuration : public opengl_resource { struct impl; std::unique_ptr<impl> d; public: shader_configuration(const shader_program*); ~shader_configuration() override; void recreate_opengl_resources() override; void set_uniform(const std::string& name, int); void set_uniform(const std::string& name, float, float, float); void set_uniform(const std::string& name, float, float, float, float); void set_uniform(const std::string& name, const la::vec4f&); void set_uniform(const std::string& name, const la::matrix33f&); void add_texture(const std::string& sampler_name, const std::string& filename); void use() const; }; #endif // SHADER_CONFIGURATION_HPP
[ "maghoff@gmail.com" ]
maghoff@gmail.com
e6ed79ffadd3fc85b598e648fc2531f130788343
994465511505f06940eaee69faec49ee1abbad63
/Source/roboRover/roboRover.cpp
ef29cf45320402402cd96dbbdfde9c067f901da5
[ "MIT" ]
permissive
Henrynaut/roboRover
e754b764a3d884651fdb1777d12758b42016e459
b716d71caf8d514c34caa72a401fbb96574b0cd4
refs/heads/master
2022-12-27T10:02:41.842857
2020-09-19T04:03:28
2020-09-19T04:03:28
296,782,768
1
0
null
null
null
null
UTF-8
C++
false
false
193
cpp
// Copyright Epic Games, Inc. All Rights Reserved. #include "roboRover.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, roboRover, "roboRover" );
[ "neilmchenry@gmail.com" ]
neilmchenry@gmail.com
6cb34d3ab97412ad301daa4114c9253f30ff7f02
f937371af92c27239132abf18dbdc4cbbb63df33
/cpp_src/estl/contexted_locks.h
a29cf71e41802e23710d37308ea73f18c293787c
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
raymayemir/reindexer
e098ed4650fca42f152c6a1d727546130e6d1bdf
3b133ac2cd7a407fc34430bbc292af1500e98a40
refs/heads/master
2020-07-17T23:48:50.008075
2019-08-27T12:19:43
2019-08-27T12:19:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,248
h
#pragma once #include <chrono> #include <functional> #include <mutex> #include "tools/errors.h" using std::chrono::milliseconds; using std::try_to_lock_t; using std::defer_lock_t; using std::adopt_lock_t; namespace reindexer { const milliseconds kDefaultCondChkTime = milliseconds(20); template <typename _Mutex, typename Context> class contexted_lock_guard { public: using MutexType = _Mutex; explicit contexted_lock_guard(MutexType& __mtx, Context& __context, milliseconds __chkTimeout = kDefaultCondChkTime) : _M_mtx(__mtx) { const auto lockWard = __context.BeforeLock(_Mutex::mark); if (__chkTimeout.count() > 0 && __context.isCancelable()) { do { ThrowOnCancel(__context, "Lock was canceled on condition"); } while (!_M_mtx.try_lock_for(__chkTimeout)); } else { _M_mtx.lock(); } } ~contexted_lock_guard() { _M_mtx.unlock(); } private: MutexType& _M_mtx; }; template <typename _Mutex, typename Context> class contexted_unique_lock { public: using MutexType = _Mutex; explicit contexted_unique_lock(MutexType& __mtx, Context* __context, milliseconds __chkTimeout = kDefaultCondChkTime) : _M_mtx(&__mtx), _M_owns(false), _M_context(__context), _M_chkTimeout(__chkTimeout) { assert(_M_context); lock(); } explicit contexted_unique_lock(MutexType& __mtx, defer_lock_t, Context* __context, milliseconds __chkTimeout = kDefaultCondChkTime) : _M_mtx(&__mtx), _M_owns(false), _M_context(__context), _M_chkTimeout(__chkTimeout) { assert(_M_context); } explicit contexted_unique_lock(MutexType& __mtx, adopt_lock_t, Context* __context, milliseconds __chkTimeout = kDefaultCondChkTime) : _M_mtx(&__mtx), _M_owns(true), _M_context(__context), _M_chkTimeout(__chkTimeout) { assert(_M_context); } explicit contexted_unique_lock(MutexType& __mtx, try_to_lock_t, Context* __context, milliseconds __chkTimeout = kDefaultCondChkTime) : _M_mtx(&__mtx), _M_owns(__mtx.try_lock()), _M_context(__context), _M_chkTimeout(__chkTimeout) { assert(_M_context); } ~contexted_unique_lock() { if (_M_owns) _M_mtx->unlock(); } contexted_unique_lock(const contexted_unique_lock&) = delete; contexted_unique_lock& operator=(const contexted_unique_lock&) = delete; contexted_unique_lock(contexted_unique_lock&& __sl) noexcept : contexted_unique_lock() { swap(__sl); } contexted_unique_lock& operator=(contexted_unique_lock&& __sl) noexcept { contexted_unique_lock(std::move(__sl)).swap(*this); return *this; } void lock() { _M_lockable(); assert(_M_context); const auto lockWard = _M_context->BeforeLock(_Mutex::mark); if (_M_chkTimeout.count() > 0 && _M_context->isCancelable()) { do { ThrowOnCancel(*_M_context, "Lock was canceled on condition"); } while (!_M_mtx->try_lock_for(_M_chkTimeout)); } else { _M_mtx->lock(); } _M_owns = true; } bool try_lock() { _M_lockable(); return _M_owns = _M_mtx->try_lock(); } void unlock() { if (!_M_owns) assert(0); _M_mtx->unlock(); _M_owns = false; } void swap(contexted_unique_lock& __u) noexcept { std::swap(_M_mtx, __u._M_mtx); std::swap(_M_owns, __u._M_owns); std::swap(_M_context, __u._M_context); std::swap(_M_chkTimeout, __u._M_chkTimeout); } MutexType* release() noexcept { _M_owns = false; auto ret = _M_mtx; _M_mtx = nullptr; return ret; } bool owns_lock() const noexcept { return _M_owns; } explicit operator bool() const noexcept { return _M_owns; } MutexType* mutex() const noexcept { return _M_mtx; } private: void _M_lockable() const { if (_M_mtx == nullptr) assert(0); if (_M_owns) assert(0); } MutexType* _M_mtx; bool _M_owns; Context* _M_context; milliseconds _M_chkTimeout; }; /// Swap specialization for contexted_unique_lock template <typename _Mutex, typename Context1, typename Context2> void swap(contexted_unique_lock<_Mutex, Context1>& __x, contexted_unique_lock<_Mutex, Context2>& __y) noexcept { __x.swap(__y); } template <typename _Mutex, typename Context> class contexted_shared_lock { public: using MutexType = _Mutex; explicit contexted_shared_lock(MutexType& __mtx, Context* __context, milliseconds __chkTimeout = kDefaultCondChkTime) : _M_mtx(&__mtx), _M_owns(false), _M_context(__context), _M_chkTimeout(__chkTimeout) { assert(_M_context); lock(); } ~contexted_shared_lock() { if (_M_owns) _M_mtx->unlock_shared(); } contexted_shared_lock(const contexted_shared_lock&) = delete; contexted_shared_lock& operator=(const contexted_shared_lock&) = delete; contexted_shared_lock(contexted_shared_lock&& __sl) noexcept : contexted_shared_lock() { swap(__sl); } contexted_shared_lock& operator=(contexted_shared_lock&& __sl) noexcept { contexted_shared_lock(std::move(__sl)).swap(*this); return *this; } void lock() { _M_lockable(); assert(_M_context); const auto lockWard = _M_context->BeforeLock(_Mutex::mark); if (_M_chkTimeout.count() > 0 && _M_context->isCancelable()) { do { ThrowOnCancel(*_M_context, "Lock was canceled on condition"); } while (!_M_mtx->try_lock_shared_for(_M_chkTimeout)); } else { _M_mtx->lock_shared(); } _M_owns = true; } bool try_lock() { _M_lockable(); return _M_owns = _M_mtx->try_lock_shared(); } void unlock() { if (!_M_owns) assert(0); _M_mtx->unlock_shared(); _M_owns = false; } void swap(contexted_shared_lock& __u) noexcept { std::swap(_M_mtx, __u._M_mtx); std::swap(_M_owns, __u._M_owns); std::swap(_M_context, __u._M_context); std::swap(_M_chkTimeout, __u._M_chkTimeout); } MutexType* release() noexcept { _M_owns = false; auto ret = _M_mtx; _M_mtx = nullptr; return ret; } bool owns_lock() const noexcept { return _M_owns; } explicit operator bool() const noexcept { return _M_owns; } MutexType* mutex() const noexcept { return _M_mtx; } private: void _M_lockable() const { if (_M_mtx == nullptr) assert(0); if (_M_owns) assert(0); } MutexType* _M_mtx; bool _M_owns; Context* _M_context; milliseconds _M_chkTimeout; }; /// Swap specialization for contexted_shared_lock template <typename _Mutex, typename Context1, typename Context2> void swap(contexted_shared_lock<_Mutex, Context1>& __x, contexted_shared_lock<_Mutex, Context2>& __y) noexcept { __x.swap(__y); } } // namespace reindexer
[ "ogerasimov@gmail.com" ]
ogerasimov@gmail.com
69b2c3c701d76867b0e6ddfee073dab420feb681
0fedf0457748b95c9f5dce90c79d329a4c856c95
/Pattern04c_AbstractFactory/src/PlumTomatoSauce.h
4bf8e79071df4b6e6f77e592907936f3c57b181e
[ "MIT" ]
permissive
MRKonrad/DesignPatternsCpp
21b24e5a114fe53badfb6e549f6a60abeba0895d
b622a4a9e7abc58a304ab138036667253fd199de
refs/heads/master
2021-01-13T03:07:09.404413
2017-03-10T13:25:01
2017-03-10T13:25:01
77,444,552
0
0
null
null
null
null
UTF-8
C++
false
false
370
h
// // PlumTomatoSauce.h // DesignPatternsCPP // // Created by Konrad Werys on 07/03/17. // Copyright © 2016 Konrad Werys. All rights reserved. // #ifndef PlumTomatoSauce_H #define PlumTomatoSauce_H #include <string> #include "Sauce.h" class PlumTomatoSauce : public Sauce{ public: std::string toString(){ return "Plum Tomato Sauce"; } }; #endif
[ "konradwerys@gmail.com" ]
konradwerys@gmail.com
20cae638d79f5a46e176bcb01c3ca0edef924ea5
573b7f2b79b6fb8b21b40985f7639bc003b60f7e
/SDK/BP_RadialVoiceCommands_Parent_functions.cpp
732b68be42e73f270877cf5af2a201198d88092c
[]
no_license
AlexzDK/SquadSDK2021
8d4c29486922fed3ba8451680d823a04a7b7fc44
cdce732ad4713b6d7f668f8b9c39e160035efb34
refs/heads/main
2023-02-21T02:52:15.634663
2021-01-23T23:28:57
2021-01-23T23:28:57
332,328,796
4
0
null
null
null
null
UTF-8
C++
false
false
2,826
cpp
// Name: Squad, Version: 13-01-2021 #include "../pch.h" #ifdef _MSC_VER #pragma pack(push, 0x01) #endif /*!!HELPER_DEF!!*/ /*!!DEFINE!!*/ namespace UFT { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function BP_RadialVoiceCommands_Parent.BP_RadialVoiceCommands_Parent_C.Create Radial Widgets // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UBaseRadialMenu_C* Base_Radial (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void UBP_RadialVoiceCommands_Parent_C::Create_Radial_Widgets(class UBaseRadialMenu_C* Base_Radial) { static auto fn = UObject::FindObject<UFunction>("Function BP_RadialVoiceCommands_Parent.BP_RadialVoiceCommands_Parent_C.Create Radial Widgets"); UBP_RadialVoiceCommands_Parent_C_Create_Radial_Widgets_Params params; params.Base_Radial = Base_Radial; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_RadialVoiceCommands_Parent.BP_RadialVoiceCommands_Parent_C.CreateChildWidgets // (BlueprintCallable, BlueprintEvent) // Parameters: // class UBaseRadialMenu_C* BaseRadialMenu (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void UBP_RadialVoiceCommands_Parent_C::CreateChildWidgets(class UBaseRadialMenu_C* BaseRadialMenu) { static auto fn = UObject::FindObject<UFunction>("Function BP_RadialVoiceCommands_Parent.BP_RadialVoiceCommands_Parent_C.CreateChildWidgets"); UBP_RadialVoiceCommands_Parent_C_CreateChildWidgets_Params params; params.BaseRadialMenu = BaseRadialMenu; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_RadialVoiceCommands_Parent.BP_RadialVoiceCommands_Parent_C.ExecuteUbergraph_BP_RadialVoiceCommands_Parent // (Final) // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void UBP_RadialVoiceCommands_Parent_C::ExecuteUbergraph_BP_RadialVoiceCommands_Parent(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function BP_RadialVoiceCommands_Parent.BP_RadialVoiceCommands_Parent_C.ExecuteUbergraph_BP_RadialVoiceCommands_Parent"); UBP_RadialVoiceCommands_Parent_C_ExecuteUbergraph_BP_RadialVoiceCommands_Parent_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "39485681+AlexzDK@users.noreply.github.com" ]
39485681+AlexzDK@users.noreply.github.com
1ff3302267167868263a9be318f13e6e69651fd0
1885818f5360aa6cdb7c606e8da58b67c67c29c4
/body.hpp
555285a9ec3847308c668e449c3b5509ec58206c
[]
no_license
heinwessels/UniverseSimulator
93e2ea9d1a0b9d3bec7c7cb11c04c1c2322ddb81
bd46b4b9204e3c25ee210fcf0a8242b4a216c5a2
refs/heads/master
2022-11-20T18:51:34.690953
2020-07-23T13:40:54
2020-07-23T13:40:54
258,475,935
0
0
null
null
null
null
UTF-8
C++
false
false
545
hpp
#include <vector> #include "vec3.hpp" #include <stdio.h> #include <cmath> #ifndef BODY_HPP #define BODY_HPP using namespace std; class Body{ public: float mass; // In kg float radius; // In meter Vec3<float> pos; // In meter Vec3<float> speed; // In m / s bool neglible; bool stationary; Vec3<float> last_force; Vec3<float> last_acc; Body(); Body(float mass, float radius, Vec3<float> pos); void apply_force(Vec3<float> force, float time_step); }; #endif
[ "heinwessels93@gmail.com" ]
heinwessels93@gmail.com
0073c3851618c9d80e2a3afc0a9a175b27da674f
51e1cf5dc3b99e8eecffcf5790ada07b2f03f39c
/FileAssistant++/Source/TinyXML/tinyxml.h
13d660573a40d15b918efb0047592e0313bf32cb
[]
no_license
jdek/jim-pspware
c3e043b59a69cf5c28daf62dc9d8dca5daf87589
fd779e1148caac2da4c590844db7235357b47f7e
refs/heads/master
2021-05-31T06:45:03.953631
2007-06-25T22:45:26
2007-06-25T22:45:26
56,973,047
2
1
null
null
null
null
UTF-8
C++
false
false
44,742
h
/* www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com) 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 TINYXML_INCLUDED #define TINYXML_INCLUDED #ifdef _MSC_VER #pragma warning( disable : 4530 ) #pragma warning( disable : 4786 ) #endif #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> // Help out windows: #if defined( _DEBUG ) && !defined( DEBUG ) #define DEBUG #endif #if defined( DEBUG ) && defined( _MSC_VER ) #include <windows.h> #define TIXML_LOG OutputDebugString #else #define TIXML_LOG printf #endif #ifdef TIXML_USE_STL #include <string> #include <iostream> //#include <ostream> #define TIXML_STRING std::string #define TIXML_ISTREAM std::istream #define TIXML_OSTREAM std::ostream #else #include "tinystr.h" #define TIXML_STRING TiXmlString #define TIXML_OSTREAM TiXmlOutStream #endif class TiXmlDocument; class TiXmlElement; class TiXmlComment; class TiXmlUnknown; class TiXmlAttribute; class TiXmlText; class TiXmlDeclaration; class TiXmlParsingData; /* Internal structure for tracking location of items in the XML file. */ struct TiXmlCursor { TiXmlCursor() { Clear(); } void Clear() { row = col = -1; } int row; // 0 based. int col; // 0 based. }; // Only used by Attribute::Query functions enum { TIXML_SUCCESS, TIXML_NO_ATTRIBUTE, TIXML_WRONG_TYPE }; /** TiXmlBase is a base class for every class in TinyXml. It does little except to establish that TinyXml classes can be printed and provide some utility functions. In XML, the document and elements can contain other elements and other types of nodes. @verbatim A Document can contain: Element (container or leaf) Comment (leaf) Unknown (leaf) Declaration( leaf ) An Element can contain: Element (container or leaf) Text (leaf) Attributes (not on tree) Comment (leaf) Unknown (leaf) A Decleration contains: Attributes (not on tree) @endverbatim */ class TiXmlBase { friend class TiXmlNode; friend class TiXmlElement; friend class TiXmlDocument; public: TiXmlBase() {userData = 0;} virtual ~TiXmlBase() {} /** All TinyXml classes can print themselves to a filestream. This is a formatted print, and will insert tabs and newlines. (For an unformatted stream, use the << operator.) */ virtual void Print( FILE* cfile, int depth ) const = 0; /** The world does not agree on whether white space should be kept or not. In order to make everyone happy, these global, static functions are provided to set whether or not TinyXml will condense all white space into a single space or not. The default is to condense. Note changing this values is not thread safe. */ static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; } /// Return the current white space setting. static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; } /** Return the position, in the original source file, of this node or attribute. The row and column are 1-based. (That is the first row and first column is 1,1). If the returns values are 0 or less, then the parser does not have a row and column value. Generally, the row and column value will be set when the TiXmlDocument::Load(), TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set when the DOM was created from operator>>. The values reflect the initial load. Once the DOM is modified programmatically (by adding or changing nodes and attributes) the new values will NOT update to reflect changes in the document. There is a minor performance cost to computing the row and column. Computation can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value. @sa TiXmlDocument::SetTabSize() */ int Row() const { return location.row + 1; } int Column() const { return location.col + 1; } ///< See Row() void SetUserData( void* user ) { userData = user; } void* GetUserData() { return userData; } // Table that returs, for a given lead byte, the total number of bytes // in the UTF-8 sequence. static const int utf8ByteTable[256]; protected: // See STL_STRING_BUG // Utility class to overcome a bug. class StringToBuffer { public: StringToBuffer( const TIXML_STRING& str ); ~StringToBuffer(); char* buffer; }; static const char* SkipWhiteSpace( const char* ); inline static bool IsWhiteSpace( char c ) { return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' ); } virtual void StreamOut (TIXML_OSTREAM *) const = 0; #ifdef TIXML_USE_STL static bool StreamWhiteSpace( TIXML_ISTREAM * in, TIXML_STRING * tag ); static bool StreamTo( TIXML_ISTREAM * in, int character, TIXML_STRING * tag ); #endif /* Reads an XML name into the string provided. Returns a pointer just past the last character of the name, or 0 if the function has an error. */ static const char* ReadName( const char* p, TIXML_STRING* name ); /* Reads text. Returns a pointer past the given end tag. Wickedly complex options, but it keeps the (sensitive) code in one place. */ static const char* ReadText( const char* in, // where to start TIXML_STRING* text, // the string read bool ignoreWhiteSpace, // whether to keep the white space const char* endTag, // what ends this text bool ignoreCase ); // whether to ignore case in the end tag virtual const char* Parse( const char* p, TiXmlParsingData* data ) = 0; // If an entity has been found, transform it into a character. static const char* GetEntity( const char* in, char* value, int* length ); // Get a character, while interpreting entities. // The length can be from 0 to 4 bytes. inline static const char* GetCharUTF8( const char* p, char* _value, int* length ) { assert( p ); *length = utf8ByteTable[ *((unsigned char*)p) ]; assert( *length >= 0 && *length < 5 ); if ( *length == 1 ) { if ( *p == '&' ) return GetEntity( p, _value, length ); *_value = *p; return p+1; } else if ( *length ) { strncpy( _value, p, *length ); return p + (*length); } else { // Not valid text. return 0; } } // Puts a string to a stream, expanding entities as it goes. // Note this should not contian the '<', '>', etc, or they will be transformed into entities! static void PutString( const TIXML_STRING& str, TIXML_OSTREAM* out ); static void PutString( const TIXML_STRING& str, TIXML_STRING* out ); // Return true if the next characters in the stream are any of the endTag sequences. // Ignore case only works for english, and should only be relied on when comparing // to Engilish words: StringEqual( p, "version", true ) is fine. static bool StringEqual( const char* p, const char* endTag, bool ignoreCase ); enum { TIXML_NO_ERROR = 0, TIXML_ERROR, TIXML_ERROR_OPENING_FILE, TIXML_ERROR_OUT_OF_MEMORY, TIXML_ERROR_PARSING_ELEMENT, TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, TIXML_ERROR_READING_ELEMENT_VALUE, TIXML_ERROR_READING_ATTRIBUTES, TIXML_ERROR_PARSING_EMPTY, TIXML_ERROR_READING_END_TAG, TIXML_ERROR_PARSING_UNKNOWN, TIXML_ERROR_PARSING_COMMENT, TIXML_ERROR_PARSING_DECLARATION, TIXML_ERROR_DOCUMENT_EMPTY, TIXML_ERROR_STRING_COUNT }; static const char* errorString[ TIXML_ERROR_STRING_COUNT ]; TiXmlCursor location; /// Field containing a generic user pointer void* userData; // None of these methods are reliable for any language except English. // Good for approximation, not great for accuracy. static int IsAlphaUTF8( unsigned char anyByte ); static int IsAlphaNumUTF8( unsigned char anyByte ); inline static int ToLowerUTF8( int v ) { if ( v < 128 ) return tolower( v ); return v; } static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); private: TiXmlBase( const TiXmlBase& ); // not implemented. void operator=( const TiXmlBase& base ); // not allowed. struct Entity { const char* str; unsigned int strLength; char chr; }; enum { NUM_ENTITY = 5, MAX_ENTITY_LENGTH = 6 }; static Entity entity[ NUM_ENTITY ]; static bool condenseWhiteSpace; }; /** The parent class for everything in the Document Object Model. (Except for attributes). Nodes have siblings, a parent, and children. A node can be in a document, or stand on its own. The type of a TiXmlNode can be queried, and it can be cast to its more defined type. */ class TiXmlNode : public TiXmlBase { friend class TiXmlDocument; friend class TiXmlElement; public: #ifdef TIXML_USE_STL /** An input stream operator, for every class. Tolerant of newlines and formatting, but doesn't expect them. */ friend std::istream& operator >> (std::istream& in, TiXmlNode& base); /** An output stream operator, for every class. Note that this outputs without any newlines or formatting, as opposed to Print(), which includes tabs and new lines. The operator<< and operator>> are not completely symmetric. Writing a node to a stream is very well defined. You'll get a nice stream of output, without any extra whitespace or newlines. But reading is not as well defined. (As it always is.) If you create a TiXmlElement (for example) and read that from an input stream, the text needs to define an element or junk will result. This is true of all input streams, but it's worth keeping in mind. A TiXmlDocument will read nodes until it reads a root element, and all the children of that root element. */ friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base); /// Appends the XML node or attribute to a std::string. friend std::string& operator<< (std::string& out, const TiXmlNode& base ); #else // Used internally, not part of the public API. friend TIXML_OSTREAM& operator<< (TIXML_OSTREAM& out, const TiXmlNode& base); #endif /** The types of XML nodes supported by TinyXml. (All the unsupported types are picked up by UNKNOWN.) */ enum NodeType { DOCUMENT, ELEMENT, COMMENT, UNKNOWN, TEXT, DECLARATION, TYPECOUNT }; virtual ~TiXmlNode(); /** The meaning of 'value' changes for the specific type of TiXmlNode. @verbatim Document: filename of the xml file Element: name of the element Comment: the comment text Unknown: the tag contents Text: the text string @endverbatim The subclasses will wrap this function. */ const char * Value() const { return value.c_str (); } /** Changes the value of the node. Defined as: @verbatim Document: filename of the xml file Element: name of the element Comment: the comment text Unknown: the tag contents Text: the text string @endverbatim */ void SetValue(const char * _value) { value = _value;} #ifdef TIXML_USE_STL /// STL std::string form. void SetValue( const std::string& _value ) { StringToBuffer buf( _value ); SetValue( buf.buffer ? buf.buffer : "" ); } #endif /// Delete all the children of this node. Does not affect 'this'. void Clear(); /// One step up the DOM. TiXmlNode* Parent() const { return parent; } TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children. TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found. TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children. TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children. #ifdef TIXML_USE_STL TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form. TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form. #endif /** An alternate way to walk the children of a node. One way to iterate over nodes is: @verbatim for( child = parent->FirstChild(); child; child = child->NextSibling() ) @endverbatim IterateChildren does the same thing with the syntax: @verbatim child = 0; while( child = parent->IterateChildren( child ) ) @endverbatim IterateChildren takes the previous child as input and finds the next one. If the previous child is null, it returns the first. IterateChildren will return null when done. */ TiXmlNode* IterateChildren( TiXmlNode* previous ) const; /// This flavor of IterateChildren searches for children with a particular 'value' TiXmlNode* IterateChildren( const char * value, TiXmlNode* previous ) const; #ifdef TIXML_USE_STL TiXmlNode* IterateChildren( const std::string& _value, TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. #endif /** Add a new node related to this. Adds a child past the LastChild. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertEndChild( const TiXmlNode& addThis ); /** Add a new node related to this. Adds a child past the LastChild. NOTE: the node to be added is passed by pointer, and will be henceforth owned (and deleted) by tinyXml. This method is efficient and avoids an extra copy, but should be used with care as it uses a different memory model than the other insert functions. @sa InsertEndChild */ TiXmlNode* LinkEndChild( TiXmlNode* addThis ); /** Add a new node related to this. Adds a child before the specified child. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ); /** Add a new node related to this. Adds a child after the specified child. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ); /** Replace a child of this node. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); /// Delete a child of this node. bool RemoveChild( TiXmlNode* removeThis ); /// Navigate to a sibling node. TiXmlNode* PreviousSibling() const { return prev; } /// Navigate to a sibling node. TiXmlNode* PreviousSibling( const char * ) const; #ifdef TIXML_USE_STL TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form. #endif /// Navigate to a sibling node. TiXmlNode* NextSibling() const { return next; } /// Navigate to a sibling node with the given 'value'. TiXmlNode* NextSibling( const char * ) const; /** Convenience function to get through elements. Calls NextSibling and ToElement. Will skip all non-Element nodes. Returns 0 if there is not another element. */ TiXmlElement* NextSiblingElement() const; /** Convenience function to get through elements. Calls NextSibling and ToElement. Will skip all non-Element nodes. Returns 0 if there is not another element. */ TiXmlElement* NextSiblingElement( const char * ) const; #ifdef TIXML_USE_STL TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. #endif /// Convenience function to get through elements. TiXmlElement* FirstChildElement() const; /// Convenience function to get through elements. TiXmlElement* FirstChildElement( const char * value ) const; #ifdef TIXML_USE_STL TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. #endif /** Query the type (as an enumerated value, above) of this node. The possible types are: DOCUMENT, ELEMENT, COMMENT, UNKNOWN, TEXT, and DECLARATION. */ virtual int Type() const { return type; } /** Return a pointer to the Document this node lives in. Returns null if not in a document. */ TiXmlDocument* GetDocument() const; /// Returns true if this node has no children. bool NoChildren() const { return !firstChild; } TiXmlDocument* ToDocument() const { return ( this && type == DOCUMENT ) ? (TiXmlDocument*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlElement* ToElement() const { return ( this && type == ELEMENT ) ? (TiXmlElement*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlComment* ToComment() const { return ( this && type == COMMENT ) ? (TiXmlComment*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlUnknown* ToUnknown() const { return ( this && type == UNKNOWN ) ? (TiXmlUnknown*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlText* ToText() const { return ( this && type == TEXT ) ? (TiXmlText*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlDeclaration* ToDeclaration() const { return ( this && type == DECLARATION ) ? (TiXmlDeclaration*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlNode* Clone() const = 0; protected: TiXmlNode( NodeType _type ); #ifdef TIXML_USE_STL // The real work of the input operator. virtual void StreamIn( TIXML_ISTREAM* in, TIXML_STRING* tag ) = 0; #endif // Figure out what is at *p, and parse it. Returns null if it is not an xml node. TiXmlNode* Identify( const char* start ); void CopyToClone( TiXmlNode* target ) const { target->SetValue (value.c_str() ); target->userData = userData; } // Internal Value function returning a TIXML_STRING const TIXML_STRING& SValue() const { return value ; } TiXmlNode* parent; NodeType type; TiXmlNode* firstChild; TiXmlNode* lastChild; TIXML_STRING value; TiXmlNode* prev; TiXmlNode* next; private: TiXmlNode( const TiXmlNode& ); // not implemented. void operator=( const TiXmlNode& base ); // not allowed. }; /** An attribute is a name-value pair. Elements have an arbitrary number of attributes, each with a unique name. @note The attributes are not TiXmlNodes, since they are not part of the tinyXML document object model. There are other suggested ways to look at this problem. */ class TiXmlAttribute : public TiXmlBase { friend class TiXmlAttributeSet; public: /// Construct an empty attribute. TiXmlAttribute() : TiXmlBase() { document = 0; prev = next = 0; } #ifdef TIXML_USE_STL /// std::string constructor. TiXmlAttribute( const std::string& _name, const std::string& _value ) { name = _name; value = _value; document = 0; prev = next = 0; } #endif /// Construct an attribute with a name and value. TiXmlAttribute( const char * _name, const char * _value ) { name = _name; value = _value; document = 0; prev = next = 0; } const char* Name() const { return name.c_str (); } ///< Return the name of this attribute. const char* Value() const { return value.c_str (); } ///< Return the value of this attribute. const int IntValue() const; ///< Return the value of this attribute, converted to an integer. const double DoubleValue() const; ///< Return the value of this attribute, converted to a double. /** QueryIntValue examines the value string. It is an alternative to the IntValue() method with richer error checking. If the value is an integer, it is stored in 'value' and the call returns TIXML_SUCCESS. If it is not an integer, it returns TIXML_WRONG_TYPE. A specialized but useful call. Note that for success it returns 0, which is the opposite of almost all other TinyXml calls. */ int QueryIntValue( int* value ) const; /// QueryDoubleValue examines the value string. See QueryIntValue(). int QueryDoubleValue( double* value ) const; void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute. void SetValue( const char* _value ) { value = _value; } ///< Set the value. void SetIntValue( int value ); ///< Set the value from an integer. void SetDoubleValue( double value ); ///< Set the value from a double. #ifdef TIXML_USE_STL /// STL std::string form. void SetName( const std::string& _name ) { StringToBuffer buf( _name ); SetName ( buf.buffer ? buf.buffer : "error" ); } /// STL std::string form. void SetValue( const std::string& _value ) { StringToBuffer buf( _value ); SetValue( buf.buffer ? buf.buffer : "error" ); } #endif /// Get the next sibling attribute in the DOM. Returns null at end. TiXmlAttribute* Next() const; /// Get the previous sibling attribute in the DOM. Returns null at beginning. TiXmlAttribute* Previous() const; bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; } bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; } bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; } /* [internal use] Attribtue parsing starts: first letter of the name returns: the next char after the value end quote */ virtual const char* Parse( const char* p, TiXmlParsingData* data ); // [internal use] virtual void Print( FILE* cfile, int depth ) const; virtual void StreamOut( TIXML_OSTREAM * out ) const; // [internal use] // Set the document pointer so the attribute can report errors. void SetDocument( TiXmlDocument* doc ) { document = doc; } private: TiXmlAttribute( const TiXmlAttribute& ); // not implemented. void operator=( const TiXmlAttribute& base ); // not allowed. TiXmlDocument* document; // A pointer back to a document, for error reporting. TIXML_STRING name; TIXML_STRING value; TiXmlAttribute* prev; TiXmlAttribute* next; }; /* A class used to manage a group of attributes. It is only used internally, both by the ELEMENT and the DECLARATION. The set can be changed transparent to the Element and Declaration classes that use it, but NOT transparent to the Attribute which has to implement a next() and previous() method. Which makes it a bit problematic and prevents the use of STL. This version is implemented with circular lists because: - I like circular lists - it demonstrates some independence from the (typical) doubly linked list. */ class TiXmlAttributeSet { public: TiXmlAttributeSet(); ~TiXmlAttributeSet(); void Add( TiXmlAttribute* attribute ); void Remove( TiXmlAttribute* attribute ); TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } TiXmlAttribute* Find( const char * name ) const; private: TiXmlAttribute sentinel; }; /** The element is a container class. It has a value, the element name, and can contain other elements, text, comments, and unknowns. Elements also contain an arbitrary number of attributes. */ class TiXmlElement : public TiXmlNode { public: /// Construct an element. TiXmlElement (const char * in_value); #ifdef TIXML_USE_STL /// std::string constructor. TiXmlElement( const std::string& _value ) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } #endif virtual ~TiXmlElement(); /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. */ const char* Attribute( const char* name ) const; /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. If the attribute exists and can be converted to an integer, the integer value will be put in the return 'i', if 'i' is non-null. */ const char* Attribute( const char* name, int* i ) const; /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. If the attribute exists and can be converted to an double, the double value will be put in the return 'd', if 'd' is non-null. */ const char* Attribute( const char* name, double* d ) const; /** QueryIntAttribute examines the attribute - it is an alternative to the Attribute() method with richer error checking. If the attribute is an integer, it is stored in 'value' and the call returns TIXML_SUCCESS. If it is not an integer, it returns TIXML_WRONG_TYPE. If the attribute does not exist, then TIXML_NO_ATTRIBUTE is returned. */ int QueryIntAttribute( const char* name, int* value ) const; /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute(). int QueryDoubleAttribute( const char* name, double* value ) const; /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetAttribute( const char* name, const char * value ); #ifdef TIXML_USE_STL const char* Attribute( const std::string& name ) const { return Attribute( name.c_str() ); } const char* Attribute( const std::string& name, int* i ) const { return Attribute( name.c_str(), i ); } /// STL std::string form. void SetAttribute( const std::string& name, const std::string& _value ) { StringToBuffer n( name ); StringToBuffer v( _value ); if ( n.buffer && v.buffer ) SetAttribute (n.buffer, v.buffer ); } ///< STL std::string form. void SetAttribute( const std::string& name, int _value ) { StringToBuffer n( name ); if ( n.buffer ) SetAttribute (n.buffer, _value); } #endif /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetAttribute( const char * name, int value ); /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetDoubleAttribute( const char * name, double value ); /** Deletes an attribute with the given name. */ void RemoveAttribute( const char * name ); #ifdef TIXML_USE_STL void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form. #endif TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element. TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element. // [internal use] Creates a new Element and returs it. virtual TiXmlNode* Clone() const; // [internal use] virtual void Print( FILE* cfile, int depth ) const; protected: // Used to be public [internal use] #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif virtual void StreamOut( TIXML_OSTREAM * out ) const; /* [internal use] Attribtue parsing starts: next char past '<' returns: next char past '>' */ virtual const char* Parse( const char* p, TiXmlParsingData* data ); /* [internal use] Reads the "value" of the element -- another element, or text. This should terminate with the current end tag. */ const char* ReadValue( const char* in, TiXmlParsingData* prevData ); private: TiXmlElement( const TiXmlElement& ); // not implemented. void operator=( const TiXmlElement& base ); // not allowed. TiXmlAttributeSet attributeSet; }; /** An XML comment. */ class TiXmlComment : public TiXmlNode { public: /// Constructs an empty comment. TiXmlComment() : TiXmlNode( TiXmlNode::COMMENT ) {} virtual ~TiXmlComment() {} // [internal use] Creates a new Element and returs it. virtual TiXmlNode* Clone() const; // [internal use] virtual void Print( FILE* cfile, int depth ) const; protected: // used to be public #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif virtual void StreamOut( TIXML_OSTREAM * out ) const; /* [internal use] Attribtue parsing starts: at the ! of the !-- returns: next char past '>' */ virtual const char* Parse( const char* p, TiXmlParsingData* data ); private: TiXmlComment( const TiXmlComment& ); // not implemented. void operator=( const TiXmlComment& base ); // not allowed. }; /** XML text. Contained in an element. */ class TiXmlText : public TiXmlNode { friend class TiXmlElement; public: /// Constructor. TiXmlText (const char * initValue) : TiXmlNode (TiXmlNode::TEXT) { SetValue( initValue ); } virtual ~TiXmlText() {} #ifdef TIXML_USE_STL /// Constructor. TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TEXT) { SetValue( initValue ); } #endif // [internal use] virtual void Print( FILE* cfile, int depth ) const; protected : // [internal use] Creates a new Element and returns it. virtual TiXmlNode* Clone() const; virtual void StreamOut ( TIXML_OSTREAM * out ) const; // [internal use] bool Blank() const; // returns true if all white space and new lines /* [internal use] Attribtue parsing starts: First char of the text returns: next char past '>' */ virtual const char* Parse( const char* p, TiXmlParsingData* data ); // [internal use] #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif private: TiXmlText( const TiXmlText& ); // not implemented. void operator=( const TiXmlText& base ); // not allowed. }; /** In correct XML the declaration is the first entry in the file. @verbatim <?xml version="1.0" standalone="yes"?> @endverbatim TinyXml will happily read or write files without a declaration, however. There are 3 possible attributes to the declaration: version, encoding, and standalone. Note: In this version of the code, the attributes are handled as special cases, not generic attributes, simply because there can only be at most 3 and they are always the same. */ class TiXmlDeclaration : public TiXmlNode { public: /// Construct an empty declaration. TiXmlDeclaration() : TiXmlNode( TiXmlNode::DECLARATION ) {} #ifdef TIXML_USE_STL /// Constructor. TiXmlDeclaration( const std::string& _version, const std::string& _encoding, const std::string& _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } #endif /// Construct. TiXmlDeclaration( const char* _version, const char* _encoding, const char* _standalone ); virtual ~TiXmlDeclaration() {} /// Version. Will return empty if none was found. const char * Version() const { return version.c_str (); } /// Encoding. Will return empty if none was found. const char * Encoding() const { return encoding.c_str (); } /// Is this a standalone document? const char * Standalone() const { return standalone.c_str (); } // [internal use] Creates a new Element and returs it. virtual TiXmlNode* Clone() const; // [internal use] virtual void Print( FILE* cfile, int depth ) const; protected: // used to be public #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif virtual void StreamOut ( TIXML_OSTREAM * out) const; // [internal use] // Attribtue parsing starts: next char past '<' // returns: next char past '>' virtual const char* Parse( const char* p, TiXmlParsingData* data ); private: TiXmlDeclaration( const TiXmlDeclaration& copy ); void operator=( const TiXmlDeclaration& copy ); TIXML_STRING version; TIXML_STRING encoding; TIXML_STRING standalone; }; /** Any tag that tinyXml doesn't recognize is saved as an unknown. It is a tag of text, but should not be modified. It will be written back to the XML, unchanged, when the file is saved. DTD tags get thrown into TiXmlUnknowns. */ class TiXmlUnknown : public TiXmlNode { public: TiXmlUnknown() : TiXmlNode( TiXmlNode::UNKNOWN ) {} virtual ~TiXmlUnknown() {} // [internal use] virtual TiXmlNode* Clone() const; // [internal use] virtual void Print( FILE* cfile, int depth ) const; protected: #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif virtual void StreamOut ( TIXML_OSTREAM * out ) const; /* [internal use] Attribute parsing starts: First char of the text returns: next char past '>' */ virtual const char* Parse( const char* p, TiXmlParsingData* data ); private: TiXmlUnknown( const TiXmlUnknown& copy ); void operator=( const TiXmlUnknown& copy ); }; /** Always the top level node. A document binds together all the XML pieces. It can be saved, loaded, and printed to the screen. The 'value' of a document node is the xml file name. */ class TiXmlDocument : public TiXmlNode { public: /// Create an empty document, that has no name. TiXmlDocument(); /// Create a document with a name. The name of the document is also the filename of the xml. TiXmlDocument( const char * documentName ); #ifdef TIXML_USE_STL /// Constructor. TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { value = documentName; error = false; } #endif virtual ~TiXmlDocument() {} /** Load a file using the current document value. Returns true if successful. Will delete any existing document data before loading. */ bool LoadFile(); /// Save a file using the current document value. Returns true if successful. bool SaveFile() const; /// Load a file using the given filename. Returns true if successful. bool LoadFile( const char * filename ); /// Save a file using the given filename. Returns true if successful. bool SaveFile( const char * filename ) const; #ifdef TIXML_USE_STL bool LoadFile( const std::string& filename ) ///< STL std::string version. { StringToBuffer f( filename ); return ( f.buffer && LoadFile( f.buffer )); } bool SaveFile( const std::string& filename ) const ///< STL std::string version. { StringToBuffer f( filename ); return ( f.buffer && SaveFile( f.buffer )); } #endif /** Parse the given null terminated block of xml data. */ virtual const char* Parse( const char* p, TiXmlParsingData* data = 0 ); /** Get the root element -- the only top level element -- of the document. In well formed XML, there should only be one. TinyXml is tolerant of multiple elements at the document level. */ TiXmlElement* RootElement() const { return FirstChildElement(); } /** If an error occurs, Error will be set to true. Also, - The ErrorId() will contain the integer identifier of the error (not generally useful) - The ErrorDesc() method will return the name of the error. (very useful) - The ErrorRow() and ErrorCol() will return the location of the error (if known) */ bool Error() const { return error; } /// Contains a textual (english) description of the error if one occurs. const char * ErrorDesc() const { return errorDesc.c_str (); } /** Generally, you probably want the error string ( ErrorDesc() ). But if you prefer the ErrorId, this function will fetch it. */ const int ErrorId() const { return errorId; } /** Returns the location (if known) of the error. The first column is column 1, and the first row is row 1. A value of 0 means the row and column wasn't applicable (memory errors, for example, have no row/column) or the parser lost the error. (An error in the error reporting, in that case.) @sa SetTabSize, Row, Column */ int ErrorRow() { return errorLocation.row+1; } int ErrorCol() { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow() /** By calling this method, with a tab size greater than 0, the row and column of each node and attribute is stored when the file is loaded. Very useful for tracking the DOM back in to the source file. The tab size is required for calculating the location of nodes. If not set, the default of 4 is used. The tabsize is set per document. Setting the tabsize to 0 disables row/column tracking. Note that row and column tracking is not supported when using operator>>. The tab size needs to be enabled before the parse or load. Correct usage: @verbatim TiXmlDocument doc; doc.SetTabSize( 8 ); doc.Load( "myfile.xml" ); @endverbatim @sa Row, Column */ void SetTabSize( int _tabsize ) { tabsize = _tabsize; } int TabSize() const { return tabsize; } /** If you have handled the error, it can be reset with this call. The error state is automatically cleared if you Parse a new XML block. */ void ClearError() { error = false; errorId = 0; errorDesc = ""; errorLocation.row = errorLocation.col = 0; //errorLocation.last = 0; } /** Dump the document to standard out. */ void Print() const { Print( stdout, 0 ); } // [internal use] virtual void Print( FILE* cfile, int depth = 0 ) const; // [internal use] void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData ); protected : virtual void StreamOut ( TIXML_OSTREAM * out) const; // [internal use] virtual TiXmlNode* Clone() const; #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif private: TiXmlDocument( const TiXmlDocument& copy ); void operator=( const TiXmlDocument& copy ); bool error; int errorId; TIXML_STRING errorDesc; int tabsize; TiXmlCursor errorLocation; }; /** A TiXmlHandle is a class that wraps a node pointer with null checks; this is an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml DOM structure. It is a separate utility class. Take an example: @verbatim <Document> <Element attributeA = "valueA"> <Child attributeB = "value1" /> <Child attributeB = "value2" /> </Element> <Document> @endverbatim Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very easy to write a *lot* of code that looks like: @verbatim TiXmlElement* root = document.FirstChildElement( "Document" ); if ( root ) { TiXmlElement* element = root->FirstChildElement( "Element" ); if ( element ) { TiXmlElement* child = element->FirstChildElement( "Child" ); if ( child ) { TiXmlElement* child2 = child->NextSiblingElement( "Child" ); if ( child2 ) { // Finally do something useful. @endverbatim And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity of such code. A TiXmlHandle checks for null pointers so it is perfectly safe and correct to use: @verbatim TiXmlHandle docHandle( &document ); TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).Element(); if ( child2 ) { // do something useful @endverbatim Which is MUCH more concise and useful. It is also safe to copy handles - internally they are nothing more than node pointers. @verbatim TiXmlHandle handleCopy = handle; @endverbatim What they should not be used for is iteration: @verbatim int i=0; while ( true ) { TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).Element(); if ( !child ) break; // do something ++i; } @endverbatim It seems reasonable, but it is in fact two embedded while loops. The Child method is a linear walk to find the element, so this code would iterate much more than it needs to. Instead, prefer: @verbatim TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild( "Child" ).Element(); for( child; child; child=child->NextSiblingElement() ) { // do something } @endverbatim */ class TiXmlHandle { public: /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. TiXmlHandle( TiXmlNode* node ) { this->node = node; } /// Copy constructor TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; } TiXmlHandle operator=( const TiXmlHandle& ref ) { this->node = ref.node; return *this; } /// Return a handle to the first child node. TiXmlHandle FirstChild() const; /// Return a handle to the first child node with the given name. TiXmlHandle FirstChild( const char * value ) const; /// Return a handle to the first child element. TiXmlHandle FirstChildElement() const; /// Return a handle to the first child element with the given name. TiXmlHandle FirstChildElement( const char * value ) const; /** Return a handle to the "index" child with the given name. The first child is 0, the second 1, etc. */ TiXmlHandle Child( const char* value, int index ) const; /** Return a handle to the "index" child. The first child is 0, the second 1, etc. */ TiXmlHandle Child( int index ) const; /** Return a handle to the "index" child element with the given name. The first child element is 0, the second 1, etc. Note that only TiXmlElements are indexed: other types are not counted. */ TiXmlHandle ChildElement( const char* value, int index ) const; /** Return a handle to the "index" child element. The first child element is 0, the second 1, etc. Note that only TiXmlElements are indexed: other types are not counted. */ TiXmlHandle ChildElement( int index ) const; #ifdef TIXML_USE_STL TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); } TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); } TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); } TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); } #endif /// Return the handle as a TiXmlNode. This may return null. TiXmlNode* Node() const { return node; } /// Return the handle as a TiXmlElement. This may return null. TiXmlElement* Element() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); } /// Return the handle as a TiXmlText. This may return null. TiXmlText* Text() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); } /// Return the handle as a TiXmlUnknown. This may return null; TiXmlUnknown* Unknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); } private: TiXmlNode* node; }; #endif
[ "71m@ff2c0c17-07fa-0310-a4bd-d48831021cb5" ]
71m@ff2c0c17-07fa-0310-a4bd-d48831021cb5
3cf0d7ff6341bebc1a230950fd7e401d8661078b
85ad2ac4b9a27fc3dee00b6134943bed9af83974
/src/test/sanity_tests.cpp
1993d06f12f3f1b13d1bdbca83138bf07af61490
[ "MIT" ]
permissive
rubcoin-project/rubcoin
f1c10e5a059608745683166e8ced5a5c5f8f2511
2ad66110ed9d49e28b26ed1d95dcc7af0d32ea94
refs/heads/master
2021-05-04T21:46:38.090301
2018-02-02T11:32:18
2018-02-02T11:32:18
113,016,355
0
0
null
null
null
null
UTF-8
C++
false
false
657
cpp
// Copyright (c) 2012-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "compat/sanity.h" #include "key.h" #include "test/test_rubcoin.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(basic_sanity) { BOOST_CHECK_MESSAGE(glibc_sanity_test() == true, "libc sanity test"); BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test"); BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test"); } BOOST_AUTO_TEST_SUITE_END()
[ "debian@debian" ]
debian@debian
13b9b78a734242e6cea4180a1b345ee345609acc
0352d41242bbe634679897acc53fc2a9988617ce
/hacks/LilyPurse/led.ino
f41be8cbc8df5f609a6893e9c24a5725cc56b292
[]
no_license
kotharitrisha/reminderBag
f3395c5fc8a781cd9042db1f585531a1c6fe18f4
1748be1a439a559138af7b8c053728eb77c46cde
refs/heads/master
2020-05-18T01:09:06.808589
2014-03-04T14:16:40
2014-03-04T14:16:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,442
ino
int ledp = 12; int ledi = 9; int ledu = 5; int buzzer = 3; int photocellPin = 0; int val = 0; char ibyte; char discon; void setup() { //SETUP pinMode(ledi,OUTPUT); pinMode(ledu,OUTPUT); pinMode(ledp,OUTPUT); pinMode(buzzer,OUTPUT); Serial.begin(115200); } void loop() { /* while(1){ digitalWrite(buzzer,HIGH); delay(1000); digitalWrite(buzzer,LOW); delay(1000); }*/ // Wait for data while (Serial.available() == 0){ digitalWrite(ledi,LOW); digitalWrite(ledp,LOW); digitalWrite(ledu,LOW); digitalWrite(buzzer,LOW); } //if (Serial.available()) //digitalWrite(led,HIGH); // Read byte and light LEDs accordingly ibyte = Serial.read(); // if (Serial.available()) // discon = Serial.read(); // if (discon == 'd') // break; if (ibyte == 'p'){ digitalWrite(ledp,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledp,LOW); digitalWrite(buzzer,LOW); delay(2000); digitalWrite(ledp,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledp,LOW); digitalWrite(buzzer,LOW); delay(2000); digitalWrite(ledp,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledp,LOW); digitalWrite(buzzer,LOW); delay(2000); digitalWrite(ledp,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledp,LOW); digitalWrite(buzzer,LOW); delay(2000); digitalWrite(ledp,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledp,LOW); digitalWrite(buzzer,LOW); delay(2000); } if (ibyte == 'i'){ digitalWrite(ledi,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledi,LOW); digitalWrite(buzzer,LOW); delay(2000); digitalWrite(ledi,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledi,LOW); digitalWrite(buzzer,LOW); delay(2000); digitalWrite(ledi,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledi,LOW); digitalWrite(buzzer,LOW); delay(2000); digitalWrite(ledi,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledi,LOW); digitalWrite(buzzer,LOW); delay(2000); digitalWrite(ledi,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledi,LOW); digitalWrite(buzzer,LOW); delay(2000); } if (ibyte == 'u'){ digitalWrite(ledu,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledu,LOW); digitalWrite(buzzer,LOW); delay(2000); digitalWrite(ledu,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledu,LOW); digitalWrite(buzzer,LOW); delay(2000); digitalWrite(ledu,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledu,LOW); digitalWrite(buzzer,LOW); delay(2000); digitalWrite(ledu,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledu,LOW); digitalWrite(buzzer,LOW); delay(2000); digitalWrite(ledu,HIGH); digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(ledu,LOW); digitalWrite(buzzer,LOW); delay(2000); } // Serial.flush(); while(Serial.available()>0) Serial.read(); }
[ "kotharitrisha@gmail.com" ]
kotharitrisha@gmail.com
93b00fba0fd891e48bb9d9e2ec59f737d89b7434
94dbfcf94dd0a61d7cd197cf996602d5a2acdda7
/weekly_contest/344/2672_number-of-adjacent-elements-with-the-same-color.cpp
a8021d273f072b2968aa0f05997e60ec98425b8e
[]
no_license
PengJi/Algorithms
46ac90691cc20b0f769374ac3d848a26766965b1
6aa26240679bc209a6fd69580b9c7994cef51b54
refs/heads/master
2023-07-21T05:57:50.637703
2023-07-07T10:16:48
2023-07-09T10:17:10
243,935,787
0
0
null
null
null
null
UTF-8
C++
false
false
870
cpp
/** * 2672. 有相同颜色的相邻元素数目 * https://leetcode.cn/problems/number-of-adjacent-elements-with-the-same-color/ */ class Solution { public: vector<int> colorTheArray(int n, vector<vector<int>>& queries) { vector<int> nums(n, 0); const int m = queries.size(); vector<int> ans(m); int cur = 0; for (int i = 0; i < m; i++) { int idx = queries[i][0], col = queries[i][1]; if (idx > 0) { if (nums[idx] > 0 && nums[idx - 1] == nums[idx]) --cur; if (nums[idx - 1] == col) ++cur; } if (idx < n - 1) { if (nums[idx] > 0 && nums[idx] == nums[idx + 1]) --cur; if (col == nums[idx + 1]) ++cur; } nums[idx] = col; ans[i] = cur; } return ans; } };
[ "jipengpro@gmail.com" ]
jipengpro@gmail.com
ae9fc384ebe1f13890ebec77c2ad9d8e92d8540a
fcc132131b929998a4bea75cf0ce9492daecb3ac
/gquiche/quic/core/congestion_control/tcp_cubic_sender_bytes.cc
1a3409c02d0ffd0c797c0456679c6f540d1be2b3
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
Moxoo/quiche
0fc8eaab5705c40b2d13b71fe98448407f980af0
16a9562e5040eeac7263ace423fedaf7202f24c5
refs/heads/main
2023-06-17T21:17:18.913695
2021-07-14T03:59:08
2021-07-14T03:59:08
382,257,508
0
0
Apache-2.0
2021-07-02T06:52:12
2021-07-02T06:52:11
null
UTF-8
C++
false
false
15,890
cc
// Copyright (c) 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gquiche/quic/core/congestion_control/tcp_cubic_sender_bytes.h" #include <algorithm> #include <cstdint> #include <string> #include "gquiche/quic/core/congestion_control/prr_sender.h" #include "gquiche/quic/core/congestion_control/rtt_stats.h" #include "gquiche/quic/core/crypto/crypto_protocol.h" #include "gquiche/quic/core/quic_constants.h" #include "gquiche/quic/platform/api/quic_bug_tracker.h" #include "gquiche/quic/platform/api/quic_flags.h" #include "gquiche/quic/platform/api/quic_logging.h" namespace quic { namespace { // Constants based on TCP defaults. const QuicByteCount kMaxBurstBytes = 3 * kDefaultTCPMSS; const float kRenoBeta = 0.7f; // Reno backoff factor. // The minimum cwnd based on RFC 3782 (TCP NewReno) for cwnd reductions on a // fast retransmission. const QuicByteCount kDefaultMinimumCongestionWindow = 2 * kDefaultTCPMSS; } // namespace TcpCubicSenderBytes::TcpCubicSenderBytes( const QuicClock* clock, const RttStats* rtt_stats, bool reno, QuicPacketCount initial_tcp_congestion_window, QuicPacketCount max_congestion_window, QuicConnectionStats* stats) : rtt_stats_(rtt_stats), stats_(stats), reno_(reno), num_connections_(kDefaultNumConnections), min4_mode_(false), last_cutback_exited_slowstart_(false), slow_start_large_reduction_(false), no_prr_(false), cubic_(clock), num_acked_packets_(0), congestion_window_(initial_tcp_congestion_window * kDefaultTCPMSS), min_congestion_window_(kDefaultMinimumCongestionWindow), max_congestion_window_(max_congestion_window * kDefaultTCPMSS), slowstart_threshold_(max_congestion_window * kDefaultTCPMSS), initial_tcp_congestion_window_(initial_tcp_congestion_window * kDefaultTCPMSS), initial_max_tcp_congestion_window_(max_congestion_window * kDefaultTCPMSS), min_slow_start_exit_window_(min_congestion_window_) {} TcpCubicSenderBytes::~TcpCubicSenderBytes() {} void TcpCubicSenderBytes::SetFromConfig(const QuicConfig& config, Perspective perspective) { if (perspective == Perspective::IS_SERVER) { if (!GetQuicReloadableFlag(quic_unified_iw_options)) { if (config.HasReceivedConnectionOptions() && ContainsQuicTag(config.ReceivedConnectionOptions(), kIW03)) { // Initial window experiment. SetInitialCongestionWindowInPackets(3); } if (config.HasReceivedConnectionOptions() && ContainsQuicTag(config.ReceivedConnectionOptions(), kIW10)) { // Initial window experiment. SetInitialCongestionWindowInPackets(10); } if (config.HasReceivedConnectionOptions() && ContainsQuicTag(config.ReceivedConnectionOptions(), kIW20)) { // Initial window experiment. SetInitialCongestionWindowInPackets(20); } if (config.HasReceivedConnectionOptions() && ContainsQuicTag(config.ReceivedConnectionOptions(), kIW50)) { // Initial window experiment. SetInitialCongestionWindowInPackets(50); } if (config.HasReceivedConnectionOptions() && ContainsQuicTag(config.ReceivedConnectionOptions(), kMIN1)) { // Min CWND experiment. SetMinCongestionWindowInPackets(1); } } if (config.HasReceivedConnectionOptions() && ContainsQuicTag(config.ReceivedConnectionOptions(), kMIN4)) { // Min CWND of 4 experiment. min4_mode_ = true; SetMinCongestionWindowInPackets(1); } if (config.HasReceivedConnectionOptions() && ContainsQuicTag(config.ReceivedConnectionOptions(), kSSLR)) { // Slow Start Fast Exit experiment. slow_start_large_reduction_ = true; } if (config.HasReceivedConnectionOptions() && ContainsQuicTag(config.ReceivedConnectionOptions(), kNPRR)) { // Use unity pacing instead of PRR. no_prr_ = true; } } } void TcpCubicSenderBytes::AdjustNetworkParameters(const NetworkParams& params) { if (params.bandwidth.IsZero() || params.rtt.IsZero()) { return; } SetCongestionWindowFromBandwidthAndRtt(params.bandwidth, params.rtt); } float TcpCubicSenderBytes::RenoBeta() const { // kNConnectionBeta is the backoff factor after loss for our N-connection // emulation, which emulates the effective backoff of an ensemble of N // TCP-Reno connections on a single loss event. The effective multiplier is // computed as: return (num_connections_ - 1 + kRenoBeta) / num_connections_; } void TcpCubicSenderBytes::OnCongestionEvent( bool rtt_updated, QuicByteCount prior_in_flight, QuicTime event_time, const AckedPacketVector& acked_packets, const LostPacketVector& lost_packets) { if (rtt_updated && InSlowStart() && hybrid_slow_start_.ShouldExitSlowStart( rtt_stats_->latest_rtt(), rtt_stats_->min_rtt(), GetCongestionWindow() / kDefaultTCPMSS)) { ExitSlowstart(); } for (const LostPacket& lost_packet : lost_packets) { OnPacketLost(lost_packet.packet_number, lost_packet.bytes_lost, prior_in_flight); } for (const AckedPacket& acked_packet : acked_packets) { OnPacketAcked(acked_packet.packet_number, acked_packet.bytes_acked, prior_in_flight, event_time); } } void TcpCubicSenderBytes::OnPacketAcked(QuicPacketNumber acked_packet_number, QuicByteCount acked_bytes, QuicByteCount prior_in_flight, QuicTime event_time) { largest_acked_packet_number_.UpdateMax(acked_packet_number); if (InRecovery()) { if (!no_prr_) { // PRR is used when in recovery. prr_.OnPacketAcked(acked_bytes); } return; } MaybeIncreaseCwnd(acked_packet_number, acked_bytes, prior_in_flight, event_time); if (InSlowStart()) { hybrid_slow_start_.OnPacketAcked(acked_packet_number); } } void TcpCubicSenderBytes::OnPacketSent( QuicTime /*sent_time*/, QuicByteCount /*bytes_in_flight*/, QuicPacketNumber packet_number, QuicByteCount bytes, HasRetransmittableData is_retransmittable) { if (InSlowStart()) { ++(stats_->slowstart_packets_sent); } if (is_retransmittable != HAS_RETRANSMITTABLE_DATA) { return; } if (InRecovery()) { // PRR is used when in recovery. prr_.OnPacketSent(bytes); } QUICHE_DCHECK(!largest_sent_packet_number_.IsInitialized() || largest_sent_packet_number_ < packet_number); largest_sent_packet_number_ = packet_number; hybrid_slow_start_.OnPacketSent(packet_number); } bool TcpCubicSenderBytes::CanSend(QuicByteCount bytes_in_flight) { if (!no_prr_ && InRecovery()) { // PRR is used when in recovery. return prr_.CanSend(GetCongestionWindow(), bytes_in_flight, GetSlowStartThreshold()); } if (GetCongestionWindow() > bytes_in_flight) { return true; } if (min4_mode_ && bytes_in_flight < 4 * kDefaultTCPMSS) { return true; } return false; } QuicBandwidth TcpCubicSenderBytes::PacingRate( QuicByteCount /* bytes_in_flight */) const { // We pace at twice the rate of the underlying sender's bandwidth estimate // during slow start and 1.25x during congestion avoidance to ensure pacing // doesn't prevent us from filling the window. QuicTime::Delta srtt = rtt_stats_->SmoothedOrInitialRtt(); const QuicBandwidth bandwidth = QuicBandwidth::FromBytesAndTimeDelta(GetCongestionWindow(), srtt); return bandwidth * (InSlowStart() ? 2 : (no_prr_ && InRecovery() ? 1 : 1.25)); } QuicBandwidth TcpCubicSenderBytes::BandwidthEstimate() const { QuicTime::Delta srtt = rtt_stats_->smoothed_rtt(); if (srtt.IsZero()) { // If we haven't measured an rtt, the bandwidth estimate is unknown. return QuicBandwidth::Zero(); } return QuicBandwidth::FromBytesAndTimeDelta(GetCongestionWindow(), srtt); } bool TcpCubicSenderBytes::InSlowStart() const { return GetCongestionWindow() < GetSlowStartThreshold(); } bool TcpCubicSenderBytes::IsCwndLimited(QuicByteCount bytes_in_flight) const { const QuicByteCount congestion_window = GetCongestionWindow(); if (bytes_in_flight >= congestion_window) { return true; } const QuicByteCount available_bytes = congestion_window - bytes_in_flight; const bool slow_start_limited = InSlowStart() && bytes_in_flight > congestion_window / 2; return slow_start_limited || available_bytes <= kMaxBurstBytes; } bool TcpCubicSenderBytes::InRecovery() const { return largest_acked_packet_number_.IsInitialized() && largest_sent_at_last_cutback_.IsInitialized() && largest_acked_packet_number_ <= largest_sent_at_last_cutback_; } bool TcpCubicSenderBytes::ShouldSendProbingPacket() const { return false; } void TcpCubicSenderBytes::OnRetransmissionTimeout(bool packets_retransmitted) { largest_sent_at_last_cutback_.Clear(); if (!packets_retransmitted) { return; } hybrid_slow_start_.Restart(); HandleRetransmissionTimeout(); } std::string TcpCubicSenderBytes::GetDebugState() const { return ""; } void TcpCubicSenderBytes::OnApplicationLimited( QuicByteCount /*bytes_in_flight*/) {} void TcpCubicSenderBytes::SetCongestionWindowFromBandwidthAndRtt( QuicBandwidth bandwidth, QuicTime::Delta rtt) { QuicByteCount new_congestion_window = bandwidth.ToBytesPerPeriod(rtt); // Limit new CWND if needed. congestion_window_ = std::max(min_congestion_window_, std::min(new_congestion_window, kMaxResumptionCongestionWindow * kDefaultTCPMSS)); } void TcpCubicSenderBytes::SetInitialCongestionWindowInPackets( QuicPacketCount congestion_window) { congestion_window_ = congestion_window * kDefaultTCPMSS; } void TcpCubicSenderBytes::SetMinCongestionWindowInPackets( QuicPacketCount congestion_window) { min_congestion_window_ = congestion_window * kDefaultTCPMSS; } void TcpCubicSenderBytes::SetNumEmulatedConnections(int num_connections) { num_connections_ = std::max(1, num_connections); cubic_.SetNumConnections(num_connections_); } void TcpCubicSenderBytes::ExitSlowstart() { slowstart_threshold_ = congestion_window_; } void TcpCubicSenderBytes::OnPacketLost(QuicPacketNumber packet_number, QuicByteCount lost_bytes, QuicByteCount prior_in_flight) { // TCP NewReno (RFC6582) says that once a loss occurs, any losses in packets // already sent should be treated as a single loss event, since it's expected. if (largest_sent_at_last_cutback_.IsInitialized() && packet_number <= largest_sent_at_last_cutback_) { if (last_cutback_exited_slowstart_) { ++stats_->slowstart_packets_lost; stats_->slowstart_bytes_lost += lost_bytes; if (slow_start_large_reduction_) { // Reduce congestion window by lost_bytes for every loss. congestion_window_ = std::max(congestion_window_ - lost_bytes, min_slow_start_exit_window_); slowstart_threshold_ = congestion_window_; } } QUIC_DVLOG(1) << "Ignoring loss for largest_missing:" << packet_number << " because it was sent prior to the last CWND cutback."; return; } ++stats_->tcp_loss_events; last_cutback_exited_slowstart_ = InSlowStart(); if (InSlowStart()) { ++stats_->slowstart_packets_lost; } if (!no_prr_) { prr_.OnPacketLost(prior_in_flight); } // TODO(b/77268641): Separate out all of slow start into a separate class. if (slow_start_large_reduction_ && InSlowStart()) { QUICHE_DCHECK_LT(kDefaultTCPMSS, congestion_window_); if (congestion_window_ >= 2 * initial_tcp_congestion_window_) { min_slow_start_exit_window_ = congestion_window_ / 2; } congestion_window_ = congestion_window_ - kDefaultTCPMSS; } else if (reno_) { congestion_window_ = congestion_window_ * RenoBeta(); } else { congestion_window_ = cubic_.CongestionWindowAfterPacketLoss(congestion_window_); } if (congestion_window_ < min_congestion_window_) { congestion_window_ = min_congestion_window_; } slowstart_threshold_ = congestion_window_; largest_sent_at_last_cutback_ = largest_sent_packet_number_; // Reset packet count from congestion avoidance mode. We start counting again // when we're out of recovery. num_acked_packets_ = 0; QUIC_DVLOG(1) << "Incoming loss; congestion window: " << congestion_window_ << " slowstart threshold: " << slowstart_threshold_; } QuicByteCount TcpCubicSenderBytes::GetCongestionWindow() const { return congestion_window_; } QuicByteCount TcpCubicSenderBytes::GetSlowStartThreshold() const { return slowstart_threshold_; } // Called when we receive an ack. Normal TCP tracks how many packets one ack // represents, but quic has a separate ack for each packet. void TcpCubicSenderBytes::MaybeIncreaseCwnd( QuicPacketNumber /*acked_packet_number*/, QuicByteCount acked_bytes, QuicByteCount prior_in_flight, QuicTime event_time) { QUIC_BUG_IF(quic_bug_10439_1, InRecovery()) << "Never increase the CWND during recovery."; // Do not increase the congestion window unless the sender is close to using // the current window. if (!IsCwndLimited(prior_in_flight)) { cubic_.OnApplicationLimited(); return; } if (congestion_window_ >= max_congestion_window_) { return; } if (InSlowStart()) { // TCP slow start, exponential growth, increase by one for each ACK. congestion_window_ += kDefaultTCPMSS; QUIC_DVLOG(1) << "Slow start; congestion window: " << congestion_window_ << " slowstart threshold: " << slowstart_threshold_; return; } // Congestion avoidance. if (reno_) { // Classic Reno congestion avoidance. ++num_acked_packets_; // Divide by num_connections to smoothly increase the CWND at a faster rate // than conventional Reno. if (num_acked_packets_ * num_connections_ >= congestion_window_ / kDefaultTCPMSS) { congestion_window_ += kDefaultTCPMSS; num_acked_packets_ = 0; } QUIC_DVLOG(1) << "Reno; congestion window: " << congestion_window_ << " slowstart threshold: " << slowstart_threshold_ << " congestion window count: " << num_acked_packets_; } else { congestion_window_ = std::min( max_congestion_window_, cubic_.CongestionWindowAfterAck(acked_bytes, congestion_window_, rtt_stats_->min_rtt(), event_time)); QUIC_DVLOG(1) << "Cubic; congestion window: " << congestion_window_ << " slowstart threshold: " << slowstart_threshold_; } } void TcpCubicSenderBytes::HandleRetransmissionTimeout() { cubic_.ResetCubicState(); slowstart_threshold_ = congestion_window_ / 2; congestion_window_ = min_congestion_window_; } void TcpCubicSenderBytes::OnConnectionMigration() { hybrid_slow_start_.Restart(); prr_ = PrrSender(); largest_sent_packet_number_.Clear(); largest_acked_packet_number_.Clear(); largest_sent_at_last_cutback_.Clear(); last_cutback_exited_slowstart_ = false; cubic_.ResetCubicState(); num_acked_packets_ = 0; congestion_window_ = initial_tcp_congestion_window_; max_congestion_window_ = initial_max_tcp_congestion_window_; slowstart_threshold_ = initial_max_tcp_congestion_window_; } CongestionControlType TcpCubicSenderBytes::GetCongestionControlType() const { return reno_ ? kRenoBytes : kCubicBytes; } } // namespace quic
[ "wangsheng@bilibili.com" ]
wangsheng@bilibili.com
681dce7d27f6f74a661435b4fb6397de654c3fdc
7ae7ddb631c04bee666588c4d50679a9f04be080
/feburary/0204/1850_faster.cpp
1be531147f6926523dcd96f6aa8b8afaa8dda3e1
[]
no_license
DooHyun-Lee/algorithm
794a34da13d188e9576431204663a1cb0b3bf47c
c274cce69d40480e01dbf819d4e846a0c6dac943
refs/heads/main
2023-06-16T12:59:17.273722
2021-07-07T20:24:24
2021-07-07T20:24:24
326,330,540
1
0
null
null
null
null
UTF-8
C++
false
false
451
cpp
// basically same thing but faster printing #include<iostream> #include<algorithm> #include<cstring> using namespace std; char ans[5000001]; long long gcd(long long a,long long b){ //assume a is bigger than b return b?gcd(b,a%b):a; } int main(){ ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long a,b,val; cin>>a>>b; val = gcd(a,b); memset(ans,'1',val); puts(ans); return 0; }
[ "noreply@github.com" ]
DooHyun-Lee.noreply@github.com
9526f13ad90801629b2ae4ef228aaf3f3c2b1f54
7730923178e9f34995d7c6be30965a73fac5d5b0
/nefu-2/nefu556.cpp
abedefc0b4e9bdec9515a09fedae79af1c6ca2b4
[]
no_license
magicdark-nefu/nefu2020-AC-code
378dce21d1dec51a876be6ddd1e396966f26accd
d1c82620ef5690925165e5430e298f24d6d2d28c
refs/heads/master
2023-02-06T08:09:49.730467
2020-12-29T03:42:26
2020-12-29T03:42:26
324,784,816
0
0
null
null
null
null
UTF-8
C++
false
false
463
cpp
#include <bits/stdc++.h> using namespace std; struct heshang{ char name[105]; int zongfeng; }; bool cmp(heshang a,heshang b) { return a.zongfeng<b.zongfeng; } int main() { int n,i,m,o; heshang hs[1000]; while(cin>>n>>m>>o) { for(i=0;i<n;i++) cin>>hs[i].name>>hs[i].zongfeng; sort(hs,hs+n,cmp); for(i=n-m;i<n;i++) cout<<hs[i].name<<endl; for(i=0;i<o;i++) cout<<hs[i].name<<endl; } return 0; }
[ "darklight@nefu.edu.cn" ]
darklight@nefu.edu.cn
3b4d264732e3e435fcd121cd2e1d5e9c6180e691
611b3f834aae2465675f5d35fcf0131ebb36c293
/LostInTheMap/ai_system.cpp
6fdf549832241a8226168e7ef01f0b7636d3861b
[]
no_license
arveon/LostInTheMap
53ad921bf81403f5d51f6992b92b089110f6b642
394091ecc4727e62d7151e7c45d076d7ed952a10
refs/heads/master
2021-04-28T01:09:24.101331
2018-05-14T08:19:46
2018-05-14T08:19:46
122,265,580
1
0
null
null
null
null
UTF-8
C++
false
false
2,742
cpp
#include "ai_system.h" void ai_system::process_rat_move(Entity * rat, std::vector<army_unit*> player_army, ITerrain* tc) { //get rats combat unit ICombatUnit* cbu = (ICombatUnit*)rat->get_component(Component::ComponentType::CombatUnit); //get rats movement component IMoving* r_mc = (IMoving*)rat->get_component(Component::ComponentType::Movement); cbu->attacking = nullptr; //construct priority queue for the possible targets std::vector<std::pair<army_unit*, float>> priority_queue; SDL_Point cur_unit_ids = map_system::get_entity_ids(rat, tc); for (army_unit* u : player_army) { if (u->health_of_first == 0) continue; std::pair<army_unit*, float> unit_priority; unit_priority.first = u; //calculate distance SDL_Point player_unit_ids = map_system::get_entity_ids(u->unit_entity, tc); SDL_Point dist; dist.x = std::abs(cur_unit_ids.x - player_unit_ids.x); dist.y = std::abs(cur_unit_ids.y - player_unit_ids.y); float full_dist = std::sqrt(std::pow(dist.x,2) + std::pow(dist.y, 2)); unit_priority.second = (1.f / full_dist) + 1.f/u->max_damage_close; int priority_lvl = 0; for (int i = 0; i < (int)priority_queue.size(); i++) { if (unit_priority.second > priority_queue.at(i).second) { priority_lvl = i+1; continue; } else { priority_lvl = i; break; } } priority_queue.insert(priority_queue.begin() + priority_lvl, unit_priority); } bool target_found = false; while (!target_found) { army_unit* potential_target = priority_queue.back().first; //measure distance //calculate distance SDL_Point player_unit_ids = map_system::get_entity_ids(potential_target->unit_entity, tc); SDL_Point dist; dist.x = std::abs(cur_unit_ids.x - player_unit_ids.x); dist.y = std::abs(cur_unit_ids.y - player_unit_ids.y); float full_dist = std::sqrt(std::pow(dist.x, 2) + std::pow(dist.y, 2)); //calculate path r_mc->pathfinder.set_origin(cur_unit_ids); r_mc->path = r_mc->pathfinder.get_path_to(player_unit_ids, true); //if path is 0 but distance is > 0, then remove this target from priority queue and continue if (r_mc->path.size() == 0 && full_dist > 0.01f) { priority_queue.pop_back(); continue; } else if (r_mc->path.size() > 0) {//if path is more than 0, do the magic cbu->attacking = potential_target->unit_entity; r_mc->path.erase(r_mc->path.begin());//just to make sure don't go ontop of unit int dif = r_mc->path.size() - cbu->unit_stats->speed; if (dif > 0) { r_mc->path.erase(r_mc->path.begin(), r_mc->path.begin() + dif - 1); cbu->attacking = nullptr; } target_found = true; } } r_mc->movement_allowed = true; } ai_system::ai_system() { } ai_system::~ai_system() { }
[ "ALoginovs@dundee.ac.uk" ]
ALoginovs@dundee.ac.uk
169ea3bc6c5c4d54e82abba9f133e0e6979e9468
c36ee04946b79f2eb9d8bf296b41ba28b21566ec
/ComputerVisionwithOpenCV3andQt5_Code/Chapter04/ImageViewer/ImageViewer/ui_mainwindow.h
d1c3b0eae30e7ac26a0df196dbddc70f414be472
[]
no_license
Daibingh/qt-project
ba622ebb1ae431463d8c343298a889b5fdf44132
42357e80093103141ce0f88d89e1fb0e2f663945
refs/heads/master
2020-04-12T19:36:10.378232
2018-12-21T12:45:24
2018-12-21T12:45:24
162,713,384
0
0
null
null
null
null
UTF-8
C++
false
false
2,334
h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.8.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QMainWindow> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QGridLayout *gridLayout; QLabel *label; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(749, 544); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); gridLayout = new QGridLayout(centralWidget); gridLayout->setSpacing(6); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QStringLiteral("gridLayout")); label = new QLabel(centralWidget); label->setObjectName(QStringLiteral("label")); QSizePolicy sizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(label->sizePolicy().hasHeightForWidth()); label->setSizePolicy(sizePolicy); label->setAlignment(Qt::AlignCenter); gridLayout->addWidget(label, 0, 0, 1, 1); MainWindow->setCentralWidget(centralWidget); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", Q_NULLPTR)); label->setText(QString()); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
[ "Daibingh@gmail.com" ]
Daibingh@gmail.com
49cfd356f497f3229b37d6c13e0cb2c8aad1aa19
e17546794b54bb4e7f65320fda8a046ce28c7915
/DeviceCode/Drivers/BatteryMeasurement/stubs/fastcompile_BatteryMeasurement_stubs.cpp
f31185706f12c7996debba92bf5ca22762337e95
[ "BSD-3-Clause", "OpenSSL", "MIT", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "Apache-2.0" ]
permissive
smaillet-ms/netmf-interpreter
693e5dc8c9463ff0824c515e9240270c948c706f
53574a439396cc98e37b82f296920c7e83a567bf
refs/heads/dev
2021-01-17T22:21:36.617467
2016-09-05T06:29:07
2016-09-05T06:29:07
32,760,598
2
1
null
2016-04-26T02:49:52
2015-03-23T21:44:01
C#
UTF-8
C++
false
false
92
cpp
#include "BatteryMeas_stubs_functions.cpp" #include "BatteryMeasurement_stubs_config.cpp"
[ "morteza.ghandehari@microsoft.com" ]
morteza.ghandehari@microsoft.com
7e8c6ef4e2de7a89e3bb285e364bfdc7b7a337d0
e079b72d1566f1da9b4050acb19837f137c719fa
/parser/token.h
b03e87c0c7451662e5e6ee8215a784c062f82f07
[]
no_license
wxmaper/phpqt5plugin
a670d984ee874fb4777971a5b4a51dce5aa133d4
dd1353a482df8b150b75a00eb64278814f60f88a
refs/heads/master
2020-12-30T13:20:35.874881
2017-05-13T21:28:54
2017-05-13T21:28:54
91,202,744
1
0
null
null
null
null
UTF-8
C++
false
false
9,323
h
#ifndef TOKEN_H #define TOKEN_H #include <QChar> #include <QHash> #include <QString> #include <qobjectdefs.h> namespace PHPQt5 { namespace Internal { class Token; class Scanner; class SourceCodeStream; typedef QList<Token> TokenList; class Token { Q_GADGET Q_ENUMS(T) public: static Token getIdentifierToken(const SourceCodeStream &stream); static Token getOperatorToken(const SourceCodeStream &stream); enum T { T_EOF, T_INTERNAL, T_PUBLIC, T_PROTECTED, T_STATIC, T_PRIVATE, T_SCOPED, T_COMMA, T_REQUIRE, T_ENDIF, T_ENDWHILE, T_ENDFOR, T_ENDFOREACH, T_ENDSWITCH, T_DOUBLEARROW, T_QUESTION, T_LIKELY, T_UNLIKELY, T_OR, T_AND, T_INSTANCEOF, T_BITWISE_OR, T_BITWISE_XOR, T_BITWISE_SHIFTLEFT, T_BITWISE_SHIFTRIGHT, T_EQUALS, T_IDENTICAL, T_LESS, T_GREATER, T_LESSEQUAL, T_GREATEREQUAL, T_NOTIDENTICAL, T_NOTEQUALS, T_ADD, T_SUB, T_CONCAT, T_MUL, T_DIV, T_MOD, T_ISSET, T_FETCH, T_EMPTY, T_INCLUSIVE_RANGE, T_EXCLUSIVE_RANGE, T_TYPEOF, T_CLONE, T_NEW, T_SELF, T_NOT, T_BITWISE_NOT, T_BITWISE_AND, T_PARENTHESES_CLOSE, T_SBRACKET_OPEN, T_ARROW, T_NAMESPACE, T_IDENTIFIER, T_DOTCOMMA, T_USE, T_AS, T_FUNCTION, T_PARENTHESES_OPEN, T_BRACKET_OPEN, T_BRACKET_CLOSE, T_INTERFACE, T_EXTENDS, T_CLASS, T_IMPLEMENTS, T_ABSTRACT, T_FINAL, T_COMMENT, T_ASSIGN, T_CONST, T_CONSTANT, T_INLINE, T_DEPRECATED, T_VOID, T_NULL, T_THIS, T_SBRACKET_CLOSE, T_TYPE_INTEGER, T_TYPE_UINTEGER, T_TYPE_LONG, T_TYPE_ULONG, T_TYPE_CHAR, T_TYPE_UCHAR, T_TYPE_DOUBLE, T_TYPE_BOOL, T_TYPE_STRING, T_TYPE_ARRAY, T_TYPE_VAR, T_TYPE_CALLABLE, T_TYPE_RESOURCE, T_TYPE_OBJECT, T_BREAK, T_CONTINUE, T_IF, T_ELSE, T_ELSEIF, T_SWITCH, T_CASE, T_COLON, T_DEFAULT, T_LOOP, T_WHILE, T_DO, T_TRY, T_CATCH, T_FOR, T_FOREACH, T_IN, T_REVERSE, T_LET, T_ADDASSIGN, T_SUBASSIGN, T_MULASSIGN, T_DIVASSIGN, T_CONCATASSIGN, T_MODASSIGN, T_STRING, T_DOUBLECOLON, T_INCR, T_DECR, T_ECHO, T_RETURN, T_OPEN_TAG, T_UNSET, T_THROW, T_PLUS, T_INTEGER, T_ISTRING, T_CHAR, T_DOUBLE, T_TRUE, T_FALSE, T_CBLOCK, T_AT, T_WHITESPACE, T_DCOMMENT, T_ANONYMOUS, T_IGNORE, T_NONE, T_ERROR }; Q_ENUM(T) Token() : m_begin(0) , m_length(0) , m_type(T_NONE) , m_value(QStringLiteral("")) {} Token(int b, int l, Token::T t, const QString &value = QStringLiteral("")) : m_begin(b), m_length(l), m_type(t), m_value(value) {} int begin() const { return m_begin; } int length() const { return m_length; } T type() const { return m_type; } QString value() const { return m_value; } bool is(T type) const { return type == m_type; } void clear() { m_begin = 0; m_length = 0; m_type = T_NONE; m_value = QStringLiteral(""); } private: int m_begin; int m_length; T m_type; QString m_value; }; static const QHash<QChar,Token::T> C_PHP_OPERATORS = { { '(', Token::T_PARENTHESES_OPEN }, { ')', Token::T_PARENTHESES_CLOSE }, { '{', Token::T_BRACKET_OPEN }, { '}', Token::T_BRACKET_CLOSE }, { '[', Token::T_SBRACKET_OPEN }, { ']', Token::T_SBRACKET_CLOSE }, { '@', Token::T_AT }, { '!', Token::T_NOT }, { '~', Token::T_BITWISE_NOT }, { '&', Token::T_BITWISE_AND }, { '|', Token::T_BITWISE_OR }, { '^', Token::T_BITWISE_XOR }, { '=', Token::T_ASSIGN }, { '>', Token::T_GREATER }, { '.', Token::T_CONCAT }, { '+', Token::T_ADD }, { '-', Token::T_SUB }, { '*', Token::T_MUL }, { '/', Token::T_DIV }, { '%', Token::T_MOD }, { ':', Token::T_COLON }, { ';', Token::T_DOTCOMMA }, { ',', Token::T_COMMA }, { '?', Token::T_QUESTION }, { '\n', Token::T_IGNORE }, { '\000', Token::T_EOF } }; static const QHash<QString,Token::T> C_PHP_KEYWORDS = { { QLatin1Literal("class"), Token::T_CLASS }, { QLatin1Literal("extends"), Token::T_EXTENDS }, { QLatin1Literal("abstract"), Token::T_ABSTRACT }, { QLatin1Literal("catch"), Token::T_CATCH }, { QLatin1Literal("clone"), Token::T_CLONE }, { QLatin1Literal("const"), Token::T_CONST }, // { QLatin1Literal("exception"), Token:: }, { QLatin1Literal("final"), Token::T_FINAL }, { QLatin1Literal("function"), Token::T_FUNCTION }, // { QLatin1Literal("global"), Token::T_GLOBAL }, { QLatin1Literal("implements"), Token::T_IMPLEMENTS }, { QLatin1Literal("instanceof"), Token::T_INSTANCEOF }, { QLatin1Literal("interface"), Token::T_INTERFACE }, { QLatin1Literal("new"), Token::T_NEW }, { QLatin1Literal("self"), Token::T_SELF }, { QLatin1Literal("static"), Token::T_STATIC }, // { QLatin1Literal("parent"), Token::T_PARENT }, { QLatin1Literal("private"), Token::T_PRIVATE }, { QLatin1Literal("protected"), Token::T_PROTECTED }, { QLatin1Literal("public"), Token::T_PUBLIC }, { QLatin1Literal("throw"), Token::T_THROW }, { QLatin1Literal("try"), Token::T_TRY }, { QLatin1Literal("and"), Token::T_AND }, { QLatin1Literal("or"), Token::T_OR }, // { QLatin1Literal("xor"), Token::T_XOR }, // { QLatin1Literal("var"), Token::T_VAR }, { QLatin1Literal("namespace"), Token::T_NAMESPACE }, { QLatin1Literal("use"), Token::T_USE } }; static const QHash<QString,Token::T> C_PHP_TYPES = { { QLatin1Literal("int"), Token::T_TYPE_INTEGER }, { QLatin1Literal("string"), Token::T_TYPE_STRING }, { QLatin1Literal("bool"), Token::T_TYPE_BOOL }, { QLatin1Literal("double"), Token::T_TYPE_DOUBLE }, { QLatin1Literal("array"), Token::T_TYPE_ARRAY }, { QLatin1Literal("float"), Token::T_TYPE_DOUBLE }, { QLatin1Literal("object"), Token::T_TYPE_OBJECT }, { QLatin1Literal("resource"), Token::T_TYPE_RESOURCE } }; static const QHash<QString,Token::T> C_PHP_IDENTIFIERS = { { QLatin1Literal("typeof"), Token::T_TYPEOF }, { QLatin1Literal("isset"), Token::T_ISSET }, { QLatin1Literal("unset"), Token::T_UNSET }, { QLatin1Literal("internal"), Token::T_INTERNAL }, { QLatin1Literal("static"), Token::T_STATIC }, { QLatin1Literal("inline"), Token::T_INLINE }, { QLatin1Literal("deprecated"), Token::T_DEPRECATED }, { QLatin1Literal("empty"), Token::T_EMPTY }, { QLatin1Literal("fetch"), Token::T_FETCH }, { QLatin1Literal("false"), Token::T_FALSE }, { QLatin1Literal("true"), Token::T_TRUE }, { QLatin1Literal("null"), Token::T_NULL }, { QLatin1Literal("FALSE"), Token::T_FALSE }, { QLatin1Literal("TRUE"), Token::T_TRUE }, { QLatin1Literal("NULL"), Token::T_NULL }, }; static const QHash<QString,Token::T> C_PHP_CONSTROLS = { { QLatin1Literal("as"), Token::T_AS }, { QLatin1Literal("case"), Token::T_CASE }, { QLatin1Literal("default"), Token::T_DEFAULT }, { QLatin1Literal("if"), Token::T_IF }, { QLatin1Literal("else"), Token::T_ELSE }, { QLatin1Literal("elseif"), Token::T_ELSEIF }, { QLatin1Literal("while"), Token::T_WHILE }, { QLatin1Literal("do"), Token::T_DO }, { QLatin1Literal("for"), Token::T_FOR }, { QLatin1Literal("foreach"), Token::T_FOREACH }, { QLatin1Literal("break"), Token::T_BREAK }, { QLatin1Literal("continue"), Token::T_CONTINUE }, { QLatin1Literal("switch"), Token::T_SWITCH }, // { QLatin1Literal("declare"), Token::T_DECLARE }, { QLatin1Literal("return"), Token::T_RETURN }, { QLatin1Literal("require"), Token::T_REQUIRE }, // { QLatin1Literal("include"), Token::T_INCLUDE }, { QLatin1Literal("endif"), Token::T_ENDIF }, { QLatin1Literal("endwhile"), Token::T_ENDWHILE }, { QLatin1Literal("endfor"), Token::T_ENDFOR }, { QLatin1Literal("endforeach"), Token::T_ENDFOREACH }, { QLatin1Literal("endswitch"), Token::T_ENDSWITCH } }; } } // namespace PHPQt5 #include <QDebug> #include <QMetaEnum> QDebug inline operator<< (QDebug d, const PHPQt5::Internal::Token &t) { QMetaEnum metaEnum = QMetaEnum::fromType<PHPQt5::Internal::Token::T>(); QString dstr = QString("Token::%1(`%2`, begin:%3, len:%4)") .arg(QLatin1String(metaEnum.valueToKey(t.type()))) .arg(t.value().replace("%","---!PERCENT!---")) .arg(t.begin()) .arg(t.length()); d.maybeSpace() << dstr.replace("---!PERCENT!---", "%"); return d; } #endif // TOKEN_H
[ "wxmaper@gmail.com" ]
wxmaper@gmail.com
8aa725a45826c25573410b303f6ca4d7edd4b576
ef1b5ce400a6321f7ad07527a86e80d401ff954d
/src/sample.cpp
41d7e2d6af1bbe3c064d60e98e21dbe503a4f3a8
[]
no_license
jprod123/roboteq
a0431bd576f562d00ded96f6f105c63185ce344b
17270cd330fbc633237546d4f000749aad9ae20c
refs/heads/master
2021-04-15T04:57:34.343688
2018-03-26T18:46:31
2018-03-26T18:46:31
126,874,474
0
0
null
null
null
null
UTF-8
C++
false
false
1,450
cpp
#include <iostream> #include <stdio.h> #include <string.h> #include <RoboteqDevice/RoboteqDevice.h> #include <RoboteqDevice/ErrorCodes.h> #include <RoboteqDevice/Constants.h> using namespace std; int main(int argc, char *argv[]) { string response = ""; RoboteqDevice device; int status = device.Connect("/dev/ttyS0"); if(status != RQ_SUCCESS) { cout<<"Error connecting to device: "<<status<<"."<<endl; return 1; } cout<<"- SetConfig(_DINA, 1, 1)..."; if((status = device.SetConfig(_DINA, 1, 1)) != RQ_SUCCESS) cout<<"failed --> "<<status<<endl; else cout<<"succeeded."<<endl; //Wait 10 ms before sending another command to device sleepms(10); int result; cout<<"- GetConfig(_DINA, 1)..."; if((status = device.GetConfig(_DINA, 1, result)) != RQ_SUCCESS) cout<<"failed --> "<<status<<endl; else cout<<"returned --> "<<result<<endl; //Wait 10 ms before sending another command to device sleepms(10); cout<<"- GetValue(_ANAIN, 1)..."; if((status = device.GetValue(_ANAIN, 1, result)) != RQ_SUCCESS) cout<<"failed --> "<<status<<endl; else cout<<"returned --> "<<result<<endl; //Wait 10 ms before sending another command to device sleepms(10); cout<<"- SetCommand(_GO, 1, 1)..."; if((status = device.SetCommand(_GO, 1, 1)) != RQ_SUCCESS) cout<<"failed --> "<<status<<endl; else cout<<"succeeded."<<endl; device.Disconnect(); return 0; }
[ "jprod123@gmail.com" ]
jprod123@gmail.com
ddc4a450896d727f0ff9a54c0e67fa083de4cee8
cc9ae71207dc667c2e0be27671ced5c86f2f71a3
/test/oldstudy/N-jiecheng.cpp
1491fda5306680d985b899d9d0c75e98d4453041
[]
no_license
xm0629/c-study
aed8480aa30b35637bfca307e009eb8b827b328d
26183be9c91b2b53bd71b6693fe6d39823bc5d63
refs/heads/master
2020-04-09T11:35:48.047562
2019-03-30T15:27:01
2019-03-30T15:27:01
160,316,327
1
0
null
null
null
null
UTF-8
C++
false
false
466
cpp
# include <iostream> using namespace std; long fac(int); int main() { int n; long y; cout << "Please input an imteger: "; cin >> n; y = fac(n); cout << n << " != " << y << endl; return 0; } long fac (int n) { long f; if (n < 0) { cout << "n<0, data error!"<< endl; f = -1; } else{ if (n == 0 || n == 1) f == 1; else f = fac(n -1) * n; } return f; }
[ "920972751@qq.com" ]
920972751@qq.com
7816fd04f7f81be5b601139c6101171ed63f69f9
6914cd2c274878c0262c0ec7218787ae2c0e392b
/genetic_algorithm/gafunction.h
8c0d6cd3f13a2d4659281558bb48c0e309637441
[]
no_license
AndreiTirpescu/tsp_genetic_algorithm
adc577daf087887f4c789bde512bb75e3c538ce1
7006b6fcb5218186d1f31ba4046b34dd453f240b
refs/heads/master
2020-12-05T07:11:09.698856
2020-01-16T07:43:16
2020-01-16T07:43:16
232,043,692
0
0
null
null
null
null
UTF-8
C++
false
false
601
h
#ifndef GA_FUNCTION_H #define GA_FUNCTION_H #include <cstdint> #include <vector> typedef double (*CALLBACK_GA_FUNC)(uint32_t arrayCount, double *arrayValues); class GaFunction { public: GaFunction(double min, double max, CALLBACK_GA_FUNC func); GaFunction& setData(const std::vector<double> & val); double operator()(); double delta(); double getMaxDomain(); double getMinDomain(); private: double minDomain; double maxDomain; CALLBACK_GA_FUNC eval; std::vector<double> arrayValues; }; #endif
[ "tirpescu.andrei@yahoo.com" ]
tirpescu.andrei@yahoo.com
b87cfa36194c978cb3daac12e61fbb51fec6000b
41e5b09f0106b9d373c84b479bbca2ba664b5cbd
/OpenGL_2D_Engine/Source/Enemy.h
8ee25bb0f4b330fb69cfe2a9370fc42f2b045af4
[]
no_license
DGMeyer96/RogueHack
833fc2e3bc5db075bf5221b233d612e43bbc3d86
0383f60eaa331cf289a73f633cd4fc956710f64a
refs/heads/main
2023-04-28T21:01:44.455441
2021-05-20T00:09:25
2021-05-20T00:09:25
334,321,337
0
0
null
null
null
null
UTF-8
C++
false
false
494
h
#ifndef ENEMY_H #define ENEMY_H #include "Engine/Game_Object.h" class Enemy : GameObject { public: Enemy(unsigned int maxHealth, unsigned int damage, unsigned int armor, glm::vec2 pos, glm::vec2 size, Texture2D sprite, glm::vec3 color); ~Enemy(); void Activate(); void Deactivate(); bool Attack(); bool TakeDamage(unsigned int damage); bool Move(); private: glm::vec2 PlayerPosition; unsigned int Health; unsigned int Mana; unsigned int Damage; unsigned int Armor; }; #endif
[ "dmlegoman96@verizon.net" ]
dmlegoman96@verizon.net
e3bee199be776c21511d12013394f964cb336d81
44d05b95c5b1586bf2a0902dbd25dbd544192f2f
/sortAlgorithm.cpp
9a725824d33e2e42130ea098a301707ad73caca0
[]
no_license
AutoWin/myClone
088fe59686fe6c1a5c3313bea33aff92fe1d67a6
78bf7c42d5ee54ebcc41a61627e1bee2d940f20f
refs/heads/master
2020-12-02T22:43:47.074699
2017-07-04T04:30:11
2017-07-04T04:30:11
96,173,897
0
0
null
null
null
null
UTF-8
C++
false
false
2,575
cpp
#include <iostream> using namespace std; void print(int , int); void swap(int *a, int *b) { int temp = *a; *a = *b; *b= temp; } void selectionSort(int arr[], int n) { int i, j, min_idx; for(int i=0; i<n-1; i++) { min_idx = i; for(int j=i+1; j<n; j++) if(arr[j] < arr[min_idx]) min_idx = j; swap(&arr[i], &arr[min_idx]); } } void insertionSort(int arr[], int n) { int i, j, key; for(int i=0; i<n; i++) { key = arr[i]; j=i-1; while(arr[j] > key && j>=0) { arr[j+1] = arr[j]; j--; } arr[j+1] = key; } } void bubbleSort(int arr[], int n) { int i, j; for(int i=0; i<n-1; i++) for(int j=0; j<n-i-1; j++) if(arr[j] > arr[j+1]) swap(&arr[j], &arr[j+1]); } int partition (int arr[], int low, int high) { int pivot = arr[high]; int i = (low - 1); for (int j = low; j <= high- 1; j++) { if (arr[j] <= pivot) { i++; swap (&arr[i], &arr[j]); } } swap (&arr[i + 1], &arr[high]); return (i + 1); } void quickSort(int arr[], int low, int high) { if (low < high) { int p = partition(arr, low, high); quickSort(arr, low, p - 1); quickSort(arr, p + 1, high); } } void heapify(int arr[], int n, int i) { int largest = i; int l = 2*i + 1; int r = 2*i + 2; if(l < n && arr[l] > arr[largest]) largest = l; if(r < n && arr[r] > arr[largest]) largest = r; if(largest != i){ swap(&arr[i], &arr[largest]); heapify(arr, n, largest); } } void heapsort(int arr[], int n) { for(int i = n/2 - 1; i>=0; i--) heapify(arr, n, i); for(int i=n-1; i>=0; i--){ swap(&arr[i], &arr[0]); heapify(arr, i, 0); } } void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m-l+1; int n2 = r-m; int L[n1], R[n2]; for(int i=0; i<n1; i++) L[i] = arr[l+i]; for(int j=0; j<n2; j++) R[j] = arr[m+1+j]; i=0; j=0; k=l; while(i < n1 && j < n2){ if(L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while(i < n1) { arr[k] = L[i]; i++; k++; } while(j < n2) { arr[k] = R[j]; j++; k++; } } void mergeSort(int arr[], int l , int r) { if(l < r) { int m = (l+r)/2; mergeSort(arr, l, m); mergeSort(arr, m+1, r); merge(arr, l, m ,r); } } void print(int arr[], int n) { for(int i=0; i<n; i++) cout<<arr[i]<<" "; } int main(void) { int arr[]= {10, 7, 8, 9, 1, 5}; int n= sizeof(arr)/sizeof(arr[0]); // quickSort(arr, 0, n-1); // heapsort(arr, n); mergeSort(arr, 0, n-1); cout<<"Sorted array: "; // selectionSort(arr, n); // insertionSort(arr, n); // bubbleSort(arr, n); print(arr, n); }
[ "luongthanhkx1997@gmail.com" ]
luongthanhkx1997@gmail.com
2d20d390d0cf3ac76015ac827dbd3e94edeb3580
ac75305ca89a0124028649b08abc6f2623b36921
/libs/poco/include/Poco/PriorityEvent.h
a20ac01aa3f164b0528460fca5b28f8fe58ea710
[ "MIT" ]
permissive
mazbox/of64
82fef1dc60f9eecc21a75d8d66590ff77ef00d51
4f82325132f217e7bfc36e379f99ba435c3dd9d9
refs/heads/master
2021-01-10T21:08:21.640739
2013-02-18T14:54:57
2013-02-18T14:54:57
3,136,581
7
2
null
2012-09-08T14:37:06
2012-01-09T13:15:48
C++
UTF-8
C++
false
false
3,107
h
// // PriorityEvent.h // // $Id: //poco/1.4/Foundation/include/Poco/PriorityEvent.h#1 $ // // Library: Foundation // Package: Events // Module: PriorityEvent // // Implementation of the PriorityEvent template. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Foundation_PriorityEvent_INCLUDED #define Foundation_PriorityEvent_INCLUDED #include "Poco/AbstractEvent.h" #include "Poco/DefaultStrategy.h" #include "Poco/AbstractPriorityDelegate.h" #include "Poco/CompareFunctions.h" namespace Poco { template <class TArgs, class TMutex = FastMutex> class PriorityEvent: public AbstractEvent < TArgs, DefaultStrategy<TArgs, AbstractPriorityDelegate<TArgs>, p_less<AbstractPriorityDelegate<TArgs> > >, AbstractPriorityDelegate<TArgs>, TMutex > /// A PriorityEvent uses internally a DefaultStrategy which /// invokes delegates in a manner determined by the priority field /// in the PriorityDelegates (lower priorities first). /// PriorityEvents can only be used together with PriorityDelegates. /// PriorityDelegates are sorted according to the priority value, when /// two delegates have the same priority, they are invoked in /// an arbitrary manner. /// Note that one object can register several methods as long as they differ /// in their priority value: /// PriorityEvent<int> tmp; /// MyClass myObject; /// tmp += priorityDelegate(&myObject, &MyClass::myMethod1, 1); /// tmp += priorityDelegate(&myObject, &MyClass::myMethod2, 2); { public: PriorityEvent() { } ~PriorityEvent() { } private: PriorityEvent(const PriorityEvent&); PriorityEvent& operator = (const PriorityEvent&); }; } // namespace Poco #endif // Foundation_PriorityEvent_INCLUDED
[ "bereza@gmail.com" ]
bereza@gmail.com
26f5c6326cdfbc20a6afd2842d58492e8a3ac304
d324fe2379426188ec542f95a4d753ba9a989a35
/projects/fender/include/events.hpp
c6c0b90c99050aae501c10bb26f4d3de85ea4c5c
[]
no_license
teamfcm/futils
886091421fdb74a4198bafcb1fe3fe15635a405e
1ef39e1a8fa3c0d58bf60a96f25d38153172bc01
refs/heads/master
2020-06-23T23:15:34.731306
2018-01-09T14:51:06
2018-01-09T14:51:06
96,908,502
2
0
null
null
null
null
UTF-8
C++
false
false
294
hpp
// // Created by arroganz on 11/29/17. // #ifndef FENDER_EVENTS_HPP #define FENDER_EVENTS_HPP # include "mediator.hpp" # include "math.hpp" namespace fender::events { struct Shutdown // A simple message to shutdown every system in the engine. { }; } #endif //FENDER_EVENTS_HPP
[ "felix.ganz@epitech.eu" ]
felix.ganz@epitech.eu
6f1e8e21173eea458d177cfccb4b457f8d1a8d4c
e00ae1281303b2ed1cc7f78cf8fdd78209dd520f
/data-structures/week4_binary_search_trees/2_is_bst/is_bst.cpp
29a7cd58d0c5733aa882d591a66fff9ed958c7a0
[]
no_license
avjotsingh/ucsd-algorithms-specialization
13a641ace9834f563d2e2e50c262457f24a18f77
bb6437116e3ca7761dcfeb5de09e2ac091bb51d1
refs/heads/master
2023-01-09T19:17:33.457977
2020-11-03T20:07:03
2020-11-03T20:07:03
279,087,663
0
0
null
null
null
null
UTF-8
C++
false
false
1,644
cpp
#include <algorithm> #include <iostream> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; struct Node { int key; int left; int right; Node() : key(0), left(-1), right(-1) {} Node(int key_, int left_, int right_) : key(key_), left(left_), right(right_) {} }; const Node *leftLargest(const Node *root, const vector<Node> &tree) { if(root->left == -1) return NULL; else { const Node *left_largest = &tree[root->left]; while(left_largest->right != -1) left_largest = &tree[left_largest->right]; return left_largest; } } const Node *rightSmallest(const Node *root, const vector<Node> &tree) { if(root->right == -1) return NULL; else { const Node *right_smallest = &tree[root->right]; while(right_smallest->left != -1) right_smallest = &tree[right_smallest->left]; return right_smallest; } } bool IsBinarySearchTree(const vector<Node>& tree) { bool valid = true; for(const Node root : tree) { const Node *left_largest = leftLargest(&root, tree); const Node *right_smallest = rightSmallest(&root, tree); if((left_largest != NULL && left_largest->key > root.key) || (right_smallest != NULL && right_smallest->key < root.key)) { valid = false; break; } } return valid; } int main() { int nodes; cin >> nodes; vector<Node> tree; for (int i = 0; i < nodes; ++i) { int key, left, right; cin >> key >> left >> right; tree.push_back(Node(key, left, right)); } if (IsBinarySearchTree(tree)) { cout << "CORRECT" << endl; } else { cout << "INCORRECT" << endl; } return 0; }
[ "avjot.singh99@gmail.com" ]
avjot.singh99@gmail.com
85fae0b0d253847d80e9dbca822115d0aa7819a3
7dc2a3e541f4ebc036e13a9bf5fce7eb993a8167
/POCO_C++/poco_fanatic/0014_DateTime/DateTimeTest.cpp
ddd738d1ab2146637ede7cf2999f98d53e16b12a
[]
no_license
schidler/MeCloud
ea53d85f0919eafc769e27a969653b21cd576134
9375ed76303e4bf74b1be3b4f8f57006257a1705
refs/heads/master
2021-01-22T03:39:12.900354
2013-08-07T09:19:53
2013-08-07T09:19:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,347
cpp
// // DateTimeTest.cpp // // Created by Setsu on 5/14/2010. // Modified by Setsu on May 30, 2013. // Copyright 2010-2013 RoundSquare Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //---------------------------------------- // include //---------------------------------------- #include <Poco/DateTime.h> #include <Poco/Timezone.h> #include <Poco/Format.h> #include <Poco/DateTimeFormatter.h> #include <string> #include "ScopedLogMessage.h" #include "PrepareConsoleLogger.h" //---------------------------------------- // DisplayDateTime //---------------------------------------- void DisplayDateTime(const Poco::DateTime& dateTime, ScopedLogMessage& msg) { msg.Message(Poco::format(" year = %d", dateTime.year())); msg.Message(Poco::format(" month = %d\t(1 to 12)", dateTime.month())); msg.Message(Poco::format(" day = %d\t(1 to 31)", dateTime.day())); msg.Message(Poco::format(" hour = %d\t(0 to 23)", dateTime.hour())); msg.Message(Poco::format(" minute = %d\t(0 to 59)", dateTime.minute())); msg.Message(Poco::format(" second = %d\t(0 to 59)", dateTime.second())); msg.Message(Poco::format(" millisecond = %d\t(0 to 999)", dateTime.millisecond())); msg.Message(Poco::format(" microsecond = %d\t(0 to 999)", dateTime.microsecond())); msg.Message(Poco::format(" isAM = %s\t(true or false)", std::string(dateTime.isAM() ? "true":"false"))); msg.Message(Poco::format(" isPM = %s\t(true or false)", std::string(dateTime.isPM() ? "true":"false"))); msg.Message(Poco::format(" isLeapYear = %s\t(true or false)", std::string(Poco::DateTime::isLeapYear(dateTime.year()) ? "true":"false"))); msg.Message(Poco::format(" hourAMPM = %d\t(0 to 12)", dateTime.hourAMPM())); msg.Message(Poco::format(" dayOfWeek = %d\t(0 to 6, 0: Sunday)", dateTime.dayOfWeek())); msg.Message(Poco::format(" dayOfYear = %d\t(1 to 366, 1: January 1)", dateTime.dayOfYear())); msg.Message(Poco::format(" daysOfMonth = %d\t(1 to 366, 1: January 1)", Poco::DateTime::daysOfMonth(dateTime.year(), dateTime.month()))); msg.Message(Poco::format(" week = %d\t(0 to 53, 1: the week containing January 4)", dateTime.week())); msg.Message(""); } //---------------------------------------- // main //---------------------------------------- int main(int /*argc*/, char** /*argv*/) { PrepareConsoleLogger logger(Poco::Logger::ROOT, Poco::Message::PRIO_INFORMATION); ScopedLogMessage msg("DateTimeTest ", "start", "end"); Poco::DateTime dateTime; msg.Message(" Current DateTime (UTC)"); DisplayDateTime(dateTime, msg); msg.Message(Poco::format(" Current DateTime (Locat Time: %s [GMT%+d])", Poco::Timezone::name(), Poco::Timezone::tzd()/(60*60))); dateTime.makeLocal(Poco::Timezone::tzd()); DisplayDateTime(dateTime, msg); msg.Message(Poco::format(Poco::DateTimeFormatter::format(dateTime, " DateTimeFormatter: %w %b %e %H:%M:%S %%s %Y") , Poco::Timezone::name())); return 0; }
[ "t.benchung@gmail.com" ]
t.benchung@gmail.com
27598cbca2aa80783eebd16a0988025bd0483711
409271cf3c4ba9394bfa71b686cc8cbf536ad55b
/vrjugglua/Internal_StringInterface.cpp
a7e00ca803028c734494203924ca3767ffaaba59
[ "BSL-1.0", "MIT" ]
permissive
lpberg/vr-jugglua
68332f40cbd8b189ad08e8aac137d3f054733939
61b4462c691f3ccb03d73083bdad04516a70cc7e
refs/heads/master
2021-01-20T19:48:46.411596
2013-10-07T19:02:41
2013-10-07T19:02:41
2,197,749
0
0
null
null
null
null
UTF-8
C++
false
false
983
cpp
/** @file @brief implementation @date 2009-2013 @author Ryan Pavlik <rpavlik@iastate.edu> and <abiryan@ryand.net> http://academic.cleardefinition.com/ Iowa State University Virtual Reality Applications Center Human-Computer Interaction Graduate Program */ // Copyright Iowa State University 2009-2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Internal Includes #include "Internal_StringInterface.h" // Library/third-party includes // - none // Standard includes // - none namespace vrjLua { namespace Internal { StringInterface::StringInterface(const std::string & device) { _iface.init(device); } std::string StringInterface::getStringData() { //see StringProxy.h in VRJuggler for getData() method implementation return (_iface->getData()); } } // end of Internal namespace } // end of vrjLua namespace
[ "carlsonp@iastate.edu" ]
carlsonp@iastate.edu
2886b20d9f8a7542f6e77a83d7fe91e153e6e2b4
9f253e6dd5809c780f2dc5b36bf91171bb2fd72e
/helper functions/pow.cpp
20c6911fdc501dab3bbf89b3c3e0f12fe43bc3d0
[]
no_license
mbikas/ACM
ab41bb3ea7c5402758bdc56c3109807c64537b3a
d4185d5168a1391d7989f9a947dfa65198b27df9
refs/heads/master
2021-01-18T19:33:58.990020
2016-10-27T08:00:03
2016-10-27T08:00:03
72,075,809
0
0
null
null
null
null
UTF-8
C++
false
false
409
cpp
#include<stdio.h> long myPow( int base,int exp ) { long result( 1 ); int bitMask( 1 ); int currentPower( base ); for( bitMask = 1; bitMask <= exp; bitMask <<= 1 ) { if( bitMask & exp ) { result *= currentPower; // multiple } currentPower *= currentPower; // square } return result; } void main() { long p,q,r; p = myPow(2,3); printf("%ld\n",p); }
[ "mbikas2@uic.edu" ]
mbikas2@uic.edu
f4008c65b90396514f990c3094c3d2308298abc6
cc13bdb0f445b8acf6bec24946fcfb5e854989b6
/Pods/BoringSSL-GRPC/src/ssl/d1_lib.cc
118015398fb115ca044d0c9b0adb5002219439a7
[ "MIT", "ISC", "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows" ]
permissive
devMEremenko/XcodeBenchmark
59eaf0f7d6cdaead6338511431489d9d2bf0bbb5
3aaaa6aa4400a20513dd4b6fdb372c48b8c9e772
refs/heads/master
2023-09-04T08:37:51.014081
2023-07-25T23:37:37
2023-07-25T23:37:37
288,524,849
2,335
346
MIT
2023-09-08T16:52:16
2020-08-18T17:47:47
Swift
UTF-8
C++
false
false
8,250
cc
/* * DTLS implementation written by Nagendra Modadugu * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. */ /* ==================================================================== * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). */ #include <openssl_grpc/ssl.h> #include <assert.h> #include <limits.h> #include <string.h> #include <openssl_grpc/err.h> #include <openssl_grpc/mem.h> #include <openssl_grpc/nid.h> #include "../crypto/internal.h" #include "internal.h" BSSL_NAMESPACE_BEGIN // DTLS1_MTU_TIMEOUTS is the maximum number of timeouts to expire // before starting to decrease the MTU. #define DTLS1_MTU_TIMEOUTS 2 // DTLS1_MAX_TIMEOUTS is the maximum number of timeouts to expire // before failing the DTLS handshake. #define DTLS1_MAX_TIMEOUTS 12 DTLS1_STATE::DTLS1_STATE() : has_change_cipher_spec(false), outgoing_messages_complete(false), flight_has_reply(false) {} DTLS1_STATE::~DTLS1_STATE() {} bool dtls1_new(SSL *ssl) { if (!ssl3_new(ssl)) { return false; } UniquePtr<DTLS1_STATE> d1 = MakeUnique<DTLS1_STATE>(); if (!d1) { ssl3_free(ssl); return false; } ssl->d1 = d1.release(); // Set the version to the highest supported version. // // TODO(davidben): Move this field into |s3|, have it store the normalized // protocol version, and implement this pre-negotiation quirk in |SSL_version| // at the API boundary rather than in internal state. ssl->version = DTLS1_2_VERSION; return true; } void dtls1_free(SSL *ssl) { ssl3_free(ssl); if (ssl == NULL) { return; } Delete(ssl->d1); ssl->d1 = NULL; } void dtls1_start_timer(SSL *ssl) { // If timer is not set, initialize duration (by default, 1 second) if (ssl->d1->next_timeout.tv_sec == 0 && ssl->d1->next_timeout.tv_usec == 0) { ssl->d1->timeout_duration_ms = ssl->initial_timeout_duration_ms; } // Set timeout to current time ssl_get_current_time(ssl, &ssl->d1->next_timeout); // Add duration to current time ssl->d1->next_timeout.tv_sec += ssl->d1->timeout_duration_ms / 1000; ssl->d1->next_timeout.tv_usec += (ssl->d1->timeout_duration_ms % 1000) * 1000; if (ssl->d1->next_timeout.tv_usec >= 1000000) { ssl->d1->next_timeout.tv_sec++; ssl->d1->next_timeout.tv_usec -= 1000000; } } bool dtls1_is_timer_expired(SSL *ssl) { struct timeval timeleft; // Get time left until timeout, return false if no timer running if (!DTLSv1_get_timeout(ssl, &timeleft)) { return false; } // Return false if timer is not expired yet if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) { return false; } // Timer expired, so return true return true; } static void dtls1_double_timeout(SSL *ssl) { ssl->d1->timeout_duration_ms *= 2; if (ssl->d1->timeout_duration_ms > 60000) { ssl->d1->timeout_duration_ms = 60000; } } void dtls1_stop_timer(SSL *ssl) { ssl->d1->num_timeouts = 0; OPENSSL_memset(&ssl->d1->next_timeout, 0, sizeof(ssl->d1->next_timeout)); ssl->d1->timeout_duration_ms = ssl->initial_timeout_duration_ms; } bool dtls1_check_timeout_num(SSL *ssl) { ssl->d1->num_timeouts++; // Reduce MTU after 2 unsuccessful retransmissions if (ssl->d1->num_timeouts > DTLS1_MTU_TIMEOUTS && !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) { long mtu = BIO_ctrl(ssl->wbio.get(), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0, nullptr); if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) { ssl->d1->mtu = (unsigned)mtu; } } if (ssl->d1->num_timeouts > DTLS1_MAX_TIMEOUTS) { // fail the connection, enough alerts have been sent OPENSSL_PUT_ERROR(SSL, SSL_R_READ_TIMEOUT_EXPIRED); return false; } return true; } BSSL_NAMESPACE_END using namespace bssl; void DTLSv1_set_initial_timeout_duration(SSL *ssl, unsigned int duration_ms) { ssl->initial_timeout_duration_ms = duration_ms; } int DTLSv1_get_timeout(const SSL *ssl, struct timeval *out) { if (!SSL_is_dtls(ssl)) { return 0; } // If no timeout is set, just return 0. if (ssl->d1->next_timeout.tv_sec == 0 && ssl->d1->next_timeout.tv_usec == 0) { return 0; } struct OPENSSL_timeval timenow; ssl_get_current_time(ssl, &timenow); // If timer already expired, set remaining time to 0. if (ssl->d1->next_timeout.tv_sec < timenow.tv_sec || (ssl->d1->next_timeout.tv_sec == timenow.tv_sec && ssl->d1->next_timeout.tv_usec <= timenow.tv_usec)) { OPENSSL_memset(out, 0, sizeof(*out)); return 1; } // Calculate time left until timer expires. struct OPENSSL_timeval ret; OPENSSL_memcpy(&ret, &ssl->d1->next_timeout, sizeof(ret)); ret.tv_sec -= timenow.tv_sec; if (ret.tv_usec >= timenow.tv_usec) { ret.tv_usec -= timenow.tv_usec; } else { ret.tv_usec = 1000000 + ret.tv_usec - timenow.tv_usec; ret.tv_sec--; } // If remaining time is less than 15 ms, set it to 0 to prevent issues // because of small divergences with socket timeouts. if (ret.tv_sec == 0 && ret.tv_usec < 15000) { OPENSSL_memset(&ret, 0, sizeof(ret)); } // Clamp the result in case of overflow. if (ret.tv_sec > INT_MAX) { assert(0); out->tv_sec = INT_MAX; } else { out->tv_sec = ret.tv_sec; } out->tv_usec = ret.tv_usec; return 1; } int DTLSv1_handle_timeout(SSL *ssl) { ssl_reset_error_state(ssl); if (!SSL_is_dtls(ssl)) { OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return -1; } // If no timer is expired, don't do anything. if (!dtls1_is_timer_expired(ssl)) { return 0; } if (!dtls1_check_timeout_num(ssl)) { return -1; } dtls1_double_timeout(ssl); dtls1_start_timer(ssl); return dtls1_retransmit_outgoing_messages(ssl); }
[ "devMEremenko@gmail.com" ]
devMEremenko@gmail.com
6a8ca6d805c3748cce115aa6dc219cc9798809ce
b43e2ba9463bb64d182d2119f13eb502ba2db1dc
/terrain/terraintab.cpp
44bf22ad3895242fc9513d1fe9b91442b75de12c
[]
no_license
aureargo/Gamagora_TP4_3D
772425eba26ca2e58073929bd8cc9cae6e16d941
31ba8f543a2b688183a920ed745d65b7b5001a2c
refs/heads/master
2021-01-10T14:02:21.010698
2015-12-15T15:05:17
2015-12-15T15:05:17
47,224,764
0
0
null
null
null
null
UTF-8
C++
false
false
5,598
cpp
#include "terrain/terraintab.h" TerrainTab::TerrainTab(const TerrainTab& copy): Terrain(copy.longueur, copy.largeur, 0), height(copy.height), width(copy.width), amplitude(copy.amplitude), hauteurMin(copy.hauteurMin), hauteurMax(copy.hauteurMax) { box = copy.box; grille = new float[height*width]; for(int i = 0; i < height*width; i++) grille[i] = copy.grille[i]; grille2d = new float*[height]; for(int j = 0; j < height; j++) grille2d[j] = &grille[j*width]; } TerrainTab::TerrainTab(TerrainTab && copy): height(copy.height), width(copy.width), amplitude(copy.amplitude), hauteurMin(copy.hauteurMin), hauteurMax(copy.hauteurMax) { longueur = copy.longueur; largeur = copy.largeur; box = copy.box; grille = copy.grille; grille2d = copy.grille2d; copy.grille = nullptr; copy.grille2d = nullptr; } TerrainTab::~TerrainTab() { if(grille != nullptr) { delete[] grille; for(int j = 0; j < height; j++) delete[] grille2d; } } inline float TerrainTab::get(int x, int y) const { return grille2d[y][x]; } float TerrainTab::getHauteur(float x, float y) const { x /= largeur; y /= longueur; if(x < 0 || y < 0 || x > 1 || y > 1) return HAUTEUR_HORS_MAP; x *= (width-1), //largeur: 1m et 5 points: (1.0f*(5-1))/1 = 4.0f donc regarder l'indice 4 y *= (height-1); int x1 = floorf(x), y1 = floorf(y), x2 = ceilf(x), y2 = ceilf(y); const float h11 = get(x1, y1); if(y1 == y2) { if(x1 == x2 ) return h11*amplitude; return interp::interp_linear1D(x, h11, get(x2, y1))*amplitude; } else { float h12 = get(x1, y2); if(x1 == x2 ) return interp::interp_linear1D(x, h11, h12)*amplitude; return interp::interp_linear2D(x, y, x1, y1, x2, y2, h11, h12, get(x2, y1), get(x2, y2))*amplitude; } } vec3 TerrainTab::getNormal(float x, float y, float eps) const { if(x < 0 || y < 0 || x > largeur || y > longueur) return vec3(0,0,1); float ha = getHauteur(x,y); float xg = std::max(x-eps, 0.f), xd = std::min(x+eps, largeur), yb = std::min(y+eps, longueur), yh = std::max(y-eps, 0.f); float g = getHauteur(xg,y), d = getHauteur(xd,y), b = getHauteur(x,yb), h = getHauteur(x,yh); vec3 vg(-eps, 0, g-ha), vd(eps, 0, d-ha), vb(0, eps, b-ha), vh(0, -eps, h-ha); float distg = length(vg), distd = length(vd), distb = length(vb), disth = length(vh); vec3 v1 = cross(vg,vh), v2 = cross(vh,vd), v3 = cross(vd,vb), v4 = cross(vb,vg); vec3 normale(0,0,0); if(distg*disth > 0) normale += normalize(v1)*distg*disth; if(disth*distd > 0) normale += normalize(v2)*disth*distd; if(distd*distb > 0) normale += normalize(v3)*distd*distb; if(distb*distg > 0) normale += normalize(v4)*distb*distg; normale = normalize(normale); return normale; } /*******************************Image********************************/ TerrainTab::TerrainTab(const QImage &img, float longueur, float largeur, float amplitude): Terrain(longueur,largeur,amplitude), height(img.height()), width(img.width()), amplitude(amplitude) { initGrille(); simpleInitImage(img); updateElevation(); } TerrainTab::TerrainTab(const QImage& img, int _nbHeight, int _nbWidth, float longueur, float largeur, float amplitude): Terrain(longueur,largeur,amplitude), height(_nbHeight), width(_nbWidth), amplitude(amplitude) { initGrille(); if(_nbHeight == img.height() && _nbWidth == img.width()) simpleInitImage(img); else { for(int j = 0; j < _nbHeight; j++) { float y = j*(float)(img.height()-1)/(_nbHeight-1); int y1 = floorf(y), y2 = ceilf(y); for(int i = 0; i < _nbWidth; i++) { float x = i*(float)(img.width()-1)/(_nbWidth-1); int x1 = floorf(x), x2 = ceilf(x); float z = interp::interp_hermite2D(x,y, x1,y1,x2,y2, qGray(img.pixel(x1, y1))/255.0, qGray(img.pixel(x1, y2))/255.0, qGray(img.pixel(x2, y1))/255.0, qGray(img.pixel(x2, y2))/255.0 ); grille2d[j][i] = z; } } } updateElevation(); } /**construit un terrain avec le même nombre de point que le nombre de pixel de l'image*/ void TerrainTab::simpleInitImage(const QImage& img) { for(int j = 0; j < height; j++) for(int i = 0; i < width; i++) grille2d[j][i] = qGray(img.pixel(i,j))/255.0; } void TerrainTab::initGrille() { grille = new float[height*width]; grille2d = new float*[height]; for(int j = 0; j < height; j++) grille2d[j] = &grille[j*width]; } /********************************************************************************************/ float TerrainTab::minElevation() const{ return hauteurMin; //pas bon } float TerrainTab::maxElevation() const{ return hauteurMax; //pas bon }
[ "aureargo@hotmail.fr" ]
aureargo@hotmail.fr
b35967db68b6cf34435b12c6c2daeebebed5d8de
d36622b2f861e2732b2012e978fe8fd77051ac08
/winframe.h
751485c9f363824cef965e78540f7e32b7f82825
[]
no_license
urielyan/kairen_github
baad5d8a3a2212a7e84bec2a8e5066682aa03343
0d06843f9ae69728e258cecd8b7d9b63dd430e3d
refs/heads/master
2021-01-21T13:03:48.263957
2016-04-20T01:16:50
2016-04-20T01:16:50
53,041,563
0
0
null
null
null
null
UTF-8
C++
false
false
915
h
#ifndef WINFRAME_H #define WINFRAME_H #include <QObject> #include <QFrame> #include <QLabel> class WinAbstractFrame : public QFrame { Q_OBJECT public: WinAbstractFrame(QWidget *parent = 0); signals: public slots: }; class WinBottomFrame : public WinAbstractFrame { Q_OBJECT enum ENUM_LABEL { enum_SAMPLE = 0, enum_PREHEAT_ALARM, enum_DATETIME, }; public: static WinBottomFrame* instance(); static QString stat_str_Reference, stat_str_test; void setSampleLabelText(QString text = ""); private slots: void update_time(); void updataPreheatAlarm(); private: WinBottomFrame(QWidget *parent = 0); QLabel* p_label[3]; }; class WinTestMeasurement : public WinAbstractFrame { Q_OBJECT public: static WinTestMeasurement* instance(); private slots: private: WinTestMeasurement(QWidget *parent = 0); }; #endif // WINFRAME_H
[ "urielyan@sina.com" ]
urielyan@sina.com
b23fb402497289efde11d9f677417822d24af3e3
cf82ec080cf56abb743faf4a70e5b5db055db252
/GCserver/src/RuntimePlatform.cpp
21279956533c95dbd19d9dba95b5a591ee977a2a
[]
no_license
raghav1203/GC_SERVER
f2a0c1c75b36e1e17f7b844511ff74586259a2dc
e834423365d576b4737bb8e939768b0c5916aa8a
refs/heads/master
2016-09-05T16:56:45.205804
2015-01-02T13:53:20
2015-01-02T13:53:20
28,714,636
0
0
null
null
null
null
UTF-8
C++
false
false
118
cpp
#include "RuntimePlatform.h" RuntimePlatform& RuntimePlatform::getPlatform() { return RuntimePlatform.WINDOWS; }
[ "raghvendra.1203@yahoo.com" ]
raghvendra.1203@yahoo.com
6b89ea92b2c198c40e652ee3461a78650c7b1bb6
89b7e4a17ae14a43433b512146364b3656827261
/testcases/CWE762_Mismatched_Memory_Management_Routines/s06/CWE762_Mismatched_Memory_Management_Routines__new_free_int64_t_68a.cpp
e3e57bc34db170e3b72e5e7ae04af5aa67acbe23
[]
no_license
tuyen1998/Juliet_test_Suite
7f50a3a39ecf0afbb2edfd9f444ee017d94f99ee
4f968ac0376304f4b1b369a615f25977be5430ac
refs/heads/master
2020-08-31T23:40:45.070918
2019-11-01T07:43:59
2019-11-01T07:43:59
218,817,337
0
1
null
null
null
null
UTF-8
C++
false
false
2,742
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__new_free_int64_t_68a.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_free.label.xml Template File: sources-sinks-68a.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: Allocate data using new * GoodSource: Allocate data using malloc() * Sinks: * GoodSink: Deallocate data using delete * BadSink : Deallocate data using free() * Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__new_free_int64_t_68 { int64_t * badData; int64_t * goodG2BData; int64_t * goodB2GData; #ifndef OMITBAD /* bad function declaration */ void badSink(); void bad() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */ data = new int64_t; badData = data; badSink(); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ void goodG2BSink(); void goodB2GSink(); /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { int64_t * data; /* Initialize data*/ data = NULL; /* FIX: Allocate memory from the heap using malloc() */ data = (int64_t *)malloc(100*sizeof(int64_t)); if (data == NULL) {exit(-1);} goodG2BData = data; goodG2BSink(); } /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */ data = new int64_t; goodB2GData = data; goodB2GSink(); } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__new_free_int64_t_68; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "35531872+tuyen1998@users.noreply.github.com" ]
35531872+tuyen1998@users.noreply.github.com
8a788466a57b99c1d992e3e8ec69862276a0e824
9ec8ffe28d54be5af26e83d9898105832ad3f119
/src/sentimental/bayesnet/undirectedgraph.cpp
370072829dd48fd0a6f58b87dbfbc42fb181980e
[]
no_license
Fs02/sentimental
98e5696d9819af95036ae770a7c10067d1d1389d
3d8d94bf30e533ff7e41987dbe2c311b29f3f673
refs/heads/master
2021-03-27T20:40:44.276670
2017-09-02T16:16:49
2017-09-02T16:16:49
77,728,342
0
0
null
2017-03-05T00:17:25
2016-12-31T06:26:02
C++
UTF-8
C++
false
false
3,527
cpp
#include <sentimental/bayesnet/undirectedgraph.h> #include <algorithm> #include <stack> #include <unordered_set> using namespace sm::bayesnet; UndirectedGraph::UndirectedGraph() : vertices_(), neighbours_() {} std::size_t UndirectedGraph::vertex(const std::string &name) const { auto it = std::find(vertices_.cbegin(), vertices_.cend(), name); if (it == vertices_.cend()) return vertices_.size(); return std::distance(vertices_.cbegin(), it); } std::string UndirectedGraph::vertex(std::size_t id) const { return vertices_[id]; } bool UndirectedGraph::add_vertex(const std::string &name) { auto it = std::find(vertices_.cbegin(), vertices_.cend(), name); if (it != vertices_.cend()) return false; vertices_.push_back(name); neighbours_[vertices_.size() - 1] = std::vector<std::size_t>(); return true; } bool UndirectedGraph::rem_vertex(std::size_t id) { vertices_.erase(vertices_.begin() + id); // transfer id for (std::size_t i = id; i < vertices_.size(); ++i) { neighbours_[i] = neighbours_[i+1]; for (auto it = neighbours_[i].begin(); it != neighbours_[i].end(); ++it) { if (*it == id) it = neighbours_[i].erase(it); else if (*it > id) *it = *it - 1; } } neighbours_.erase(vertices_.size() - 1); return true; } bool UndirectedGraph::add_neighbour(std::size_t from, std::size_t to) { std::vector<std::size_t> &from_nb = neighbours_.at(from); { auto it = std::find(from_nb.cbegin(), from_nb.cend(), to); if (it == from_nb.cend()) return false; } std::vector<std::size_t> &to_nb = neighbours_.at(to); { auto it = std::find(to_nb.cbegin(), to_nb.cend(), from); if (it == to_nb.cend()) return false; } from_nb.push_back(to); to_nb.push_back(from); return true; } bool UndirectedGraph::rem_neighbour(std::size_t from, std::size_t to) { std::vector<std::size_t> &from_nb = neighbours_.at(from); { auto it = std::find(from_nb.cbegin(), from_nb.cend(), to); if (it != from_nb.cend()) from_nb.erase(it); } std::vector<std::size_t> &to_nb = neighbours_.at(to); { auto it = std::find(to_nb.cbegin(), to_nb.cend(), from); if (it != to_nb.cend()) to_nb.erase(it); } return true; } bool UndirectedGraph::clear() { vertices_.clear(); neighbours_.clear(); } bool UndirectedGraph::clear_neighbours(std::size_t vertex_id) { neighbours_.at(vertex_id).clear(); return true; } bool UndirectedGraph::clear_all_neighbours() { for (auto neighbours : neighbours_) neighbours.second.clear(); } bool UndirectedGraph::separated(std::size_t from, std::size_t to) const { return !connected(from, to); } bool UndirectedGraph::connected(std::size_t from, std::size_t to) const { if (from == to) return true; // do dfs std::stack<std::size_t> stack; std::unordered_set<std::size_t> discovered; stack.push(from); while (!stack.empty()) { std::size_t current = stack.top(); stack.pop(); if (discovered.find(current) == discovered.end()) { discovered.insert(current); for (auto nb : neighbours_.at(current)) { if (nb == to) return true; stack.push(to); } } } return false; }
[ "surya.asriadie@gmail.com" ]
surya.asriadie@gmail.com
5b1686b46db389292f2b07d3a2221dac8cc01503
b55835565b2ec5c75856f0f4bebaa941b932c8ca
/musli/StreamPacker.h
9ddf0be03bafb47a0643623e0b666319af69013b
[ "MIT" ]
permissive
rioki/musli
358cb2ee3482f34383553a9690fdfbddc46710b6
4efa634f4a70d7d9a39df8f42463934ea9c0e4be
refs/heads/master
2021-01-25T03:40:46.481754
2021-01-08T10:51:24
2021-01-08T10:51:24
1,584,248
0
0
null
null
null
null
UTF-8
C++
false
false
1,704
h
// musli - simple serialisation library // Copyright (c) 2011-2021 Sean Farrell // // 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 _MUSLI_STREAM_PACKER_H_ #define _MUSLI_STREAM_PACKER_H_ #include "config.h" #include "Packer.h" #include <iosfwd> namespace musli { //! Implementation of a Packer that packs to std::ostream. class MUSLI_EXPORT StreamPacker : public Packer { public: //! Constructor //! //! @param stream the stream to pack to StreamPacker(std::ostream& stream); protected: virtual void write(const char* data, unsigned int size); private: std::ostream& stream; }; } #endif
[ "sean.farrell@rioki.org" ]
sean.farrell@rioki.org
9fb15f582213871f5616e19c74d72fad379de81c
3a174b12caad3e651d314e3baaba5fc02d08806d
/src/ciripch.cpp
862036eedb8eb1a45e3fc9a875ad5119b67e1a8e
[]
no_license
cianjinks/CiriGB
db63a2cbdb04b676c75aa3e35a95efe8802708bb
34777401a26080f0e5708293e7239eccd723ae99
refs/heads/master
2023-02-01T23:53:30.675899
2020-12-18T14:49:52
2020-12-18T14:49:52
311,473,158
0
0
null
null
null
null
UTF-8
C++
false
false
20
cpp
#include "ciripch.h"
[ "cjinks99@gmail.com" ]
cjinks99@gmail.com
7e00cf54029afa2705abcf4c75a815c304890e45
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/openh264/src/codec/encoder/core/inc/rc.h
ec15a62f9e08360b6e6d6baf26dc15440a2b1912
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
9,558
h
/*! * \copy * Copyright (c) 2004-2013, Cisco Systems * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * ratectl.c * * Abstract * Include file for ratectl.c * * History * 9/8/2004 Created * 12/26/2011 Modified * * *************************************************************************/ #ifndef RC_H #define RC_H #include "codec_app_def.h" #include "svc_enc_macroblock.h" #include "slice.h" namespace WelsEnc { typedef struct TagWelsEncCtx sWelsEncCtx; //trace #define GOM_TRACE_FLAG 0 #define GOM_H_SCC 8 enum { BITS_NORMAL, BITS_LIMITED, BITS_EXCEEDED }; enum { //virtual gop size VGOP_SIZE = 8, //qp information GOM_MIN_QP_MODE = 12, GOM_MAX_QP_MODE = 36, MAX_LOW_BR_QP = 42, MIN_IDR_QP = 26, MAX_IDR_QP = 32, MIN_SCREEN_QP = 26, MAX_SCREEN_QP = 35, DELTA_QP = 2, DELTA_QP_BGD_THD = 3, //frame skip constants SKIP_QP_90P = 24, SKIP_QP_180P = 24, SKIP_QP_360P = 31, SKIP_QP_720P = 31, LAST_FRAME_QP_RANGE_UPPER_MODE0 = 3, LAST_FRAME_QP_RANGE_LOWER_MODE0 = 2, LAST_FRAME_QP_RANGE_UPPER_MODE1 = 5, LAST_FRAME_QP_RANGE_LOWER_MODE1 = 3, MB_WIDTH_THRESHOLD_90P = 15, MB_WIDTH_THRESHOLD_180P = 30, MB_WIDTH_THRESHOLD_360P = 60, //Mode 0 parameter GOM_ROW_MODE0_90P = 2, GOM_ROW_MODE0_180P = 2, GOM_ROW_MODE0_360P = 4, GOM_ROW_MODE0_720P = 4, QP_RANGE_MODE0 = 3, //Mode 1 parameter GOM_ROW_MODE1_90P = 1, GOM_ROW_MODE1_180P = 1, GOM_ROW_MODE1_360P = 2, GOM_ROW_MODE1_720P = 2, QP_RANGE_UPPER_MODE1 = 9, QP_RANGE_LOWER_MODE1 = 4, QP_RANGE_INTRA_MODE1 = 3 }; //bits allocation #define MAX_BITS_VARY_PERCENTAGE 100 //bits vary range in percentage #define MAX_BITS_VARY_PERCENTAGE_x3d2 150 //bits vary range in percentage * 3/2 #define INT_MULTIPLY 100 // use to multiply in Double to Int Conversion, should be same as AQ_QSTEP_INT_MULTIPLY in WelsVP #define WEIGHT_MULTIPLY 2000 #define REMAIN_BITS_TH (1) #define VGOP_BITS_PERCENTAGE_DIFF 5 #define IDR_BITRATE_RATIO 4 #define FRAME_iTargetBits_VARY_RANGE 50 // *INT_MULTIPLY //R-Q Model #define LINEAR_MODEL_DECAY_FACTOR 80 // *INT_MULTIPLY #define FRAME_CMPLX_RATIO_RANGE 10 // *INT_MULTIPLY #define SMOOTH_FACTOR_MIN_VALUE 2 // *INT_MULTIPLY //#define VGOP_BITS_MIN_RATIO 0.8 //skip and padding #define TIME_CHECK_WINDOW 5000 // ms #define SKIP_RATIO 50 // *INT_MULTIPLY #define LAST_FRAME_PREDICT_WEIGHT 0.5 #define PADDING_BUFFER_RATIO 50 // *INT_MULTIPLY #define PADDING_THRESHOLD 5 //*INT_MULTIPLY #define VIRTUAL_BUFFER_LOW_TH 120 //*INT_MULTIPLY #define VIRTUAL_BUFFER_HIGH_TH 180 //*INT_MULTIPLY #define _BITS_RANGE 0 enum { EVEN_TIME_WINDOW =0, ODD_TIME_WINDOW =1, TIME_WINDOW_TOTAL =2 }; typedef struct TagRCSlicing { int32_t iComplexityIndexSlice; int32_t iCalculatedQpSlice; int32_t iStartMbSlice; int32_t iEndMbSlice; int32_t iTotalQpSlice; int32_t iTotalMbSlice; int32_t iTargetBitsSlice; int32_t iBsPosSlice; int32_t iFrameBitsSlice; int32_t iGomBitsSlice; int32_t iGomTargetBits; //int32_t gom_coded_mb; } SRCSlicing; typedef struct TagRCTemporal { int32_t iMinBitsTl; int32_t iMaxBitsTl; int32_t iTlayerWeight; int32_t iGopBitsDq; //P frame level R-Q Model int64_t iLinearCmplx; // *INT_MULTIPLY int32_t iPFrameNum; int32_t iFrameCmplxMean; } SRCTemporal; typedef struct TagWelsRc { int32_t iRcVaryPercentage; int32_t iRcVaryRatio; int32_t iInitialQp; //initial qp int64_t iBitRate; // Note: although the max bit rate is 240000*1200 which can be represented by int32, but there are many multipler of this iBitRate in the calculation of RC, so use int64 to avoid type conversion at all such places int32_t iPreviousBitrate; int32_t iPreviousGopSize; double fFrameRate; int32_t iBitsPerFrame; int32_t iMaxBitsPerFrame; double dPreviousFps; // bits allocation and status int32_t iRemainingBits; int32_t iTargetBits; int32_t iCurrentBitsLevel;//0:normal; 1:limited; 2:exceeded. int32_t iIdrNum; int64_t iIntraComplexity; //255*255(MaxMbSAD)*36864(MaxFS) make the highest bit of 32-bit integer 1 int32_t iIntraMbCount; int8_t iTlOfFrames[VGOP_SIZE]; int32_t iRemainingWeights; int32_t iFrameDqBits; double* pGomComplexity; int32_t* pGomForegroundBlockNum; int32_t* pCurrentFrameGomSad; int32_t* pGomCost; int32_t iAverageFrameQp; int32_t iMinFrameQp; int32_t iMaxFrameQp; int32_t iNumberMbFrame; int32_t iNumberMbGom; int32_t iSliceNum; int32_t iGomSize; int32_t iSkipFrameNum; int32_t iFrameCodedInVGop; int32_t iSkipFrameInVGop; int32_t iGopNumberInVGop; int32_t iGopIndexInVGop; int32_t iSkipQpValue; int32_t iQpRangeUpperInFrame; int32_t iQpRangeLowerInFrame; int32_t iMinQp; int32_t iMaxQp; //int32_t delta_adaptive_qp; int32_t iSkipBufferRatio; int32_t iQStep; // *INT_MULTIPLY int32_t iFrameDeltaQpUpper; int32_t iFrameDeltaQpLower; int32_t iLastCalculatedQScale; //for skip frame and padding int32_t iBufferSizeSkip; int64_t iBufferFullnessSkip; int64_t iBufferMaxBRFullness[TIME_WINDOW_TOTAL];//0: EVEN_TIME_WINDOW; 1: ODD_TIME_WINDOW int32_t iPredFrameBit; bool bNeedShiftWindowCheck[TIME_WINDOW_TOTAL]; int32_t iBufferSizePadding; int32_t iBufferFullnessPadding; int32_t iPaddingSize; int32_t iPaddingBitrateStat; bool bSkipFlag; SRCSlicing* pSlicingOverRc; SRCTemporal* pTemporalOverRc; //for scc int64_t iAvgCost2Bits; int64_t iCost2BitsIntra; int32_t iBaseQp; long long uiLastTimeStamp; //for statistics and online adjustments int32_t iActualBitRate; // TODO: to complete later float fLatestFrameRate; // TODO: to complete later } SWelsSvcRc; typedef void (*PWelsRCPictureInitFunc) (sWelsEncCtx* pCtx,long long uiTimeStamp); typedef void (*PWelsRCPictureDelayJudgeFunc) (sWelsEncCtx* pCtx, EVideoFrameType eFrameType, long long uiTimeStamp); typedef void (*PWelsRCPictureInfoUpdateFunc) (sWelsEncCtx* pCtx, int32_t iLayerSize); typedef void (*PWelsRCMBInfoUpdateFunc) (sWelsEncCtx* pCtx, SMB* pCurMb, int32_t iCostLuma, SSlice* pSlice); typedef void (*PWelsRCMBInitFunc) (sWelsEncCtx* pCtx, SMB* pCurMb, SSlice* pSlice); typedef bool (*PWelsCheckFrameSkipBasedMaxbrFunc) (sWelsEncCtx* pCtx, int32_t iSpatialNum, EVideoFrameType eFrameType, const uint32_t uiTimeStamp); typedef void (*PWelsUpdateBufferWhenFrameSkippedFunc)(sWelsEncCtx* pCtx, int32_t iSpatialNum); typedef void (*PWelsUpdateMaxBrCheckWindowStatusFunc)(sWelsEncCtx* pCtx, int32_t iSpatialNum, const long long uiTimeStamp); typedef bool (*PWelsRCPostFrameSkippingFunc)(sWelsEncCtx* pCtx, const int32_t iDid, const long long uiTimeStamp); typedef struct WelsRcFunc_s { PWelsRCPictureInitFunc pfWelsRcPictureInit; PWelsRCPictureDelayJudgeFunc pfWelsRcPicDelayJudge; PWelsRCPictureInfoUpdateFunc pfWelsRcPictureInfoUpdate; PWelsRCMBInitFunc pfWelsRcMbInit; PWelsRCMBInfoUpdateFunc pfWelsRcMbInfoUpdate; PWelsCheckFrameSkipBasedMaxbrFunc pfWelsCheckSkipBasedMaxbr; PWelsUpdateBufferWhenFrameSkippedFunc pfWelsUpdateBufferWhenSkip; PWelsUpdateMaxBrCheckWindowStatusFunc pfWelsUpdateMaxBrWindowStatus; PWelsRCPostFrameSkippingFunc pfWelsRcPostFrameSkipping; } SWelsRcFunc; bool CheckFrameSkipBasedMaxbr (sWelsEncCtx* pCtx, int32_t iSpatialNum, EVideoFrameType eFrameType, const uint32_t uiTimeStamp); void UpdateBufferWhenFrameSkipped(sWelsEncCtx* pCtx, int32_t iSpatialNum); void UpdateMaxBrCheckWindowStatus(sWelsEncCtx* pCtx, int32_t iSpatialNum, const long long uiTimeStamp); bool WelsRcPostFrameSkipping(sWelsEncCtx* pCtx, const int32_t iDid, const long long uiTimeStamp); void WelsRcPostFrameSkippedUpdate (sWelsEncCtx* pCtx, const int32_t iDid); void RcTraceFrameBits (sWelsEncCtx* pEncCtx, long long uiTimeStamp); void WelsRcInitModule (sWelsEncCtx* pCtx, RC_MODES iRcMode); void WelsRcInitFuncPointers (sWelsEncCtx* pEncCtx, RC_MODES iRcMode); void WelsRcFreeMemory (sWelsEncCtx* pCtx); } #endif //RC_H
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
20f0d385677aa97540a642575f357b0c9c0f8fad
0af16f53b3450882e994aec44b20dcf277372b4f
/Forms/ODLinkPropertiesDialogDef.h
4850364c14f39980e648d6b4e8caba78579ee063
[]
no_license
hreuver0183/ocpn_draw_pi
2372e34de010f60c835768613c7255177d240a15
4115bec72879e6ffc407e0af149e7d38619070d5
refs/heads/master
2022-12-21T20:21:19.963709
2020-10-03T14:17:16
2020-10-03T14:17:16
285,889,919
0
0
null
2020-08-07T17:53:44
2020-08-07T17:53:43
null
UTF-8
C++
false
false
1,879
h
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version Oct 26 2018) // http://www.wxformbuilder.org/ // // PLEASE DO *NOT* EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #pragma once #include <wx/artprov.h> #include <wx/xrc/xmlres.h> #include <wx/intl.h> #include <wx/string.h> #include <wx/stattext.h> #include <wx/gdicmn.h> #include <wx/font.h> #include <wx/colour.h> #include <wx/settings.h> #include <wx/textctrl.h> #include <wx/filepicker.h> #include <wx/sizer.h> #include <wx/statbox.h> #include <wx/bitmap.h> #include <wx/image.h> #include <wx/icon.h> #include <wx/button.h> #include <wx/dialog.h> /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /// Class ODLinkPropertiesDialogDef /////////////////////////////////////////////////////////////////////////////// class ODLinkPropertiesDialogDef : public wxDialog { private: protected: wxStaticText* m_staticTextLinkDescription; wxTextCtrl* m_textCtrlLinkDescription; wxStaticText* m_staticTextURL; wxTextCtrl* m_textCtrlURL; wxFilePickerCtrl* m_filePickerLocalFile; wxButton* m_buttonOK; wxButton* m_buttonCancel; // Virtual event handlers, overide them in your derived class virtual void OnFileChanged( wxFileDirPickerEvent& event ) { event.Skip(); } virtual void OnOKClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnCancelClick( wxCommandEvent& event ) { event.Skip(); } public: ODLinkPropertiesDialogDef( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 189,299 ), long style = wxDEFAULT_DIALOG_STYLE ); ~ODLinkPropertiesDialogDef(); };
[ "jon.gough@eclipsesystems.com.au" ]
jon.gough@eclipsesystems.com.au
80e09b198dc4476f44f470f4f4e44ab202059175
9e932f84264d812e1a5f209ec3b0591a6216b148
/Raytracer (Offline)/BasicScene.h
edc55b9f7ba17ac8f0a7ec55784de75ee22ce28c
[ "MIT" ]
permissive
bryanlawsmith/Raytracing
17321b4bd0575b8f221ce727ba3d7bbdebb8b83c
519b3f3867e0c00b92091dd755a4a73121e22064
refs/heads/master
2016-08-11T19:39:47.422605
2016-02-02T13:17:28
2016-02-02T13:17:28
46,450,267
1
0
null
null
null
null
UTF-8
C++
false
false
527
h
#pragma once #include "IScene.h" #include <vector> namespace Raytracer { /// <summary> /// Basic implementation of the IScene interface which does not partition scene elements /// using some form of spatial subdivision. /// </summary> class BasicScene : public IScene { public: BasicScene(); bool Trace(const ray& intersectionRay, float* t, float* results) const override; void AddTraceable(ITraceable& traceable) override; void Clear() override; protected: std::vector<ITraceable*> m_Elements; }; }
[ "bryanlawsmith@gmail.com" ]
bryanlawsmith@gmail.com
b7d9a1b60ed2ab593d2b66db8d2c06d56c6082dd
164ffe077dde59373ad9fadcfd727f279a1cfe93
/jni_build/jni/include/tensorflow/core/framework/common_shape_fns.cc
6439a2854e0a30f55274224ceef9174c3cf45038
[]
no_license
Basofe/Community_Based_Repository_Traffic_Signs
524a4cfc77dc6ed3b279556e4201ba63ee8cf6bd
a20da440a21ed5160baae4d283c5880b8ba8e83c
refs/heads/master
2021-01-22T21:17:37.392145
2017-09-28T21:35:58
2017-09-28T21:35:58
85,407,197
0
2
null
null
null
null
UTF-8
C++
false
false
24,921
cc
/* Copyright 2016 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/framework/common_shape_fns.h" namespace tensorflow { Status GetWindowedOutputSizeVerbose(int64 input_size, int64 filter_size, int64 stride, Padding padding_type, int64* output_size, int64* padding_before, int64* padding_after) { if (stride <= 0) { return errors::InvalidArgument("Stride must be > 0, but got ", stride); } switch (padding_type) { case Padding::VALID: *output_size = (input_size - filter_size + stride) / stride; *padding_before = *padding_after = 0; break; case Padding::SAME: *output_size = (input_size + stride - 1) / stride; const int64 padding_needed = std::max(0LL, (*output_size - 1) * stride + filter_size - input_size); // For odd values of total padding, add more padding at the 'right' // side of the given dimension. *padding_before = padding_needed / 2; *padding_after = padding_needed - *padding_before; break; } if (*output_size < 0) { return errors::InvalidArgument("computed output size would be negative"); } return Status::OK(); } Status GetWindowedOutputSize(int64 input_size, int64 filter_size, int64 stride, Padding padding_type, int64* output_size, int64* padding) { int64 padding_after_unused; return GetWindowedOutputSizeVerbose(input_size, filter_size, stride, padding_type, output_size, padding, &padding_after_unused); } Status Get3dOutputSize(const std::array<int64, 3>& input, const std::array<int64, 3>& window, const std::array<int64, 3>& strides, Padding padding_type, std::array<int64, 3>* output_ptr, std::array<int64, 3>* padding_ptr) { for (size_t i = 0; i < input.size(); ++i) { TF_RETURN_IF_ERROR(GetWindowedOutputSize(input[i], window[i], strides[i], padding_type, &(*output_ptr)[i], &(*padding_ptr)[i])); } return Status::OK(); } namespace shape_inference { Status UnchangedShape(shape_inference::InferenceContext* c) { c->set_output(0, c->input(0)); return Status::OK(); } Status MatMulShape(shape_inference::InferenceContext* c) { const Shape* a; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &a)); const Shape* b; TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 2, &b)); bool transpose_a, transpose_b; TF_RETURN_IF_ERROR(c->GetAttr("transpose_a", &transpose_a)); TF_RETURN_IF_ERROR(c->GetAttr("transpose_b", &transpose_b)); const Dimension* output_rows = transpose_a ? c->Dim(a, 1) : c->Dim(a, 0); const Dimension* output_cols = transpose_b ? c->Dim(b, 0) : c->Dim(b, 1); // Validate that the inner shapes are compatible. const Dimension* inner_a = transpose_a ? c->Dim(a, 0) : c->Dim(a, 1); const Dimension* inner_b = transpose_b ? c->Dim(b, 1) : c->Dim(b, 0); const Dimension* merged; TF_RETURN_IF_ERROR(c->Merge(inner_a, inner_b, &merged)); c->set_output(0, c->Matrix(output_rows, output_cols)); return Status::OK(); } Status BiasAddShape(shape_inference::InferenceContext* c) { const Shape* input_shape; // Fetch the data_format attribute, which may not exist. string data_format; Status s = c->GetAttr("data_format", &data_format); if (s.ok() && data_format == "NCHW") { TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 4, &input_shape)); } else { TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 2, &input_shape)); } const Shape* bias_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &bias_shape)); const Dimension* bias_dim = c->Dim(bias_shape, 0); // If rank unknown, return unknown shape. if (!c->RankKnown(input_shape)) { c->set_output(0, c->UnknownShape()); return Status::OK(); } // Output has the same shape as the input, and matches the length of // the bias in its bias dimension. const Shape* output_shape; if (s.ok() && data_format == "NCHW") { // Merge the length of bias_shape into the third to last dimension const Shape* first; TF_RETURN_IF_ERROR(c->Subshape(input_shape, 0, -3, &first)); const Shape* last; TF_RETURN_IF_ERROR(c->Subshape(input_shape, -2, &last)); const Dimension* input_bias_dim = c->Dim(input_shape, -3); const Dimension* merged_bias_dim; TF_RETURN_IF_ERROR(c->Merge(input_bias_dim, bias_dim, &merged_bias_dim)); const Shape* merged_bias = c->Vector(merged_bias_dim); const Shape* temp; TF_RETURN_IF_ERROR(c->Concatenate(first, merged_bias, &temp)); TF_RETURN_IF_ERROR(c->Concatenate(temp, last, &output_shape)); } else { const Shape* all_but_bias; TF_RETURN_IF_ERROR(c->Subshape(input_shape, 0, -1, &all_but_bias)); const Dimension* input_bias_dim = c->Dim(input_shape, -1); const Dimension* merged_bias_dim; TF_RETURN_IF_ERROR(c->Merge(input_bias_dim, bias_dim, &merged_bias_dim)); const Shape* merged_bias = c->Vector(merged_bias_dim); TF_RETURN_IF_ERROR( c->Concatenate(all_but_bias, merged_bias, &output_shape)); } c->set_output(0, output_shape); return Status::OK(); } Status BiasAddGradShape(shape_inference::InferenceContext* c) { const Shape* input_shape; // Fetch the data_format attribute, which may not exist. string data_format; Status s = c->GetAttr("data_format", &data_format); if (s.ok() && data_format == "NCHW") { TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 4, &input_shape)); c->set_output(0, c->Vector(c->Dim(input_shape, -3))); } else { TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 2, &input_shape)); c->set_output(0, c->Vector(c->Dim(input_shape, -1))); } return Status::OK(); } Status Conv2DShape(shape_inference::InferenceContext* c) { const Shape* input_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 4, &input_shape)); const Shape* filter_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 4, &filter_shape)); string data_format; Status s = c->GetAttr("data_format", &data_format); std::vector<int32> strides; TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides)); if (strides.size() != 4) { return errors::InvalidArgument( "Conv2D requires the stride attribute to contain 4 values, but got: ", strides.size()); } int32 stride_rows, stride_cols; if (s.ok() && data_format == "NCHW") { // Convert input shape to default NHWC for inference input_shape = c->MakeShape({{c->Dim(input_shape, 0), c->Dim(input_shape, 2), c->Dim(input_shape, 3), c->Dim(input_shape, 1)}}); stride_rows = strides[2]; stride_cols = strides[3]; } else { stride_rows = strides[1]; stride_cols = strides[2]; } const Dimension* batch_size_dim = c->Dim(input_shape, 0); const Dimension* in_rows_dim = c->Dim(input_shape, 1); const Dimension* in_cols_dim = c->Dim(input_shape, 2); const Dimension* filter_rows_dim = c->Dim(filter_shape, 0); const Dimension* filter_cols_dim = c->Dim(filter_shape, 1); const Dimension* output_depth_dim = c->Dim(filter_shape, 3); // At the moment we need to know the values of several fields. TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_rows_dim, "in_rows")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_cols_dim, "in_cols")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(filter_rows_dim, "filter_rows")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(filter_cols_dim, "filter_cols")); auto in_rows = c->Value(in_rows_dim); auto in_cols = c->Value(in_cols_dim); auto filter_rows = c->Value(filter_rows_dim); auto filter_cols = c->Value(filter_cols_dim); const Dimension* unused; TF_RETURN_IF_ERROR( c->Merge(c->Dim(input_shape, 3), c->Dim(filter_shape, 2), &unused)); Padding padding; TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding)); int64 output_rows, output_cols; int64 padding_before, padding_after; TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_rows, filter_rows, stride_rows, padding, &output_rows, &padding_before, &padding_after)); TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_cols, filter_cols, stride_cols, padding, &output_cols, &padding_before, &padding_after)); const Shape* output_shape; if (data_format == "NCHW") { output_shape = c->MakeShape( {batch_size_dim, output_depth_dim, output_rows, output_cols}); } else { output_shape = c->MakeShape( {batch_size_dim, output_rows, output_cols, output_depth_dim}); } c->set_output(0, output_shape); return Status::OK(); } Status Conv3DShape(shape_inference::InferenceContext* c) { const Shape* input_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 5, &input_shape)); const Shape* filter_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 5, &filter_shape)); std::vector<int32> strides; TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides)); if (strides.size() != 5) { return errors::InvalidArgument( "Conv3D requires the stride attribute to contain 5 values, but got: ", strides.size()); } int32 stride_planes = strides[1]; int32 stride_rows = strides[2]; int32 stride_cols = strides[3]; const Dimension* batch_size_dim = c->Dim(input_shape, 0); const Dimension* in_planes_dim = c->Dim(input_shape, 1); const Dimension* in_rows_dim = c->Dim(input_shape, 2); const Dimension* in_cols_dim = c->Dim(input_shape, 3); const Dimension* filter_planes_dim = c->Dim(filter_shape, 0); const Dimension* filter_rows_dim = c->Dim(filter_shape, 1); const Dimension* filter_cols_dim = c->Dim(filter_shape, 2); const Dimension* output_depth_dim = c->Dim(filter_shape, 4); // At the moment we need to know the values of several fields. TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_planes_dim, "in_planes")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_rows_dim, "in_rows")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_cols_dim, "in_cols")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(filter_planes_dim, "filter_planes")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(filter_rows_dim, "filter_rows")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(filter_cols_dim, "filter_cols")); auto in_planes = c->Value(in_planes_dim); auto in_rows = c->Value(in_rows_dim); auto in_cols = c->Value(in_cols_dim); auto filter_planes = c->Value(filter_planes_dim); auto filter_rows = c->Value(filter_rows_dim); auto filter_cols = c->Value(filter_cols_dim); const Dimension* unused; TF_RETURN_IF_ERROR( c->Merge(c->Dim(input_shape, 4), c->Dim(filter_shape, 3), &unused)); Padding padding; TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding)); int64 output_planes, output_rows, output_cols; int64 padding_before, padding_after; TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_planes, filter_planes, stride_planes, padding, &output_planes, &padding_before, &padding_after)); TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_rows, filter_rows, stride_rows, padding, &output_rows, &padding_before, &padding_after)); TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_cols, filter_cols, stride_cols, padding, &output_cols, &padding_before, &padding_after)); const Shape* output_shape = c->MakeShape({batch_size_dim, output_planes, output_rows, output_cols, output_depth_dim}); c->set_output(0, output_shape); return Status::OK(); } Status DepthwiseConv2DNativeShape(shape_inference::InferenceContext* c) { const Shape* input_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 4, &input_shape)); const Shape* filter_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 4, &filter_shape)); std::vector<int32> strides; TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides)); if (strides.size() != 4) { return errors::InvalidArgument( "DepthwiseConv2D requires the stride attribute to contain 4 values, " "but got: ", strides.size()); } const Dimension* batch_size_dim = c->Dim(input_shape, 0); const Dimension* in_rows_dim = c->Dim(input_shape, 1); const Dimension* in_cols_dim = c->Dim(input_shape, 2); const Dimension* filter_rows_dim = c->Dim(filter_shape, 0); const Dimension* filter_cols_dim = c->Dim(filter_shape, 1); const Dimension* input_depth = c->Dim(filter_shape, 2); const Dimension* depth_multiplier = c->Dim(filter_shape, 3); // At the moment we need to know the values of several fields. TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_rows_dim, "in_rows")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_cols_dim, "in_cols")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(filter_rows_dim, "filter_rows")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(filter_cols_dim, "filter_cols")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(input_depth, "depth")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(depth_multiplier, "depth_multiplier")); // Check that the input depths are compatible. TF_RETURN_IF_ERROR( c->Merge(c->Dim(input_shape, 3), input_depth, &input_depth)); const Dimension* output_depth; TF_RETURN_IF_ERROR(c->Multiply(input_depth, depth_multiplier, &output_depth)); const int32 stride_rows = strides[1]; const int32 stride_cols = strides[2]; Padding padding; TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding)); // TODO(mrry,shlens): Raise an error if the stride would cause // information in the input to be ignored. This will require a change // in the kernel implementation. auto in_rows = c->Value(in_rows_dim); auto in_cols = c->Value(in_cols_dim); auto filter_rows = c->Value(filter_rows_dim); auto filter_cols = c->Value(filter_cols_dim); int64 output_rows, output_cols; int64 padding_before, padding_after; TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_rows, filter_rows, stride_rows, padding, &output_rows, &padding_before, &padding_after)); TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_cols, filter_cols, stride_cols, padding, &output_cols, &padding_before, &padding_after)); const Shape* output_shape = c->MakeShape({batch_size_dim, output_rows, output_cols, output_depth}); c->set_output(0, output_shape); return Status::OK(); } Status AvgPoolShape(shape_inference::InferenceContext* c) { const Shape* input_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 4, &input_shape)); string data_format; Status s = c->GetAttr("data_format", &data_format); std::vector<int32> strides; TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides)); if (strides.size() != 4) { return errors::InvalidArgument( "AvgPool requires the stride attribute to contain 4 values, but " "got: ", strides.size()); } std::vector<int32> kernel_sizes; TF_RETURN_IF_ERROR(c->GetAttr("ksize", &kernel_sizes)); if (kernel_sizes.size() != 4) { return errors::InvalidArgument( "AvgPool requires the ksize attribute to contain 4 values, but got: ", kernel_sizes.size()); } int32 stride_rows, stride_cols; int32 kernel_rows, kernel_cols; if (s.ok() && data_format == "NCHW") { // Convert input shape to default NHWC for inference input_shape = c->MakeShape({{c->Dim(input_shape, 0), c->Dim(input_shape, 2), c->Dim(input_shape, 3), c->Dim(input_shape, 1)}}); stride_rows = strides[2]; stride_cols = strides[3]; kernel_rows = kernel_sizes[2]; kernel_cols = kernel_sizes[3]; } else { stride_rows = strides[1]; stride_cols = strides[2]; kernel_rows = kernel_sizes[1]; kernel_cols = kernel_sizes[2]; } const Dimension* batch_size_dim = c->Dim(input_shape, 0); const Dimension* in_rows_dim = c->Dim(input_shape, 1); const Dimension* in_cols_dim = c->Dim(input_shape, 2); const Dimension* output_depth_dim = c->Dim(input_shape, 3); // At the moment we need to know the values of several fields. TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_rows_dim, "in_rows")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_cols_dim, "in_cols")); Padding padding; TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding)); // TODO(mrry,shlens): Raise an error if the stride would cause // information in the input to be ignored. This will require a change // in the kernel implementation. auto in_rows = c->Value(in_rows_dim); auto in_cols = c->Value(in_cols_dim); int64 output_rows, output_cols; int64 padding_before, padding_after; TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_rows, kernel_rows, stride_rows, padding, &output_rows, &padding_before, &padding_after)); TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_cols, kernel_cols, stride_cols, padding, &output_cols, &padding_before, &padding_after)); const Shape* output_shape; if (data_format == "NCHW") { output_shape = c->MakeShape( {batch_size_dim, output_depth_dim, output_rows, output_cols}); } else { output_shape = c->MakeShape( {batch_size_dim, output_rows, output_cols, output_depth_dim}); } c->set_output(0, output_shape); return Status::OK(); } Status MaxPoolShape(shape_inference::InferenceContext* c) { const Shape* input_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 4, &input_shape)); string data_format; Status s = c->GetAttr("data_format", &data_format); std::vector<int32> strides; TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides)); if (strides.size() != 4) { return errors::InvalidArgument( "AvgPool requires the stride attribute to contain 4 values, but " "got: ", strides.size()); } std::vector<int32> kernel_sizes; TF_RETURN_IF_ERROR(c->GetAttr("ksize", &kernel_sizes)); if (kernel_sizes.size() != 4) { return errors::InvalidArgument( "AvgPool requires the ksize attribute to contain 4 values, but got: ", kernel_sizes.size()); } int32 stride_rows, stride_cols, stride_depth; int32 kernel_rows, kernel_cols, kernel_depth; if (s.ok() && data_format == "NCHW") { // Convert input shape to default NHWC for inference input_shape = c->MakeShape({{c->Dim(input_shape, 0), c->Dim(input_shape, 2), c->Dim(input_shape, 3), c->Dim(input_shape, 1)}}); stride_depth = strides[1]; stride_rows = strides[2]; stride_cols = strides[3]; kernel_depth = kernel_sizes[1]; kernel_rows = kernel_sizes[2]; kernel_cols = kernel_sizes[3]; } else { stride_rows = strides[1]; stride_cols = strides[2]; stride_depth = strides[3]; kernel_rows = kernel_sizes[1]; kernel_cols = kernel_sizes[2]; kernel_depth = kernel_sizes[3]; } const Dimension* batch_size_dim = c->Dim(input_shape, 0); const Dimension* in_rows_dim = c->Dim(input_shape, 1); const Dimension* in_cols_dim = c->Dim(input_shape, 2); const Dimension* in_depth_dim = c->Dim(input_shape, 3); // At the moment we need to know the values of several fields. TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_rows_dim, "in_rows")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_cols_dim, "in_cols")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_depth_dim, "in_depth")); Padding padding; TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding)); // TODO(mrry,shlens): Raise an error if the stride would cause // information in the input to be ignored. This will require a change // in the kernel implementation. auto in_rows = c->Value(in_rows_dim); auto in_cols = c->Value(in_cols_dim); auto in_depth = c->Value(in_depth_dim); int64 output_rows, output_cols, output_depth; int64 padding_before, padding_after; TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_rows, kernel_rows, stride_rows, padding, &output_rows, &padding_before, &padding_after)); TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_cols, kernel_cols, stride_cols, padding, &output_cols, &padding_before, &padding_after)); TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_depth, kernel_depth, stride_depth, padding, &output_depth, &padding_before, &padding_after)); const Shape* output_shape = c->MakeShape({batch_size_dim, output_rows, output_cols, output_depth}); if (data_format == "NCHW") { // Convert output shape back to expected NCHW data format. output_shape = c->MakeShape({c->Dim(output_shape, 0), c->Dim(output_shape, 3), c->Dim(output_shape, 1), c->Dim(output_shape, 2)}); } c->set_output(0, output_shape); return Status::OK(); } Status Pool3DShape(shape_inference::InferenceContext* c) { const Shape* input_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 5, &input_shape)); std::vector<int32> strides; TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides)); if (strides.size() != 5) { return errors::InvalidArgument( "Pool3D ops require the stride attribute to contain 5 values, but " "got: ", strides.size()); } std::vector<int32> kernel_sizes; TF_RETURN_IF_ERROR(c->GetAttr("ksize", &kernel_sizes)); if (kernel_sizes.size() != 5) { return errors::InvalidArgument( "Pool3D requires the ksize attribute to contain 5 values, but got: ", kernel_sizes.size()); } int32 stride_planes, stride_rows, stride_cols; int32 kernel_planes, kernel_rows, kernel_cols; stride_planes = strides[1]; stride_rows = strides[2]; stride_cols = strides[3]; kernel_planes = kernel_sizes[1]; kernel_rows = kernel_sizes[2]; kernel_cols = kernel_sizes[3]; const Dimension* batch_size_dim = c->Dim(input_shape, 0); const Dimension* in_planes_dim = c->Dim(input_shape, 1); const Dimension* in_rows_dim = c->Dim(input_shape, 2); const Dimension* in_cols_dim = c->Dim(input_shape, 3); const Dimension* output_depth_dim = c->Dim(input_shape, 4); // At the moment we need to know the values of several fields. TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_planes_dim, "in_planes")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_rows_dim, "in_rows")); TF_RETURN_IF_ERROR(c->ValidateKnownDim(in_cols_dim, "in_cols")); Padding padding; TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding)); // TODO(mrry,shlens): Raise an error if the stride would cause // information in the input to be ignored. This will require a change // in the kernel implementation. auto in_planes = c->Value(in_planes_dim); auto in_rows = c->Value(in_rows_dim); auto in_cols = c->Value(in_cols_dim); int64 output_planes, output_rows, output_cols; int64 padding_before, padding_after; TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_planes, kernel_planes, stride_planes, padding, &output_planes, &padding_before, &padding_after)); TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_rows, kernel_rows, stride_rows, padding, &output_rows, &padding_before, &padding_after)); TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( in_cols, kernel_cols, stride_cols, padding, &output_cols, &padding_before, &padding_after)); const Shape* output_shape = c->MakeShape({batch_size_dim, output_planes, output_rows, output_cols, output_depth_dim}); c->set_output(0, output_shape); return Status::OK(); } Status UnknownShape(shape_inference::InferenceContext* c) { for (int i = 0; i < c->num_outputs(); ++i) { c->set_output(i, c->UnknownShape()); } return Status::OK(); } } // namespace shape_inference } // namespace tensorflow
[ "helder_m_p_novais@hotmail.com" ]
helder_m_p_novais@hotmail.com
5c7766225070c27351069e2c03bd1d7189f01014
69a3b83413ad7699a1a91fd51eb0a51b7b4199f1
/Learning_routing/Nodes/App.cc
a95c5d5d171b8c3b14ad509dcf5c546c5794cb29
[]
no_license
Lee0xwee/OMNET-
c63b13cfcfd339c3476b6377e18a9efaf2a7c2fc
28d17486d8bedeb9ccb3fb0190aa7656c797c5c9
refs/heads/master
2021-10-20T11:26:39.000749
2019-02-27T14:37:54
2019-02-27T14:37:54
182,414,584
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,933
cc
/* * App.cc * * Created on: 2019Äê2ÔÂ26ÈÕ * Author: Jason */ #ifdef _MSC_VER #pragma warning(disable:4786) #endif # include <vector> # include <iostream> # include <omnetpp.h> # include "packet_m.h" using namespace omnetpp; using namespace std; class App :public cSimpleModule { private: //configure int myAddress; vector<int> destAddresses; cPar *sendIATime; cPar *packetLengthBytes; cMessage *generatePacket; long pkCounter; simsignal_t endToEndDelaySignal; simsignal_t hopCountSignal; simsignal_t sourceAddressSignal; public: App(); virtual ~App(); protected: virtual void initialize() override; virtual void handleMessage(cMessage *msg) override ; }; Define_Module(App); App::App() { generatePacket =nullptr; } App::~App() { cancelAndDelete (generatePacket); } void App::initialize() { myAddress =par("address"); packetLengthBytes=&par("packetLength"); sendIATime= &par("sendIaTime"); pkCounter=0; WATCH(pkCounter); WATCH(myAddress); const char *destAdderssesPar=par("destAddresses"); cStringTokenizer tokenizer(destAdderssesPar); const char *token; while((token=tokenizer.nextToken())!=nullptr) { destAddresses.push_back(atoi(token)); } if(destAddresses.size()==0) { throw cRuntimeError("At least one address must be specified in the destAdress parameter!"); } generatePacket =new cMessage("nextPacket"); scheduleAt(sendIATime->doubleValue(),generatePacket); endToEndDelaySignal =registerSignal("endToEndDelay"); hopCountSignal =registerSignal("hopCount"); sourceAddressSignal =registerSignal("sourceAdress"); } void App::handleMessage(cMessage *msg) { if(msg==generatePacket) { //sending packet int destAddress= destAddresses[intuniform(0,destAddresses.size()-1)]; char pkname[40]; sprintf(pkname,"pk-%d-to-%d-#1d",myAddress,destAddress,pkCounter++); EV<<"Generate packet "<< pkname <<endl; Packet *pk=new Packet(pkname); pk->setByteLength(packetLengthBytes->intValue()); pk->setKind(intuniform(0,7)); pk->setSrcAddr(myAddress); pk->setSrcAddr(destAddress); send(pk,"out"); scheduleAt(simTime()+sendIATime->doubleValue(),generatePacket); if(hasGUI()) { getParentModule()->bubble("Generating packet....."); } } else { //handle Packet Packet *pk= check_and_cast<Packet *>(msg); EV<<"Received packet"<<pk->getName()<<"after"<<pk->getHopCount()<<"hops"<<endl; emit(endToEndDelaySignal,simTime()-pk->getCreationTime()); emit(hopCountSignal,pk->getHopCount()); emit(sourceAddressSignal,pk->getSrcAddr()); if(hasGUI()) { getParentModule()->bubble("Arrived"); } } }
[ "41442321+Stephenhua@users.noreply.github.com" ]
41442321+Stephenhua@users.noreply.github.com
20f733cf78c8e867def3af98b29432785fc73b13
7afb4818a3ae770dc7edd539e0dea85d4d8474d3
/camcalib/2020/include/Dgelom/properties.hpp
4fdcb4a7656d212ede8894de831af7d3f1cc2a54
[]
no_license
ZL-Su/camera-calibration
5d9ac1266202950c605065dc97e8d08c9e7e9eb0
73cf1adbe2ea0cfb5fbfb8ee2efffa39658d4d28
refs/heads/master
2023-06-07T17:21:48.979240
2021-07-01T07:12:49
2021-07-01T07:12:49
143,122,023
1
0
null
null
null
null
UTF-8
C++
false
false
6,968
hpp
/************************************************************************** This file is part of dgecalib, an effcient camera calibration library. Copyright(C) 2017-2020, Zhilong(Dgelom) Su, all rights reserved. **************************************************************************/ #pragma once #include <type_traits> #include <typeinfo> #ifndef _MSC_VER # include <cxxabi.h> #endif #include <memory> #include <string> #include <cstdlib> #include <sstream> #include <string> #include <mmintrin.h> #include <immintrin.h> #include <iostream> #include <chrono> #include <iomanip> #if defined __BORLANDC__ # include <fastmath.h> #elif defined __cplusplus # include <cmath> #else # include <math.h> #endif #ifdef HAVE_TEGRA_OPTIMIZATION # include "tegra_round.hpp" #endif #ifndef DGE_INLINE #define DGE_INLINE inline #endif #define PROPERTY(_T, name) \ __declspec(property(put = _set_##name, get = _get_##name)) _T name; \ typedef _T _type_##name #define READONLY_PROPERTY(_T, name) \ __declspec(property(get = _get_##name)) _T name;\ typedef _T _type_##name #define WRITEONLY_PROPERTY(_T, name) \ __declspec(property(put = _set_##name)) _T name;\ typedef _T _type_##name #define __property__(_T, name) \ __declspec(property(put = _set_##name, get = _get_##name)) _T name; \ typedef _T _type_##name /*value returned type getter*/ #define __get__(name) inline _type_##name _get_##name() /*copy assigned type setter*/ #define __set__(name) inline void _set_##name(_type_##name name) #define CONST_PROPERTY(TYPE, NAME, EXP) \ __declspec(property(get = _Get_##NAME)) TYPE NAME;\ inline TYPE _Get_##NAME() const noexcept {\ return EXP;\ } namespace dgelom { ///<summary> //@brief Template function to detect the data type //@author Zhilong (Dgelom) Su - May/15/2016 - SUTD //@para Example-- _Ty* ty = nullptr; [_Ty* _Ty] = type_name<decltype(ty)>() ///</summary> template <typename _Ty> DGE_INLINE std::string type_name() noexcept { using ty_nonref = typename std::remove_reference_t<_Ty>; std::unique_ptr<char, void(*)(void*)> uPtr( #ifndef _MSC_VER abi::__cxa_demangle(typeid(ty_nonref).name(), nullptr, nullptr, nullptr), #else nullptr, #endif free); std::string strTyName = (uPtr != nullptr) ? uPtr.get() : typeid(ty_nonref).name(); if constexpr (std::is_const<ty_nonref>::value) return "const " + strTyName; else if constexpr (std::is_volatile<ty_nonref>::value) return "volatile " + strTyName; else if constexpr (std::is_lvalue_reference<_Ty>::value) return strTyName + "&"; else if constexpr (std::is_rvalue_reference<_Ty>::value) return strTyName + "&&"; else return strTyName; }; ///<summary> //@brief: Template function to cvt. number to std::string //@author: Zhilong (Dgelom) Su - Jan.10.2017 @SEU ///</summary> template <typename _Ty> DGE_INLINE std::string strf(_Ty _val) noexcept { std::ostringstream strs; strs << _val; return strs.str(); } template <typename _Ty> DGE_INLINE int round_(_Ty _val) noexcept { #if ((defined _MSC_VER && defined _M_X64) || (defined __x86_64__ \ && defined __SSE2__)) && !defined(__CUDACC__) if constexpr (sizeof(_Ty) == 4) return _val; if constexpr (sizeof(_Ty) == 32) { __m128 t = _mm_set_ss((float)_val); return _mm_cvtss_si32(t); } if constexpr (sizeof(_Ty) == 64) { __m128d t = _mm_set_sd((double)_val); return _mm_cvtsd_si32(t); } #elif (defined _MSC_VER && defined _M_IX86) int t; __asm { fld _val; fistp t; } return t; #elif ((defined _MSC_VER && defined _M_ARM) && defined HAVE_TEGRA_OPTIMIZATION) TEGRA_ROUND_DBL(_val); #else /* it's ok if round does not comply with IEEE754 standard; the tests should allow +/-1 difference when the tested functions use round */ return (int)(_val + (_val >= 0 ? 0.5 : -0.5)); #endif } template<typename _Ty> DGE_INLINE int ceil_(_Ty value) noexcept { #if (defined _MSC_VER && defined _M_X64) && !defined(__CUDACC__) if constexpr (sizeof(_Ty) == 4) return(value); if constexpr (sizeof(_Ty) == 32) { __m128 t = _mm_set_ss((float)value); int i = _mm_cvtss_si32(t); return i + _mm_movemask_ps(_mm_cmplt_ss(_mm_cvtsi32_ss(t, i), t)); } if constexpr (sizeof(_Ty) == 64) { __m128d t = _mm_set_sd(value); int i = _mm_cvtsd_si32(t); return i + _mm_movemask_pd(_mm_cmplt_sd(_mm_cvtsi32_sd(t, i), t)); } #else int i = round_(value); float diff = (float)(i - value); return i + (diff < 0); #endif } template<typename _Ty> DGE_INLINE int floor_(_Ty value) noexcept { #if (defined _MSC_VER && defined _M_X64) && !defined(__CUDACC__) if constexpr (sizeof(_Ty) == 4) return(value); if constexpr (sizeof(_Ty) == 32) { __m128 t = _mm_set_ss((float)value); int i = _mm_cvtss_si32(t); return i - _mm_movemask_ps(_mm_cmplt_ss(_mm_cvtsi32_ss(t, i), t)); } if constexpr (sizeof(_Ty) == 64) { __m128d t = _mm_set_sd(value); int i = _mm_cvtsd_si32(t); return i - _mm_movemask_pd(_mm_cmplt_sd(_mm_cvtsi32_sd(t, i), t)); } #else int i = round_(value); float diff = (float)(value - i); return i - (diff < 0); #endif } template<typename _Inty> static inline /*convert matrix indices to linear index*/ _Inty lidx(const _Inty _r, const _Inty _c, const _Inty _w) { return (_c + _r * _w); } template<typename _Inty> static inline /*convert linear index to matrix indices*/ auto midx(const _Inty _lidx, const _Inty _w) { _Inty r = _lidx / _w; return std::make_tuple(_lidx - r * _w, r); } /* * @Name: _HRC -- High Resolution Clock * @Calling pipeline: _HRC.start -> "target block" -> _HRC_stop -> elapsed_time() * @Copyright(c): Zhilong Su (su-zl@seu.edu.cn) 2017 */ template<typename _Clock = std::chrono::high_resolution_clock> class _HRC final { typedef std::chrono::time_point<std::chrono::steady_clock> time_point; public: _HRC() { } ~_HRC() { } public: // start-timer of high resolution clock __declspec(property(get = _prop_time_getter)) time_point start; // stop-timer of high resolution clock __declspec(property(get = _prop_time_getter)) time_point stop; inline time_point _prop_time_getter() { return _Clock::now(); } // return elapsed time inline double elapsed_time(const time_point& _start) { using namespace std; auto now = _Clock::now(); auto interval = chrono::duration_cast<chrono::nanoseconds>( now - _start).count(); m_time = (double)interval / m_ns2msconst; return m_time; } // output elasped time of runing target represented by _txt inline void elapsed_time(const time_point& _start, const std::string& _txt) { using namespace std; auto now = _Clock::now(); auto interval = chrono::duration_cast<chrono::nanoseconds>( now - _start).count(); m_time = (double)interval / m_ns2msconst; cout << " >> [Timer Message] Elapsed time of " << _txt << setprecision(9) << " " << m_time << "ms" << endl; } private: double m_time; const double m_ns2msconst = 1.0e6; }; }
[ "su-zl@seu.edu.cn" ]
su-zl@seu.edu.cn
8895cad83567be708ba1d3b1490918f360be1200
6724a8351ccb974c4ee1fef0e458c401a8c96daa
/VirtualCreatures/Volumetric_SDL/Source/SceneObjects/VirtualCreatures/Limb.cpp
28f0cf6e8bec3936493fafb571d4fabd1285bbfb
[ "Zlib" ]
permissive
fernicar/EvolvedVirtualCreaturesRepo
73985b000a23b5e18f1909341abd08632e919488
4efaba960c7c56a08faaaeb1f3cae91a9ef1e54e
refs/heads/master
2021-01-11T22:44:36.944115
2017-01-15T13:26:53
2017-01-15T13:26:53
79,027,931
0
0
null
2017-01-15T11:15:59
2017-01-15T11:15:59
null
UTF-8
C++
false
false
29,975
cpp
#include <SceneObjects/VirtualCreatures/Limb.h> #include <SceneObjects/VirtualCreatures/SceneObject_Creature.h> #include <Utilities/UtilFuncs.h> float Limb::s_minInitTimerRate = 0.05f; float Limb::s_maxInitTimerRate = 0.6f; float Limb::s_minInitTimerTime = 0.0f; float Limb::s_maxInitTimerTime = 0.9f; LimbGenes::LimbGenes() { } LimbGenes::~LimbGenes() { } Limb::Limb() : m_pCreature(NULL), m_pCollisionShape(NULL), m_pMotionState(NULL), m_pRigidBody(NULL), m_pJoint(NULL), m_pModel(NULL), m_PID_x(0.7f, 0.1f, 0.5f), m_PID_y(0.7f, 0.1f, 0.5f), m_PID_z(0.7f, 0.1f, 0.5f) { for(unsigned int i = 0; i < s_numMotorOutputs; i++) m_motorOutputs[i] = 0.0f; } Limb::~Limb() { if(m_pCreature != NULL) { if(PhysicsWorldAlive()) { if(m_pJoint != NULL) GetPhysicsWorld()->m_pDynamicsWorld->removeConstraint(m_pJoint); GetPhysicsWorld()->m_pDynamicsWorld->removeRigidBody(m_pRigidBody); } if(m_pJoint != NULL) delete m_pJoint; delete m_pCollisionShape; delete m_pMotionState; delete m_pRigidBody; } } void Limb::Create(class SceneObject_Creature* pCreature, Limb* pParent, LimbGenes &genes, int flipAxis) // flipAxis = -1 makes it not flip it { assert(m_pCreature == NULL); // Not already created // ----------------------------------------- Copy gene data ----------------------------------------- // Physics related data m_pCreature = pCreature; m_pParent = pParent; assert(m_pParent != NULL); m_limbLevel = m_pParent->m_limbLevel + 1; m_bendLimit = genes.m_bendLimit; m_twistLimit = genes.m_twistLimit; m_strength = genes.m_strength; m_halfDims = genes.m_dims / 2.0f; // ------------------------------------------ Physics ------------------------------------------ m_pCollisionShape = new btBoxShape(bt(m_halfDims)); Vec3f attachmentPositionOnThis(genes.m_relativeAttachmentPositionOnThis * m_halfDims); Vec3f attachmentPositionOnParent(genes.m_relativeAttachmentPositionOnParent * m_pParent->m_halfDims); Quaternion rot(cons(m_pParent->m_pRigidBody->getWorldTransform().getRotation()) * genes.m_relativeRotation); m_reflected = flipAxis != -1; switch(flipAxis) { case 0: // x attachmentPositionOnThis.x *= -1; attachmentPositionOnParent.x *= -1; rot.y *= -1; rot.z *= -1; break; case 1: // y attachmentPositionOnThis.y *= -1; attachmentPositionOnParent.y *= -1; rot.x *= -1; rot.z *= -1; break; case 2: // z attachmentPositionOnThis.z *= -1; attachmentPositionOnParent.z *= -1; rot.x *= -1; rot.y *= -1; break; } rot.NormalizeThis(); assert(m_pParent->m_pRigidBody != NULL); Vec3f boxCenterPos(cons(m_pParent->m_pRigidBody->getWorldTransform().getOrigin()) + cons(m_pParent->m_pRigidBody->getWorldTransform().getRotation()) * attachmentPositionOnParent + rot * (Vec3f(m_halfDims.x, 0.0f, 0.0f) + attachmentPositionOnThis)); m_pMotionState = new btDefaultMotionState(btTransform(bt(genes.m_relativeRotation).normalized(), bt(boxCenterPos))); const float mass = genes.m_density * genes.m_dims.Magnitude(); btVector3 intertia; m_pCollisionShape->calculateLocalInertia(mass, intertia); btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass, m_pMotionState, m_pCollisionShape, intertia); rigidBodyCI.m_friction = genes.m_friction; assert(m_pRigidBody == NULL); m_pRigidBody = new btRigidBody(rigidBodyCI); #ifdef SELF_COLLISION unsigned short group = Pow2(m_limbLevel); unsigned short mask = 0xffff ^ (Pow2(m_pParent->m_limbLevel) | group | Pow2(m_limbLevel + 1)); // Mask out parent and child #else unsigned short group = 0x8000; unsigned short mask = 0x7fff; #endif GetPhysicsWorld()->m_pDynamicsWorld->addRigidBody(m_pRigidBody, group, mask); // If it has a parent, create a joint btTransform parentFrame; parentFrame.setIdentity(); parentFrame.setOrigin(bt(attachmentPositionOnParent)); parentFrame.setRotation(bt(genes.m_relativeRotation)); btTransform thisFrame; thisFrame.setIdentity(); thisFrame.setOrigin(bt(genes.m_relativeAttachmentPositionOnThis * m_halfDims)); // Create joint m_pJoint = new btGeneric6DofConstraint(*m_pParent->m_pRigidBody, *m_pRigidBody, parentFrame, thisFrame, true); // Limit angles //m_pJoint->setAngularLowerLimit(btVector3(-genes.m_bendLimit, -genes.m_bendLimit, -genes.m_twistLimit)); //m_pJoint->setAngularUpperLimit(btVector3(genes.m_bendLimit, genes.m_bendLimit, genes.m_twistLimit)); m_pJoint->setLimit(3, -genes.m_bendLimit, genes.m_bendLimit); m_pJoint->setLimit(4, -genes.m_bendLimit, genes.m_bendLimit); m_pJoint->setLimit(5, -genes.m_twistLimit, genes.m_twistLimit); const float maxLimitForce = genes.m_strength * 2.0f; // Larger number than limb strength const float limitSoftness = 0.1f; const float damping = 0.5f; // Limit motor angles too (not really necessary?) m_pJoint->getRotationalLimitMotor(0)->m_enableMotor = true; m_pJoint->getRotationalLimitMotor(0)->m_loLimit = -genes.m_bendLimit; m_pJoint->getRotationalLimitMotor(0)->m_hiLimit = genes.m_bendLimit; m_pJoint->getRotationalLimitMotor(0)->m_maxLimitForce = maxLimitForce; m_pJoint->getRotationalLimitMotor(0)->m_limitSoftness = limitSoftness; m_pJoint->getRotationalLimitMotor(0)->m_damping = damping; m_pJoint->getRotationalLimitMotor(1)->m_enableMotor = true; m_pJoint->getRotationalLimitMotor(1)->m_loLimit = -genes.m_bendLimit; m_pJoint->getRotationalLimitMotor(1)->m_hiLimit = genes.m_bendLimit; m_pJoint->getRotationalLimitMotor(1)->m_maxLimitForce = maxLimitForce; m_pJoint->getRotationalLimitMotor(1)->m_limitSoftness = limitSoftness; m_pJoint->getRotationalLimitMotor(1)->m_damping = damping; m_pJoint->getRotationalLimitMotor(2)->m_enableMotor = true; m_pJoint->getRotationalLimitMotor(2)->m_loLimit = -genes.m_twistLimit; m_pJoint->getRotationalLimitMotor(2)->m_hiLimit = genes.m_twistLimit; m_pJoint->getRotationalLimitMotor(2)->m_maxLimitForce = maxLimitForce; m_pJoint->getRotationalLimitMotor(2)->m_limitSoftness = limitSoftness; m_pJoint->getRotationalLimitMotor(2)->m_damping = damping; GetPhysicsWorld()->m_pDynamicsWorld->addConstraint(m_pJoint); // ------------------------------------------ Neural Network ------------------------------------------ CreateNet_SubNet_FeedForward(genes); // --------------------------------------------- Graphics --------------------------------------------- // Choose model based on parameters if(m_pContactSensor.get() != NULL) m_pModel = m_pCreature->m_pLimbModel_Sensor; else m_pModel = m_pCreature->m_pLimbModel_Other; } void Limb::Create_Root(class SceneObject_Creature* pCreature, const btTransform &baseTransform, LimbGenes &genes, unsigned int numOutputs) { assert(m_pCreature == NULL); // Not already created // ----------------------------------------- Copy gene data ----------------------------------------- // Physics related data m_pCreature = pCreature; m_pParent = NULL; m_limbLevel = 2; m_bendLimit = genes.m_bendLimit; m_twistLimit = genes.m_twistLimit; m_strength = genes.m_strength; m_halfDims = genes.m_dims / 2.0f; // ------------------------------------------ Physics ------------------------------------------ m_pCollisionShape = new btBoxShape(bt(m_halfDims)); Vec3f attachmentPositionOnThis(genes.m_relativeAttachmentPositionOnThis * m_halfDims); Vec3f attachmentPositionOnParent(genes.m_relativeAttachmentPositionOnParent * m_halfDims); // Randomly init these for now m_pMotionState = new btDefaultMotionState(btTransform(bt(genes.m_relativeRotation).normalized(), baseTransform.getOrigin())); const float mass = genes.m_density * genes.m_dims.Magnitude(); btVector3 intertia; m_pCollisionShape->calculateLocalInertia(mass, intertia); btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass, m_pMotionState, m_pCollisionShape, intertia); rigidBodyCI.m_friction = genes.m_friction; assert(m_pRigidBody == NULL); m_pRigidBody = new btRigidBody(rigidBodyCI); #ifdef SELF_COLLISION unsigned short group = 1; unsigned short mask = 0xffff ^ (Pow2(m_limbLevel + 1) | group); #else unsigned short group = 0x8000; unsigned short mask = 0x7fff; #endif GetPhysicsWorld()->m_pDynamicsWorld->addRigidBody(m_pRigidBody, group, mask); // ------------------------------------------ Neural Network ------------------------------------------ CreateNet_MainBrain_FeedForward(genes, numOutputs); // --------------------------------------------- Graphics --------------------------------------------- // Choose model based on parameters if(m_pContactSensor != NULL) m_pModel = m_pCreature->m_pLimbModel_Sensor; else m_pModel = m_pCreature->m_pLimbModel_Other; } void Limb::CreateNet_SubNet_FeedForward(LimbGenes &genes) { assert(m_pParent != NULL); m_numOutputs = s_numMotorOutputs; m_neurons.resize(genes.m_numHiddenLayers * genes.m_numNeuronsPerHiddenLayer + m_numOutputs); // Skip first hidden layer for now unsigned int ni = genes.m_numNeuronsPerHiddenLayer; for(unsigned int l = 1; l < genes.m_numHiddenLayers; l++) { const unsigned int startNi = ni - 1; for(unsigned int i = 0; i < genes.m_numNeuronsPerHiddenLayer; i++, ni++) { // Create neuron if it does not exist if(ni >= genes.m_neuronData.size()) { while(ni >= genes.m_neuronData.size()) { LimbGenes::Neuron_Data data; // Random assignment data.m_threshold = Randf(); for(unsigned int j = 0; j < genes.m_numNeuronsPerHiddenLayer; j++) data.m_weights.push_back(Randf(Neuron::s_minRandomWeight, Neuron::s_maxRandomWeight)); genes.m_neuronData.push_back(data); } } else if(genes.m_neuronData[ni].m_weights.size() != genes.m_numNeuronsPerHiddenLayer) // Remove/Add Random inputs if size mismatch { const unsigned int numWeights = genes.m_neuronData[ni].m_weights.size(); // Add random weights if there are not enough if(numWeights < genes.m_numNeuronsPerHiddenLayer) { const unsigned int difference = genes.m_numNeuronsPerHiddenLayer - numWeights; for(unsigned int i = 0; i < difference; i++) genes.m_neuronData[ni].m_weights.push_back(Randf(Neuron::s_minRandomWeight, Neuron::s_maxRandomWeight)); } else genes.m_neuronData[ni].m_weights.resize(genes.m_numNeuronsPerHiddenLayer); } // Create weight array for neuron to take over const unsigned int numWeights = genes.m_neuronData[ni].m_weights.size(); Neuron::NeuronInputAndWeight* pNeuronInputs = new Neuron::NeuronInputAndWeight[numWeights]; for(unsigned int j = 0; j < numWeights; j++) { pNeuronInputs[j].m_pInput = &m_neurons[startNi - j]; pNeuronInputs[j].m_weight = genes.m_neuronData[ni].m_weights[j]; } m_neurons[ni].SetInputs(numWeights, pNeuronInputs); } } // Outputs unsigned int startNi = ni - 1; for(unsigned int i = 0; i < s_numMotorOutputs; i++, ni++) { // Create neuron if it does not exist if(ni >= genes.m_neuronData.size()) { while(ni >= genes.m_neuronData.size()) { LimbGenes::Neuron_Data data; // Random assignment data.m_threshold = Randf(); for(unsigned int j = 0; j < genes.m_numNeuronsPerHiddenLayer; j++) data.m_weights.push_back(Randf(Neuron::s_minRandomWeight, Neuron::s_maxRandomWeight)); genes.m_neuronData.push_back(data); } } else if(genes.m_neuronData[ni].m_weights.size() != genes.m_numNeuronsPerHiddenLayer) // Remove/Add Random inputs if size mismatch { const unsigned int numWeights = genes.m_neuronData[ni].m_weights.size(); // Add random weights if there are not enough if(numWeights < genes.m_numNeuronsPerHiddenLayer) { const unsigned int difference = genes.m_numNeuronsPerHiddenLayer - numWeights; for(unsigned int j = 0; j < difference; j++) genes.m_neuronData[ni].m_weights.push_back(Randf(Neuron::s_minRandomWeight, Neuron::s_maxRandomWeight)); } else genes.m_neuronData[ni].m_weights.resize(genes.m_numNeuronsPerHiddenLayer); } // Create weight array for neuron to take over const unsigned int numWeights = genes.m_neuronData[ni].m_weights.size(); Neuron::NeuronInputAndWeight* pNeuronInputs = new Neuron::NeuronInputAndWeight[numWeights]; for(unsigned int j = 0; j < numWeights; j++) { pNeuronInputs[j].m_pInput = &m_neurons[startNi - j]; pNeuronInputs[j].m_weight = genes.m_neuronData[ni].m_weights[j]; } m_neurons[ni].SetInputs(numWeights, pNeuronInputs); } // Trim away unused neurons if(ni < genes.m_neuronData.size() - 1) genes.m_neuronData.resize(ni + 1); } void Limb::CreateNet_MainBrain_FeedForward(LimbGenes &genes, unsigned int numOutputs) { assert(m_pParent == NULL); m_numOutputs = numOutputs; m_neurons.resize(genes.m_numHiddenLayers * genes.m_numNeuronsPerHiddenLayer + m_numOutputs); // Skip first hidden layer for now unsigned int ni = genes.m_numNeuronsPerHiddenLayer; // Other hidden layers for(unsigned int l = 1; l < genes.m_numHiddenLayers; l++) { const unsigned int startNi = ni - 1; for(unsigned int i = 0; i < genes.m_numNeuronsPerHiddenLayer; i++, ni++) { // Create neuron if it does not exist if(ni >= genes.m_neuronData.size()) { while(ni >= genes.m_neuronData.size()) { LimbGenes::Neuron_Data data; // Random assignment data.m_threshold = Randf(); for(unsigned int j = 0; j < genes.m_numNeuronsPerHiddenLayer; j++) data.m_weights.push_back(Randf(Neuron::s_minRandomWeight, Neuron::s_maxRandomWeight)); genes.m_neuronData.push_back(data); } } else if(genes.m_neuronData[ni].m_weights.size() != genes.m_numNeuronsPerHiddenLayer) // Remove/Add Random inputs if size mismatch { const unsigned int numWeights = genes.m_neuronData[ni].m_weights.size(); // Add random weights if there are not enough if(numWeights < genes.m_numNeuronsPerHiddenLayer) { const unsigned int difference = genes.m_numNeuronsPerHiddenLayer - numWeights; for(unsigned int j = 0; j < difference; j++) genes.m_neuronData[ni].m_weights.push_back(Randf(Neuron::s_minRandomWeight, Neuron::s_maxRandomWeight)); } else genes.m_neuronData[ni].m_weights.resize(genes.m_numNeuronsPerHiddenLayer); } // Create weight array for neuron to take over const unsigned int numWeights = genes.m_neuronData[ni].m_weights.size(); Neuron::NeuronInputAndWeight* pNeuronInputs = new Neuron::NeuronInputAndWeight[numWeights]; for(unsigned int j = 0; j < numWeights; j++) { pNeuronInputs[j].m_pInput = &m_neurons[startNi - j]; pNeuronInputs[j].m_weight = genes.m_neuronData[ni].m_weights[j]; } m_neurons[ni].SetInputs(numWeights, pNeuronInputs); } } // Outputs unsigned int startNi = ni - 1; for(unsigned int i = 0; i < m_numOutputs; i++, ni++) { // Create neuron if it does not exist if(ni >= genes.m_neuronData.size()) { while(ni >= genes.m_neuronData.size()) { LimbGenes::Neuron_Data data; // Random assignment data.m_threshold = Randf(); for(unsigned int j = 0; j < genes.m_numNeuronsPerHiddenLayer; j++) data.m_weights.push_back(Randf(Neuron::s_minRandomWeight, Neuron::s_maxRandomWeight)); genes.m_neuronData.push_back(data); } } else if(genes.m_neuronData[ni].m_weights.size() != genes.m_numNeuronsPerHiddenLayer) // Remove/Add Random inputs if size mismatch { const unsigned int numWeights = genes.m_neuronData[ni].m_weights.size(); // Add random weights if there are not enough if(numWeights < genes.m_numNeuronsPerHiddenLayer) { const unsigned int difference = genes.m_numNeuronsPerHiddenLayer - numWeights; for(unsigned int j = 0; j < difference; j++) genes.m_neuronData[ni].m_weights.push_back(Randf(Neuron::s_minRandomWeight, Neuron::s_maxRandomWeight)); } else genes.m_neuronData[ni].m_weights.resize(genes.m_numNeuronsPerHiddenLayer); } // Create weight array for neuron to take over const unsigned int numWeights = genes.m_neuronData[ni].m_weights.size(); Neuron::NeuronInputAndWeight* pNeuronInputs = new Neuron::NeuronInputAndWeight[numWeights]; for(unsigned int j = 0; j < numWeights; j++) { pNeuronInputs[j].m_pInput = &m_neurons[startNi - j]; pNeuronInputs[j].m_weight = genes.m_neuronData[ni].m_weights[j]; } m_neurons[ni].SetInputs(numWeights, pNeuronInputs); } // Trim away unused neurons if(ni < genes.m_neuronData.size() - 1) genes.m_neuronData.resize(ni + 1); } void Limb::SetInputs_SubNet(LimbGenes &genes) { // All inputs/sensors list std::vector<NeuronInput*> inputs; // Create/Append inputs/sensors to list for(unsigned int i = 0; i < s_numMotorInputs; i++) inputs.push_back(&m_motorInputs[i]); if(genes.m_hasContactSensor) { m_pContactSensor.reset(new Neuron_Sensor_Contact()); m_pContactSensor->m_pLimb = this; m_pContactSensor->Create(); inputs.push_back(m_pContactSensor.get()); } m_timers.reserve(genes.m_numTimerSensors); for(unsigned int i = 0; i < genes.m_numTimerSensors; i++) { if(m_timers.size() <= i) { LimbGenes::Sensor_Timer_Data newTimer; newTimer.m_initTime = Randf(s_minInitTimerTime, s_maxInitTimerTime); newTimer.m_rate = Randf(s_minInitTimerRate, s_maxInitTimerRate); genes.m_timerSensorData.push_back(newTimer); m_timers.push_back(Neuron_Sensor_Timer()); } m_timers[i].m_timer = genes.m_timerSensorData[i].m_initTime; m_timers[i].m_rate = genes.m_timerSensorData[i].m_rate; m_timers[i].m_pLimb = this; m_timers[i].Create(); inputs.push_back(&m_timers[i]); } // Trim away unused timer data if(genes.m_numTimerSensors < genes.m_timerSensorData.size()) genes.m_timerSensorData.resize(genes.m_numTimerSensors); // Add previous limb inputs for(unsigned int i = 0, size = genes.m_parentLimbInputNeurons.size(); i < size; i++) { if(genes.m_parentLimbInputNeurons[i] >= static_cast<signed>(m_pParent->m_numOutputs)) genes.m_parentLimbInputNeurons[i] = rand() % m_pParent->m_numOutputs; inputs.push_back(&m_pParent->m_neurons[m_pParent->m_numOutputs - genes.m_parentLimbInputNeurons[i] - 1]); } // Add child limb inputs if(!m_children.empty()) for(unsigned int i = 0, size = genes.m_childLimbInputNeurons.size(); i < size; i++) { if(genes.m_childLimbInputNeurons[i].m_childIndex >= static_cast<signed>(m_children.size())) genes.m_childLimbInputNeurons[i].m_childIndex = rand() % m_children.size(); Limb* pChild = m_children[genes.m_childLimbInputNeurons[i].m_childIndex]; if(genes.m_childLimbInputNeurons[i].m_outputIndex >= static_cast<signed>(pChild->m_numOutputs)) genes.m_childLimbInputNeurons[i].m_outputIndex = rand() % pChild->m_numOutputs; inputs.push_back(&pChild->m_neurons[pChild->GetNumNeurons() - genes.m_childLimbInputNeurons[i].m_outputIndex - 1]); } // Add main brain inputs neurons for(unsigned int i = 0, size = genes.m_mainBrainInputNeurons.size(); i < size; i++) { if(genes.m_mainBrainInputNeurons[i] >= static_cast<signed>(m_pCreature->m_pRoot->m_numOutputs)) genes.m_mainBrainInputNeurons[i] = rand() % m_pCreature->m_pRoot->m_numOutputs; inputs.push_back(&m_pCreature->m_pRoot->m_neurons[m_pCreature->m_pRoot->m_numOutputs - genes.m_mainBrainInputNeurons[i] - 1]); } const unsigned int numInputs = inputs.size(); // First hidden layer for(unsigned int ni = 0; ni < genes.m_numNeuronsPerHiddenLayer; ni++) { // Create neuron if it does not exist if(ni >= genes.m_neuronData.size()) { while(ni >= genes.m_neuronData.size()) { LimbGenes::Neuron_Data data; // Random assignment data.m_threshold = Randf(); for(unsigned int j = 0; j < numInputs; j++) data.m_weights.push_back(Randf(Neuron::s_minRandomWeight, Neuron::s_maxRandomWeight)); genes.m_neuronData.push_back(data); } } else if(genes.m_neuronData[ni].m_weights.size() != numInputs) // Remove/Add Random inputs if size mismatch { const unsigned int numWeights = genes.m_neuronData[ni].m_weights.size(); // Add random weights if there are not enough if(numWeights < numInputs) { const unsigned int difference = numInputs - numWeights; for(unsigned int j = 0; j < difference; j++) genes.m_neuronData[ni].m_weights.push_back(Randf(Neuron::s_minRandomWeight, Neuron::s_maxRandomWeight)); } else genes.m_neuronData[ni].m_weights.resize(numInputs); } // Create weight array for neuron to take over const unsigned int numWeights = genes.m_neuronData[ni].m_weights.size(); Neuron::NeuronInputAndWeight* pNeuronInputs = new Neuron::NeuronInputAndWeight[numWeights]; for(unsigned int j = 0; j < numWeights; j++) { pNeuronInputs[j].m_pInput = inputs[j]; pNeuronInputs[j].m_weight = genes.m_neuronData[ni].m_weights[j]; } m_neurons[ni].SetInputs(numWeights, pNeuronInputs); } } void Limb::SetInputs_Root(LimbGenes &genes, const std::vector<NeuronInput*> &additionalInputs) { std::vector<NeuronInput*> inputs(additionalInputs); // Create/Append inputs/sensors to list if(genes.m_hasContactSensor) { m_pContactSensor.reset(new Neuron_Sensor_Contact()); m_pContactSensor->m_pLimb = this; m_pContactSensor->Create(); inputs.push_back(m_pContactSensor.get()); } m_timers.reserve(genes.m_numTimerSensors); for(unsigned int i = 0; i < genes.m_numTimerSensors; i++) { if(m_timers.size() <= i) { LimbGenes::Sensor_Timer_Data newTimer; newTimer.m_initTime = Randf(s_minInitTimerTime, s_maxInitTimerTime); newTimer.m_rate = Randf(s_minInitTimerRate, s_maxInitTimerRate); genes.m_timerSensorData.push_back(newTimer); m_timers.push_back(Neuron_Sensor_Timer()); } m_timers[i].m_timer = genes.m_timerSensorData[i].m_initTime; m_timers[i].m_rate = genes.m_timerSensorData[i].m_rate; m_timers[i].m_pLimb = this; m_timers[i].Create(); inputs.push_back(&m_timers[i]); } // Trim away unused timer data if(genes.m_numTimerSensors < genes.m_timerSensorData.size()) genes.m_timerSensorData.resize(genes.m_numTimerSensors); // Add child limb inputs if(!m_children.empty()) for(unsigned int i = 0, size = genes.m_childLimbInputNeurons.size(); i < size; i++) { if(genes.m_childLimbInputNeurons[i].m_childIndex >= static_cast<signed>(m_children.size())) genes.m_childLimbInputNeurons[i].m_childIndex = rand() % m_children.size(); Limb* pChild = m_children[genes.m_childLimbInputNeurons[i].m_childIndex]; if(genes.m_childLimbInputNeurons[i].m_outputIndex >= static_cast<signed>(pChild->m_numOutputs)) genes.m_childLimbInputNeurons[i].m_outputIndex = rand() % pChild->m_numOutputs; inputs.push_back(&pChild->m_neurons[pChild->GetNumNeurons() - genes.m_childLimbInputNeurons[i].m_outputIndex - 1]); } // Add outputs as recurrent for(unsigned int i = 0; i < m_numOutputs; i++) inputs.push_back(&m_neurons[GetNumNeurons() - i - 1]); const unsigned int numInputs = inputs.size(); // First hidden layer for(unsigned int ni = 0; ni < genes.m_numNeuronsPerHiddenLayer; ni++) { // Create neuron if it does not exist if(ni >= genes.m_neuronData.size()) { while(ni >= genes.m_neuronData.size()) { LimbGenes::Neuron_Data data; // Random assignment data.m_threshold = Randf(); for(unsigned int j = 0; j < numInputs; j++) data.m_weights.push_back(Randf(Neuron::s_minRandomWeight, Neuron::s_maxRandomWeight)); genes.m_neuronData.push_back(data); } } else if(genes.m_neuronData[ni].m_weights.size() != numInputs) // Remove/Add Random inputs if size mismatch { const unsigned int numWeights = genes.m_neuronData[ni].m_weights.size(); // Add random weights if there are not enough if(numWeights < numInputs) { const unsigned int difference = numInputs - numWeights; for(unsigned int j = 0; j < difference; j++) genes.m_neuronData[ni].m_weights.push_back(Randf(Neuron::s_minRandomWeight, Neuron::s_maxRandomWeight)); } else genes.m_neuronData[ni].m_weights.resize(numInputs); } // Create weight array for neuron to take over const unsigned int numWeights = genes.m_neuronData[ni].m_weights.size(); Neuron::NeuronInputAndWeight* pNeuronInputs = new Neuron::NeuronInputAndWeight[numWeights]; for(unsigned int j = 0; j < numWeights; j++) { pNeuronInputs[j].m_pInput = inputs[j]; pNeuronInputs[j].m_weight = genes.m_neuronData[ni].m_weights[j]; } m_neurons[ni].SetInputs(numWeights, pNeuronInputs); } } void Limb::PhysicsUpdate() { m_pMotionState->getWorldTransform(m_physicsTransform); for(unsigned int i = 0, numTimers = m_timers.size(); i < numTimers; i++) m_timers[i].PhysicsUpdate(); if(m_pContactSensor.get() != NULL) m_pContactSensor->PhysicsUpdate(); if(m_pJoint != NULL) { if(m_reflected) { m_motorInputs[0].m_output = -m_pJoint->getAngle(0) / pif_times_2; m_motorInputs[1].m_output = -m_pJoint->getAngle(1) / pif_times_2; m_motorInputs[2].m_output = -m_pJoint->getAngle(2) / pif_times_2; } else { m_motorInputs[0].m_output = m_pJoint->getAngle(0) / pif_times_2; m_motorInputs[1].m_output = m_pJoint->getAngle(1) / pif_times_2; m_motorInputs[2].m_output = m_pJoint->getAngle(2) / pif_times_2; } /*m_motorInputs[0].m_output = m_pJoint->getRotationalLimitMotor(0)->m_currentPosition / pif_times_2; m_motorInputs[1].m_output = m_pJoint->getRotationalLimitMotor(1)->m_currentPosition / pif_times_2; m_motorInputs[2].m_output = m_pJoint->getRotationalLimitMotor(2)->m_currentPosition / pif_times_2;*/ // Get joint angle inputs /*btTransform parentLocal(m_pParent->m_pRigidBody->getWorldTransform().inverse() * m_pRigidBody->getWorldTransform()); Vec3f euler(cons(parentLocal.getRotation()).GetEulerAngles()); m_motorInputs[0].m_output = euler.x / pif_times_2; m_motorInputs[1].m_output = euler.y / pif_times_2; m_motorInputs[2].m_output = euler.z / pif_times_2;*/ } } void Limb::StartMotorAveraging() { // Init to 0 for(unsigned int i = 0; i < s_numMotorOutputs; i++) m_motorOutputs[i] = 0.0f; } void Limb::NeuronUpdate(float dopamine) { if(dopamine == 0.0f) { for(unsigned int i = 0, numNeurons = m_neurons.size(); i < numNeurons; i++) m_neurons[i].Update(); } else { for(unsigned int i = 0, numNeurons = m_neurons.size(); i < numNeurons; i++) m_neurons[i].Update_Reinforce(dopamine); } } void Limb::AddMotorAverages(float weighting) { // Add outputs to averages const unsigned int numNeurons = m_neurons.size(); assert(numNeurons >= s_numMotorOutputs); for(unsigned int i = 0; i < s_numMotorOutputs; i++) m_motorOutputs[i] += NeuronInput::GetFireRateValue(m_neurons[numNeurons - i - 1].GetTimeSinceLastFire()) * weighting; } void Limb::MotorUpdate() { if(m_pJoint == NULL) return; const unsigned int numNeurons = GetNumNeurons(); assert(numNeurons >= s_numMotorOutputs); assert(s_numMotorOutputs == 14); const float maxVelocity = 0.0f; // MAXIMUM // Last s_numMotorOutputs neurons are outputs // Get desired angles float dax, day, daz; if(m_reflected) { dax = -((m_motorOutputs[0] + m_motorOutputs[1] - (m_motorOutputs[2] + m_motorOutputs[3])) / 2.0f) * m_bendLimit; day = -((m_motorOutputs[4] + m_motorOutputs[5] - (m_motorOutputs[6] + m_motorOutputs[7])) / 2.0f) * m_bendLimit; daz = -((m_motorOutputs[8] + m_motorOutputs[9] - (m_motorOutputs[10] + m_motorOutputs[11])) / 2.0f) * m_twistLimit; } else { dax = ((m_motorOutputs[0] + m_motorOutputs[1] - (m_motorOutputs[2] + m_motorOutputs[3])) / 2.0f) * m_bendLimit; day = ((m_motorOutputs[4] + m_motorOutputs[5] - (m_motorOutputs[6] + m_motorOutputs[7])) / 2.0f) * m_bendLimit; daz = ((m_motorOutputs[8] + m_motorOutputs[9] - (m_motorOutputs[10] + m_motorOutputs[11])) / 2.0f) * m_twistLimit; } float maxStrength = m_strength * (m_motorOutputs[12] + m_motorOutputs[13]) / 2.0f; // Max strength (force) // Update PID's m_PID_x.m_desiredValue = 0.0f;//dax; m_PID_y.m_desiredValue = 0.0f;//day; m_PID_z.m_desiredValue = 0.0f;//daz; m_PID_x.Update(m_pJoint->getAngle(0) / m_bendLimit, m_pCreature->GetScene()->m_frameTimer.GetTimeMultiplier()); m_PID_y.Update(m_pJoint->getAngle(1) / m_bendLimit, m_pCreature->GetScene()->m_frameTimer.GetTimeMultiplier()); m_PID_z.Update(m_pJoint->getAngle(2) / m_twistLimit, m_pCreature->GetScene()->m_frameTimer.GetTimeMultiplier()); // X if(m_PID_x.m_output < 0.0f) { m_pJoint->getRotationalLimitMotor(0)->m_targetVelocity = -maxVelocity; m_pJoint->getRotationalLimitMotor(0)->m_maxMotorForce = Clamp(absf(m_PID_x.m_output), 0.0f, maxStrength); } else { m_pJoint->getRotationalLimitMotor(0)->m_targetVelocity = maxVelocity; m_pJoint->getRotationalLimitMotor(0)->m_maxMotorForce = Clamp(absf(m_PID_x.m_output), 0.0f, maxStrength); } // Y if(m_PID_y.m_output < 0.0f) { m_pJoint->getRotationalLimitMotor(1)->m_targetVelocity = -maxVelocity; m_pJoint->getRotationalLimitMotor(1)->m_maxMotorForce = Clamp(absf(m_PID_y.m_output), 0.0f, maxStrength); } else { m_pJoint->getRotationalLimitMotor(1)->m_targetVelocity = maxVelocity; m_pJoint->getRotationalLimitMotor(1)->m_maxMotorForce = Clamp(absf(m_PID_y.m_output), 0.0f, maxStrength); } // Z if(m_PID_z.m_output < 0.0f) { m_pJoint->getRotationalLimitMotor(2)->m_targetVelocity = -maxVelocity; m_pJoint->getRotationalLimitMotor(2)->m_maxMotorForce = Clamp(absf(m_PID_z.m_output), 0.0f, maxStrength); } else { m_pJoint->getRotationalLimitMotor(2)->m_targetVelocity = maxVelocity; m_pJoint->getRotationalLimitMotor(2)->m_maxMotorForce = Clamp(absf(m_PID_z.m_output), 0.0f, maxStrength); } //std::cout << x << " " << y << " " << z << " " << strength << std::endl; } void Limb::Render() { assert(m_pModel != NULL); m_pCreature->GetScene()->SetWorldMatrix(Matrix4x4f::IdentityMatrix()); Matrix4x4f glTransform; m_physicsTransform.getOpenGLMatrix(glTransform.m_elements); glTransform *= Matrix4x4f::ScaleMatrix(m_halfDims); m_pModel->Render(glTransform); } bool Limb::PhysicsWorldAlive() const { return m_pCreature->m_physicsWorldTracker.ReferenceAlive(); } SceneObject_PhysicsWorld* Limb::GetPhysicsWorld() const { assert(m_pCreature != NULL); return m_pCreature->m_pPhysicsWorld; }
[ "nullpointer222464@gmail.com" ]
nullpointer222464@gmail.com
3fb9dd6ce18d340f67abae383f0819c3857aa5a9
bb82a5f977bef455714c16e24e2d8254e2d0faa5
/tests/src/probable_stuck_events_manager/src/test.cpp
33423ccef38371ee9bb3ee1763c49db12ba409f6
[ "Unlicense" ]
permissive
pqrs-org/Karabiner-Elements
4ae307d82f8b67547c161c7d46d2083a0fd07630
d05057d7c769e2ff35638282e888a6d5eca566be
refs/heads/main
2023-09-01T03:11:08.474417
2023-09-01T00:44:19
2023-09-01T00:44:19
63,037,806
8,197
389
Unlicense
2023-09-01T00:11:00
2016-07-11T04:57:55
C++
UTF-8
C++
false
false
12,051
cpp
#include "probable_stuck_events_manager.hpp" #include <boost/ut.hpp> int main(void) { using namespace boost::ut; using namespace boost::ut::literals; "probable_stuck_events_manager"_test = [] { krbn::probable_stuck_events_manager m; // ---------------------------------------- // key_down, key_up expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a), krbn::event_type::key_down, krbn::absolute_time_point(1000), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a), krbn::event_type::key_up, krbn::absolute_time_point(1010), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); // ---------------------------------------- // key_up, key_down, key_up, key_down, key_up expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_b), krbn::event_type::key_up, krbn::absolute_time_point(1100), krbn::device_state::grabbed) == true); expect(m.find_probable_stuck_event() == krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_b)); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_b), krbn::event_type::key_down, krbn::absolute_time_point(1110), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_b)); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_b), krbn::event_type::key_up, krbn::absolute_time_point(1120), krbn::device_state::grabbed) == true); expect(m.find_probable_stuck_event() == std::nullopt); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_b), krbn::event_type::key_down, krbn::absolute_time_point(1130), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_b), krbn::event_type::key_up, krbn::absolute_time_point(1140), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); // ---------------------------------------- // ignore old event expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_c), krbn::event_type::key_up, krbn::absolute_time_point(900), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_c), krbn::event_type::key_up, krbn::absolute_time_point(1200), krbn::device_state::grabbed) == true); expect(m.find_probable_stuck_event() == krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_c)); // ---------------------------------------- // clear m.clear(); expect(m.find_probable_stuck_event() == std::nullopt); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a), krbn::event_type::key_up, krbn::absolute_time_point(500), krbn::device_state::grabbed) == true); expect(m.find_probable_stuck_event() == krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a)); }; "probable_stuck_events_manager key_down is dropped"_test = [] { krbn::probable_stuck_events_manager m; // ---------------------------------------- // key_down, key_up, key_up expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a), krbn::event_type::key_down, krbn::absolute_time_point(1000), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a), krbn::event_type::key_up, krbn::absolute_time_point(1010), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a), krbn::event_type::key_up, krbn::absolute_time_point(1020), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); }; "probable_stuck_events_manager time_stamp rewind"_test = [] { // // key_down, key_up, key_up (normal time_stamp) // { krbn::probable_stuck_events_manager m; expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a), krbn::event_type::key_down, krbn::absolute_time_point(1000), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_b), krbn::event_type::key_up, krbn::absolute_time_point(1010), krbn::device_state::grabbed) == true); expect(m.find_probable_stuck_event() == krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_b)); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_c), krbn::event_type::key_up, krbn::absolute_time_point(1020), krbn::device_state::grabbed) == true); expect(m.find_probable_stuck_event() == krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_b)); } // // key_down, key_up, key_up (rewind time_stamp) // { krbn::probable_stuck_events_manager m; expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a), krbn::event_type::key_down, krbn::absolute_time_point(1000), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_b), krbn::event_type::key_up, krbn::absolute_time_point(910), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_c), krbn::event_type::key_up, krbn::absolute_time_point(920), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); } }; "probable_stuck_events_manager key_up only"_test = [] { // // key_up, key_up, key_up // { krbn::probable_stuck_events_manager m; expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a), krbn::event_type::key_up, krbn::absolute_time_point(1000), krbn::device_state::grabbed) == true); expect(m.find_probable_stuck_event() == krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a)); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a), krbn::event_type::key_up, krbn::absolute_time_point(1010), krbn::device_state::grabbed) == true); expect(m.find_probable_stuck_event() == std::nullopt); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a), krbn::event_type::key_up, krbn::absolute_time_point(1020), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); m.clear(); expect(m.update(krbn::momentary_switch_event(pqrs::hid::usage_page::keyboard_or_keypad, pqrs::hid::usage::keyboard_or_keypad::keyboard_a), krbn::event_type::key_up, krbn::absolute_time_point(1030), krbn::device_state::grabbed) == false); expect(m.find_probable_stuck_event() == std::nullopt); } }; return 0; }
[ "tekezo@pqrs.org" ]
tekezo@pqrs.org
989a1f96d221366bb9889301e3c107ac67c9c938
7d2607d4449836abf3c9f0148c458098089649c8
/u3/e1/owl.cc
f4656c3fb2d1269e586374362fd30a0008b60ffb
[]
no_license
Timo-Vehvilainen/Cplusplus_Aalto_course
b6233d74f901d1ad80d0308f7f0bebd3633b4fb1
64d5322b85f296be841d755f313320d937c3fa10
refs/heads/master
2021-05-21T06:39:56.954056
2020-04-02T23:40:44
2020-04-02T23:40:44
252,588,264
0
0
null
null
null
null
UTF-8
C++
false
false
122
cc
#include "owl.hh" void Owl::speak(std::ostream& os) const{ os << (this->getName()) << ": WHUU" << std::endl; return; }
[ "noreply@github.com" ]
Timo-Vehvilainen.noreply@github.com
9ad4ad7bfc8a2f76f76c5be012d4ae45ab1bb25a
078aa7712611fc45fc0d1733a2a33eaec404b609
/Svid/ModelUni.h
3110d111943518d7d123d7781423c2e4cec12e76
[]
no_license
koboveb/SVID.T3
eeb80e140c9705fd025d44468d37b1a74a04a763
186ac5e7d6926cfb5a2315d255ed01fa8a2f7bb8
refs/heads/master
2020-08-26T15:16:23.463575
2020-02-23T17:35:31
2020-02-23T17:35:31
217,052,598
0
0
null
null
null
null
UTF-8
C++
false
false
2,538
h
#ifndef MODELUNI_H #define MODELUNI_H #include "StorProject.h" //#include "StorCache.h" //#include "StorData.h" enum typemodel { PROJECT, CACHE, DOCUM, MAXNUM, DATA, DOCKEY, DOCPROJECT }; class ModelUni: public QAbstractTableModel { //Q_OBJECT public: ModelUni(typemodel TypeModel, StorProject *StPr); int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; // bool insertRows(const QModelIndex &parent = QModelIndex()); // bool setData(const QModelIndex &index, const QVariant &value, int role); // void LoadDataToModel(int i); QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; // void SetDocKey (QString ttDocKey); // void setRowsOffset(int i); //void setRowsPage(int i); // int MyColumnCount() const; // int SearchRow(QString TuxtForFind); // QList<int> GetFieldForShowDocum(QString NameDocum) const; // QList<int> GetFieldForShowDialog(QString NameDialog) const; // QList<int> GetFieldForHideDialog(QString NameDialog) const; // QList<QStringList> Get_FieldDialog(); // QStringList GetDialogs() const; // QStringList GetFileds() const; // QStringList GetDocumLevel() const; //Перенести Stor //bool Save(QString DataForSave); // bool canFetchMore(const QModelIndex &parent) const; // void fetchMore(const QModelIndex &parent); // int GetCounRowPlus() const; // int GetPageSize() const; //int GetField_Width(int i) const; // QString GetField_Type(int i) const; // StorProject StorPro; //static StorProject *StorProj; private: StorProject *StorProj; //StorCache StCch; // StorData StDat; QStringList d1; QStringList d2; QList<QStringList> lPoleInfo; // int tCounRowPlus; // количество элементов, добавленные в модель int tRowsOffset; // значение для смещение строк; int tRowsPageMin; // значение миним строки страницы; int tRowsPageBase; // значение базовой строки страницы; int tRowsPageMax; // значение максимал строки страницы; int tPrevI; //Предыдущее значение строки int tPageSize; //размер страницы typemodel TypeModelL; signals: // void numberPopulated(int number); //Разобраться }; #endif // MODELUNI_H
[ "koboveb@gmail.com" ]
koboveb@gmail.com
06c0efb676fe83a70f1a694448535eade4e11bc8
0281aa00053607d3cbc273479d7fb4d3d1c9d359
/board.h
5e931815e4e5977d52029b864b4d29fb41ec87a2
[ "MIT" ]
permissive
mattvchandler/mancala
291c950f2930c7507988d8574ae7c7012da0233c
b43dadb80c9b2e57b8bee8c1322030f597b84d93
refs/heads/master
2021-01-25T07:27:49.387333
2015-10-01T21:34:13
2015-10-01T21:34:13
6,598,500
2
0
null
null
null
null
UTF-8
C++
false
false
2,725
h
// board.h // Mancala board representation // Copyright Matthew Chandler 2014 #ifndef MANCALA_BOARD_H #define MANCALA_BOARD_H #include <thread> #include <vector> #include <sigc++/sigc++.h> namespace Mancala { enum Player {PLAYER_1, PLAYER_2}; // Bead data class Bead { public: Bead(const std::vector<double> & Pos = std::vector<double>({0.0, 0.0}), const int Color_i = 0); // location std::vector<double> pos; // color index int color_i; }; // Bowl data class Bowl { public: Bowl(const int Count = 0, const std::vector<double> & Ul = std::vector<double>({0.0, 0.0}), const double Width = 1.0, const double Height = 1.0); // add a new bead void add_bead(const Mancala::Bead & new_bead); // redistribute the beads void redist_beads(); // base coords for beads std::vector<double> ul; float width, height; // bead data std::vector<Bead> beads; Bowl * next; Bowl * across; }; // Board data class Board { public: Board(const int Num_bowls = 6, const int Num_beads = 4, const int Ai_depth = 10, const bool Extra_rule = true, const bool Capture_rule = true, const bool Collect_rule = true); Board(const Board & b); Board & operator=(const Board & b); public: // set up bowls void set_bowls(); // perform a move // returns true if the move earns an extra turn bool move(const Mancala::Player p, const int i); // is the game over bool finished() const; // heuristics to evaluate the board status int evaluate(const Mancala::Player p) const; // ai method to choose the best move based on evaluate() int choosemove(const Mancala::Player p) const; // non-blocking version // emits signal with int when complete // return id of thread, to be matched with signal std::thread::id choosemove_noblock(const Mancala::Player p) const; // signal for choosemove_noblock typedef sigc::signal<void, int, std::thread::id> signal_choosemove_t; signal_choosemove_t signal_choosemove(); int num_bowls; int num_beads; // maximum depth for ai lookahead (choosemove) int ai_depth; // disable / enable rules bool extra_rule, capture_rule, collect_rule; // board layout vars std::vector<Bowl> top_row; std::vector<Bowl> bottom_row; Bowl l_store; Bowl r_store; signal_choosemove_t signal_choosemove_sig; }; } #endif // MANCALA_BOARD_H
[ "tardarsauce@gmail.com" ]
tardarsauce@gmail.com
9ef79ba2504ea9b149f3fe784b946550fee63c23
d324b3d4ce953574c5945cda64e179f33c36c71b
/php/php-sky/grpc/test/cpp/interop/http2_client.cc
2aa1b1f1b7cce5701ba8c39ebdcc1d518b5eb436
[ "Apache-2.0" ]
permissive
Denticle/docker-base
decc36cc8eb01be1157d0c0417958c2c80ac0d2f
232115202594f4ea334d512dffb03f34451eb147
refs/heads/main
2023-04-21T10:08:29.582031
2021-05-13T07:27:52
2021-05-13T07:27:52
320,431,033
1
1
null
null
null
null
UTF-8
C++
false
false
8,062
cc
/* * * Copyright 2016 gRPC authors. * * 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 "test/cpp/interop/http2_client.h" #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpcpp/channel.h> #include <grpcpp/client_context.h> #include <thread> #include "absl/flags/flag.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/useful.h" #include "src/core/lib/transport/byte_stream.h" #include "src/proto/grpc/testing/messages.pb.h" #include "src/proto/grpc/testing/test.grpc.pb.h" #include "test/cpp/util/create_test_channel.h" #include "test/cpp/util/test_config.h" namespace grpc { namespace testing { namespace { const int kLargeRequestSize = 271828; const int kLargeResponseSize = 314159; } // namespace Http2Client::ServiceStub::ServiceStub(const std::shared_ptr<Channel>& channel) : channel_(channel) { stub_ = TestService::NewStub(channel); } TestService::Stub* Http2Client::ServiceStub::Get() { return stub_.get(); } Http2Client::Http2Client(const std::shared_ptr<Channel>& channel) : serviceStub_(channel), channel_(channel), defaultRequest_(BuildDefaultRequest()) {} bool Http2Client::AssertStatusCode(const Status& s, StatusCode expected_code) { if (s.error_code() == expected_code) { return true; } gpr_log(GPR_ERROR, "Error status code: %d (expected: %d), message: %s", s.error_code(), expected_code, s.error_message().c_str()); abort(); } Status Http2Client::SendUnaryCall(SimpleResponse* response) { ClientContext context; return serviceStub_.Get()->UnaryCall(&context, defaultRequest_, response); } SimpleRequest Http2Client::BuildDefaultRequest() { SimpleRequest request; request.set_response_size(kLargeResponseSize); std::string payload(kLargeRequestSize, '\0'); request.mutable_payload()->set_body(payload.c_str(), kLargeRequestSize); return request; } bool Http2Client::DoRstAfterHeader() { gpr_log(GPR_DEBUG, "Sending RPC and expecting reset stream after header"); SimpleResponse response; AssertStatusCode(SendUnaryCall(&response), grpc::StatusCode::INTERNAL); GPR_ASSERT(!response.has_payload()); // no data should be received gpr_log(GPR_DEBUG, "Done testing reset stream after header"); return true; } bool Http2Client::DoRstAfterData() { gpr_log(GPR_DEBUG, "Sending RPC and expecting reset stream after data"); SimpleResponse response; AssertStatusCode(SendUnaryCall(&response), grpc::StatusCode::INTERNAL); // There is no guarantee that data would be received. gpr_log(GPR_DEBUG, "Done testing reset stream after data"); return true; } bool Http2Client::DoRstDuringData() { gpr_log(GPR_DEBUG, "Sending RPC and expecting reset stream during data"); SimpleResponse response; AssertStatusCode(SendUnaryCall(&response), grpc::StatusCode::INTERNAL); GPR_ASSERT(!response.has_payload()); // no data should be received gpr_log(GPR_DEBUG, "Done testing reset stream during data"); return true; } bool Http2Client::DoGoaway() { gpr_log(GPR_DEBUG, "Sending two RPCs and expecting goaway"); SimpleResponse response; AssertStatusCode(SendUnaryCall(&response), grpc::StatusCode::OK); GPR_ASSERT(response.payload().body() == std::string(kLargeResponseSize, '\0')); // Sleep for one second to give time for client to receive goaway frame. gpr_timespec sleep_time = gpr_time_add( gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(1, GPR_TIMESPAN)); gpr_sleep_until(sleep_time); response.Clear(); AssertStatusCode(SendUnaryCall(&response), grpc::StatusCode::OK); GPR_ASSERT(response.payload().body() == std::string(kLargeResponseSize, '\0')); gpr_log(GPR_DEBUG, "Done testing goaway"); return true; } bool Http2Client::DoPing() { gpr_log(GPR_DEBUG, "Sending RPC and expecting ping"); SimpleResponse response; AssertStatusCode(SendUnaryCall(&response), grpc::StatusCode::OK); GPR_ASSERT(response.payload().body() == std::string(kLargeResponseSize, '\0')); gpr_log(GPR_DEBUG, "Done testing ping"); return true; } void Http2Client::MaxStreamsWorker( const std::shared_ptr<grpc::Channel>& /*channel*/) { SimpleResponse response; AssertStatusCode(SendUnaryCall(&response), grpc::StatusCode::OK); GPR_ASSERT(response.payload().body() == std::string(kLargeResponseSize, '\0')); } bool Http2Client::DoMaxStreams() { gpr_log(GPR_DEBUG, "Testing max streams"); // Make an initial call on the channel to ensure the server's max streams // setting is received SimpleResponse response; AssertStatusCode(SendUnaryCall(&response), grpc::StatusCode::OK); GPR_ASSERT(response.payload().body() == std::string(kLargeResponseSize, '\0')); std::vector<std::thread> test_threads; test_threads.reserve(10); for (int i = 0; i < 10; i++) { test_threads.emplace_back( std::thread(&Http2Client::MaxStreamsWorker, this, channel_)); } for (auto it = test_threads.begin(); it != test_threads.end(); it++) { it->join(); } gpr_log(GPR_DEBUG, "Done testing max streams"); return true; } } // namespace testing } // namespace grpc ABSL_FLAG(int32_t, server_port, 0, "Server port."); ABSL_FLAG(std::string, server_host, "localhost", "Server host to connect to"); ABSL_FLAG(std::string, test_case, "rst_after_header", "Configure different test cases. Valid options are:\n\n" "goaway\n" "max_streams\n" "ping\n" "rst_after_data\n" "rst_after_header\n" "rst_during_data\n"); int main(int argc, char** argv) { grpc::testing::InitTest(&argc, &argv, true); GPR_ASSERT(absl::GetFlag(FLAGS_server_port)); const int host_port_buf_size = 1024; char host_port[host_port_buf_size]; snprintf(host_port, host_port_buf_size, "%s:%d", absl::GetFlag(FLAGS_server_host).c_str(), absl::GetFlag(FLAGS_server_port)); std::shared_ptr<grpc::Channel> channel = grpc::CreateTestChannel(host_port, grpc::testing::INSECURE); GPR_ASSERT(channel->WaitForConnected(gpr_time_add( gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(300, GPR_TIMESPAN)))); grpc::testing::Http2Client client(channel); gpr_log(GPR_INFO, "Testing case: %s", absl::GetFlag(FLAGS_test_case).c_str()); int ret = 0; if (absl::GetFlag(FLAGS_test_case) == "rst_after_header") { client.DoRstAfterHeader(); } else if (absl::GetFlag(FLAGS_test_case) == "rst_after_data") { client.DoRstAfterData(); } else if (absl::GetFlag(FLAGS_test_case) == "rst_during_data") { client.DoRstDuringData(); } else if (absl::GetFlag(FLAGS_test_case) == "goaway") { client.DoGoaway(); } else if (absl::GetFlag(FLAGS_test_case) == "ping") { client.DoPing(); } else if (absl::GetFlag(FLAGS_test_case) == "max_streams") { client.DoMaxStreams(); } else { const char* testcases[] = { "goaway", "max_streams", "ping", "rst_after_data", "rst_after_header", "rst_during_data"}; char* joined_testcases = gpr_strjoin_sep(testcases, GPR_ARRAY_SIZE(testcases), "\n", nullptr); gpr_log(GPR_ERROR, "Unsupported test case %s. Valid options are\n%s", absl::GetFlag(FLAGS_test_case).c_str(), joined_testcases); gpr_free(joined_testcases); ret = 1; } return ret; }
[ "root@localhost.localdomain" ]
root@localhost.localdomain
54ae5f93e86c4891e983cab171954a4a70a0387f
242ad5f61dd260f2b65e2ab0ddf9404d85fbbe13
/_7segmentos/_7segmentos.ino
ee7ae9e079231aff216c446436e4b15f7b4e49c8
[]
no_license
CrissDeveloper/Arduino
6f09a26a9893e148914cc53e684c5f651c5b757b
0cafe602245c6357b26dbcb6bd904c13c2a477d8
refs/heads/master
2021-08-08T16:27:43.234150
2017-11-10T17:51:50
2017-11-10T17:51:50
110,266,397
0
0
null
null
null
null
UTF-8
C++
false
false
2,132
ino
void setup() { for (int i = 6; i <= 13; i++) { pinMode(i,OUTPUT); } } void loop() { //0 = LOW, 1 = HIGH //Zero digitalWrite(13,0); digitalWrite(12,1); digitalWrite(11,1); digitalWrite(10,1); digitalWrite(9,1); digitalWrite(8,1); digitalWrite(7,1); digitalWrite(6,0); delay(1000); //um digitalWrite(13,0); digitalWrite(12,0); digitalWrite(11,0); digitalWrite(10,1); digitalWrite(9,0); digitalWrite(8,0); digitalWrite(7,1); digitalWrite(6,0); delay(1000); //dois digitalWrite(13,1); digitalWrite(12,0); digitalWrite(11,1); digitalWrite(10,1); digitalWrite(9,1); digitalWrite(8,1); digitalWrite(7,0); digitalWrite(6,0); delay(1000); //tres digitalWrite(13,1); digitalWrite(12,0); digitalWrite(11,1); digitalWrite(10,1); digitalWrite(9,0); digitalWrite(8,1); digitalWrite(7,1); digitalWrite(6,0); delay(1000); //quatro digitalWrite(13,1); digitalWrite(12,1); digitalWrite(11,0); digitalWrite(10,1); digitalWrite(9,0); digitalWrite(8,0); digitalWrite(7,1); digitalWrite(6,0); delay(1000); //cinco digitalWrite(13,1); digitalWrite(12,1); digitalWrite(11,1); digitalWrite(10,0); digitalWrite(9,0); digitalWrite(8,1); digitalWrite(7,1); digitalWrite(6,0); delay(1000); //seis digitalWrite(13,1); digitalWrite(12,1); digitalWrite(11,1); digitalWrite(10,0); digitalWrite(9,1); digitalWrite(8,1); digitalWrite(7,1); digitalWrite(6,0); delay(1000); //sete digitalWrite(13,0); digitalWrite(12,0); digitalWrite(11,1); digitalWrite(10,1); digitalWrite(9,0); digitalWrite(8,0); digitalWrite(7,1); digitalWrite(6,0); delay(1000); //oito digitalWrite(13,1); digitalWrite(12,1); digitalWrite(11,1); digitalWrite(10,1); digitalWrite(9,1); digitalWrite(8,1); digitalWrite(7,1); digitalWrite(6,0); delay(1000); //nove digitalWrite(13,1); digitalWrite(12,1); digitalWrite(11,1); digitalWrite(10,1); digitalWrite(9,0); digitalWrite(8,1); digitalWrite(7,1); digitalWrite(6,0); delay(1000); //ponto digitalWrite(6,1); delay(1000); }
[ "cris_valentini94@hotmail.com" ]
cris_valentini94@hotmail.com
3bee157a1e8771587183adfd1dade28ba8e13b0b
f6439b5ed1614fd8db05fa963b47765eae225eb5
/content/browser/renderer_host/media/video_capture_controller_unittest.cc
367095fa02ea6410189b57f76c7340c06f9690f3
[ "BSD-3-Clause" ]
permissive
aranajhonny/chromium
b8a3c975211e1ea2f15b83647b4d8eb45252f1be
caf5bcb822f79b8997720e589334266551a50a13
refs/heads/master
2021-05-11T00:20:34.020261
2018-01-21T03:31:45
2018-01-21T03:31:45
118,301,142
2
0
null
null
null
null
UTF-8
C++
false
false
26,509
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Unit test for VideoCaptureController. #include <string> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "content/browser/renderer_host/media/media_stream_provider.h" #include "content/browser/renderer_host/media/video_capture_controller.h" #include "content/browser/renderer_host/media/video_capture_controller_event_handler.h" #include "content/browser/renderer_host/media/video_capture_manager.h" #include "content/common/gpu/client/gl_helper.h" #include "content/common/media/media_stream_options.h" #include "content/public/test/test_browser_thread_bundle.h" #include "gpu/command_buffer/common/mailbox_holder.h" #include "media/base/video_util.h" #include "media/video/capture/video_capture_types.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_ANDROID) #include "content/browser/renderer_host/test/no_transport_image_transport_factory_android.h" #else #include "content/browser/compositor/test/no_transport_image_transport_factory.h" #endif using ::testing::InSequence; using ::testing::Mock; namespace content { class MockVideoCaptureControllerEventHandler : public VideoCaptureControllerEventHandler { public: explicit MockVideoCaptureControllerEventHandler( VideoCaptureController* controller) : controller_(controller) {} virtual ~MockVideoCaptureControllerEventHandler() {} // These mock methods are delegated to by our fake implementation of // VideoCaptureControllerEventHandler, to be used in EXPECT_CALL(). MOCK_METHOD1(DoBufferCreated, void(const VideoCaptureControllerID&)); MOCK_METHOD1(DoBufferDestroyed, void(const VideoCaptureControllerID&)); MOCK_METHOD1(DoBufferReady, void(const VideoCaptureControllerID&)); MOCK_METHOD1(DoMailboxBufferReady, void(const VideoCaptureControllerID&)); MOCK_METHOD1(DoEnded, void(const VideoCaptureControllerID&)); MOCK_METHOD1(DoError, void(const VideoCaptureControllerID&)); virtual void OnError(const VideoCaptureControllerID& id) OVERRIDE { DoError(id); } virtual void OnBufferCreated(const VideoCaptureControllerID& id, base::SharedMemoryHandle handle, int length, int buffer_id) OVERRIDE { DoBufferCreated(id); } virtual void OnBufferDestroyed(const VideoCaptureControllerID& id, int buffer_id) OVERRIDE { DoBufferDestroyed(id); } virtual void OnBufferReady(const VideoCaptureControllerID& id, int buffer_id, const media::VideoCaptureFormat& format, base::TimeTicks timestamp) OVERRIDE { DoBufferReady(id); base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&VideoCaptureController::ReturnBuffer, base::Unretained(controller_), id, this, buffer_id, 0)); } virtual void OnMailboxBufferReady(const VideoCaptureControllerID& id, int buffer_id, const gpu::MailboxHolder& mailbox_holder, const media::VideoCaptureFormat& format, base::TimeTicks timestamp) OVERRIDE { DoMailboxBufferReady(id); base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&VideoCaptureController::ReturnBuffer, base::Unretained(controller_), id, this, buffer_id, mailbox_holder.sync_point)); } virtual void OnEnded(const VideoCaptureControllerID& id) OVERRIDE { DoEnded(id); // OnEnded() must respond by (eventually) unregistering the client. base::MessageLoop::current()->PostTask(FROM_HERE, base::Bind(base::IgnoreResult(&VideoCaptureController::RemoveClient), base::Unretained(controller_), id, this)); } VideoCaptureController* controller_; }; // Test class. class VideoCaptureControllerTest : public testing::Test { public: VideoCaptureControllerTest() {} virtual ~VideoCaptureControllerTest() {} protected: static const int kPoolSize = 3; virtual void SetUp() OVERRIDE { controller_.reset(new VideoCaptureController()); device_ = controller_->NewDeviceClient().Pass(); client_a_.reset(new MockVideoCaptureControllerEventHandler( controller_.get())); client_b_.reset(new MockVideoCaptureControllerEventHandler( controller_.get())); } virtual void TearDown() OVERRIDE { base::RunLoop().RunUntilIdle(); } scoped_refptr<media::VideoFrame> WrapI420Buffer( const scoped_refptr<media::VideoCaptureDevice::Client::Buffer>& buffer, gfx::Size dimensions) { return media::VideoFrame::WrapExternalPackedMemory( media::VideoFrame::I420, dimensions, gfx::Rect(dimensions), dimensions, reinterpret_cast<uint8*>(buffer->data()), media::VideoFrame::AllocationSize(media::VideoFrame::I420, dimensions), base::SharedMemory::NULLHandle(), base::TimeDelta(), base::Closure()); } scoped_refptr<media::VideoFrame> WrapMailboxBuffer( const scoped_refptr<media::VideoCaptureDevice::Client::Buffer>& buffer, scoped_ptr<gpu::MailboxHolder> holder, const media::VideoFrame::ReleaseMailboxCB& release_cb, gfx::Size dimensions) { return media::VideoFrame::WrapNativeTexture( holder.Pass(), release_cb, dimensions, gfx::Rect(dimensions), dimensions, base::TimeDelta(), media::VideoFrame::ReadPixelsCB()); } TestBrowserThreadBundle bundle_; scoped_ptr<MockVideoCaptureControllerEventHandler> client_a_; scoped_ptr<MockVideoCaptureControllerEventHandler> client_b_; scoped_ptr<VideoCaptureController> controller_; scoped_ptr<media::VideoCaptureDevice::Client> device_; private: DISALLOW_COPY_AND_ASSIGN(VideoCaptureControllerTest); }; // A simple test of VideoCaptureController's ability to add, remove, and keep // track of clients. TEST_F(VideoCaptureControllerTest, AddAndRemoveClients) { media::VideoCaptureParams session_100; session_100.requested_format = media::VideoCaptureFormat( gfx::Size(320, 240), 30, media::PIXEL_FORMAT_I420); media::VideoCaptureParams session_200 = session_100; media::VideoCaptureParams session_300 = session_100; media::VideoCaptureParams session_400 = session_100; // Intentionally use the same route ID for two of the clients: the device_ids // are a per-VideoCaptureHost namespace, and can overlap across hosts. const VideoCaptureControllerID client_a_route_1(44); const VideoCaptureControllerID client_a_route_2(30); const VideoCaptureControllerID client_b_route_1(30); const VideoCaptureControllerID client_b_route_2(1); // Clients in controller: [] ASSERT_EQ(0, controller_->GetClientCount()) << "Client count should initially be zero."; controller_->AddClient(client_a_route_1, client_a_.get(), base::kNullProcessHandle, 100, session_100); // Clients in controller: [A/1] ASSERT_EQ(1, controller_->GetClientCount()) << "Adding client A/1 should bump client count."; controller_->AddClient(client_a_route_2, client_a_.get(), base::kNullProcessHandle, 200, session_200); // Clients in controller: [A/1, A/2] ASSERT_EQ(2, controller_->GetClientCount()) << "Adding client A/2 should bump client count."; controller_->AddClient(client_b_route_1, client_b_.get(), base::kNullProcessHandle, 300, session_300); // Clients in controller: [A/1, A/2, B/1] ASSERT_EQ(3, controller_->GetClientCount()) << "Adding client B/1 should bump client count."; ASSERT_EQ(200, controller_->RemoveClient(client_a_route_2, client_a_.get())) << "Removing client A/1 should return its session_id."; // Clients in controller: [A/1, B/1] ASSERT_EQ(2, controller_->GetClientCount()); ASSERT_EQ(static_cast<int>(kInvalidMediaCaptureSessionId), controller_->RemoveClient(client_a_route_2, client_a_.get())) << "Removing a nonexistant client should fail."; // Clients in controller: [A/1, B/1] ASSERT_EQ(2, controller_->GetClientCount()); ASSERT_EQ(300, controller_->RemoveClient(client_b_route_1, client_b_.get())) << "Removing client B/1 should return its session_id."; // Clients in controller: [A/1] ASSERT_EQ(1, controller_->GetClientCount()); controller_->AddClient(client_b_route_2, client_b_.get(), base::kNullProcessHandle, 400, session_400); // Clients in controller: [A/1, B/2] EXPECT_CALL(*client_a_, DoEnded(client_a_route_1)).Times(1); controller_->StopSession(100); // Session 100 == client A/1 Mock::VerifyAndClearExpectations(client_a_.get()); ASSERT_EQ(2, controller_->GetClientCount()) << "Client should be closed but still exist after StopSession."; // Clients in controller: [A/1 (closed, removal pending), B/2] base::RunLoop().RunUntilIdle(); // Clients in controller: [B/2] ASSERT_EQ(1, controller_->GetClientCount()) << "Client A/1 should be deleted by now."; controller_->StopSession(200); // Session 200 does not exist anymore // Clients in controller: [B/2] ASSERT_EQ(1, controller_->GetClientCount()) << "Stopping non-existant session 200 should be a no-op."; controller_->StopSession(256); // Session 256 never existed. // Clients in controller: [B/2] ASSERT_EQ(1, controller_->GetClientCount()) << "Stopping non-existant session 256 should be a no-op."; ASSERT_EQ(static_cast<int>(kInvalidMediaCaptureSessionId), controller_->RemoveClient(client_a_route_1, client_a_.get())) << "Removing already-removed client A/1 should fail."; // Clients in controller: [B/2] ASSERT_EQ(1, controller_->GetClientCount()) << "Removing non-existant session 200 should be a no-op."; ASSERT_EQ(400, controller_->RemoveClient(client_b_route_2, client_b_.get())) << "Removing client B/2 should return its session_id."; // Clients in controller: [] ASSERT_EQ(0, controller_->GetClientCount()) << "Client count should return to zero after all clients are gone."; } static void CacheSyncPoint(uint32* called_release_sync_point, uint32 release_sync_point) { *called_release_sync_point = release_sync_point; } // This test will connect and disconnect several clients while simulating an // active capture device being started and generating frames. It runs on one // thread and is intended to behave deterministically. TEST_F(VideoCaptureControllerTest, NormalCaptureMultipleClients) { // VideoCaptureController::ReturnBuffer() uses ImageTransportFactory. #if defined(OS_ANDROID) ImageTransportFactoryAndroid::InitializeForUnitTests( scoped_ptr<ImageTransportFactoryAndroid>( new NoTransportImageTransportFactoryAndroid)); #else ImageTransportFactory::InitializeForUnitTests( scoped_ptr<ImageTransportFactory>(new NoTransportImageTransportFactory)); #endif media::VideoCaptureParams session_100; session_100.requested_format = media::VideoCaptureFormat( gfx::Size(320, 240), 30, media::PIXEL_FORMAT_I420); media::VideoCaptureParams session_200 = session_100; media::VideoCaptureParams session_300 = session_100; media::VideoCaptureParams session_1 = session_100; gfx::Size capture_resolution(444, 200); // The device format needn't match the VideoCaptureParams (the camera can do // what it wants). Pick something random. media::VideoCaptureFormat device_format( gfx::Size(10, 10), 25, media::PIXEL_FORMAT_RGB24); const VideoCaptureControllerID client_a_route_1(0xa1a1a1a1); const VideoCaptureControllerID client_a_route_2(0xa2a2a2a2); const VideoCaptureControllerID client_b_route_1(0xb1b1b1b1); const VideoCaptureControllerID client_b_route_2(0xb2b2b2b2); // Start with two clients. controller_->AddClient(client_a_route_1, client_a_.get(), base::kNullProcessHandle, 100, session_100); controller_->AddClient(client_b_route_1, client_b_.get(), base::kNullProcessHandle, 300, session_300); controller_->AddClient(client_a_route_2, client_a_.get(), base::kNullProcessHandle, 200, session_200); ASSERT_EQ(3, controller_->GetClientCount()); // Now, simulate an incoming captured buffer from the capture device. As a // side effect this will cause the first buffer to be shared with clients. uint8 buffer_no = 1; scoped_refptr<media::VideoCaptureDevice::Client::Buffer> buffer; buffer = device_->ReserveOutputBuffer(media::VideoFrame::I420, capture_resolution); ASSERT_TRUE(buffer); memset(buffer->data(), buffer_no++, buffer->size()); { InSequence s; EXPECT_CALL(*client_a_, DoBufferCreated(client_a_route_1)).Times(1); EXPECT_CALL(*client_a_, DoBufferReady(client_a_route_1)).Times(1); } { InSequence s; EXPECT_CALL(*client_b_, DoBufferCreated(client_b_route_1)).Times(1); EXPECT_CALL(*client_b_, DoBufferReady(client_b_route_1)).Times(1); } { InSequence s; EXPECT_CALL(*client_a_, DoBufferCreated(client_a_route_2)).Times(1); EXPECT_CALL(*client_a_, DoBufferReady(client_a_route_2)).Times(1); } device_->OnIncomingCapturedVideoFrame( buffer, media::VideoCaptureFormat(capture_resolution, device_format.frame_rate, media::PIXEL_FORMAT_I420), WrapI420Buffer(buffer, capture_resolution), base::TimeTicks()); buffer = NULL; base::RunLoop().RunUntilIdle(); Mock::VerifyAndClearExpectations(client_a_.get()); Mock::VerifyAndClearExpectations(client_b_.get()); // Second buffer which ought to use the same shared memory buffer. In this // case pretend that the Buffer pointer is held by the device for a long // delay. This shouldn't affect anything. buffer = device_->ReserveOutputBuffer(media::VideoFrame::I420, capture_resolution); ASSERT_TRUE(buffer); memset(buffer->data(), buffer_no++, buffer->size()); device_->OnIncomingCapturedVideoFrame( buffer, media::VideoCaptureFormat(capture_resolution, device_format.frame_rate, media::PIXEL_FORMAT_I420), WrapI420Buffer(buffer, capture_resolution), base::TimeTicks()); buffer = NULL; // The buffer should be delivered to the clients in any order. EXPECT_CALL(*client_a_, DoBufferReady(client_a_route_1)).Times(1); EXPECT_CALL(*client_b_, DoBufferReady(client_b_route_1)).Times(1); EXPECT_CALL(*client_a_, DoBufferReady(client_a_route_2)).Times(1); base::RunLoop().RunUntilIdle(); Mock::VerifyAndClearExpectations(client_a_.get()); Mock::VerifyAndClearExpectations(client_b_.get()); // Add a fourth client now that some buffers have come through. controller_->AddClient(client_b_route_2, client_b_.get(), base::kNullProcessHandle, 1, session_1); Mock::VerifyAndClearExpectations(client_b_.get()); // Third, fourth, and fifth buffers. Pretend they all arrive at the same time. for (int i = 0; i < kPoolSize; i++) { buffer = device_->ReserveOutputBuffer(media::VideoFrame::I420, capture_resolution); ASSERT_TRUE(buffer); memset(buffer->data(), buffer_no++, buffer->size()); device_->OnIncomingCapturedVideoFrame( buffer, media::VideoCaptureFormat(capture_resolution, device_format.frame_rate, media::PIXEL_FORMAT_I420), WrapI420Buffer(buffer, capture_resolution), base::TimeTicks()); buffer = NULL; } // ReserveOutputBuffer ought to fail now, because the pool is depleted. ASSERT_FALSE(device_->ReserveOutputBuffer(media::VideoFrame::I420, capture_resolution)); // The new client needs to be told of 3 buffers; the old clients only 2. EXPECT_CALL(*client_b_, DoBufferCreated(client_b_route_2)).Times(kPoolSize); EXPECT_CALL(*client_b_, DoBufferReady(client_b_route_2)).Times(kPoolSize); EXPECT_CALL(*client_a_, DoBufferCreated(client_a_route_1)) .Times(kPoolSize - 1); EXPECT_CALL(*client_a_, DoBufferReady(client_a_route_1)).Times(kPoolSize); EXPECT_CALL(*client_a_, DoBufferCreated(client_a_route_2)) .Times(kPoolSize - 1); EXPECT_CALL(*client_a_, DoBufferReady(client_a_route_2)).Times(kPoolSize); EXPECT_CALL(*client_b_, DoBufferCreated(client_b_route_1)) .Times(kPoolSize - 1); EXPECT_CALL(*client_b_, DoBufferReady(client_b_route_1)).Times(kPoolSize); base::RunLoop().RunUntilIdle(); Mock::VerifyAndClearExpectations(client_a_.get()); Mock::VerifyAndClearExpectations(client_b_.get()); // Now test the interaction of client shutdown and buffer delivery. // Kill A1 via renderer disconnect (synchronous). controller_->RemoveClient(client_a_route_1, client_a_.get()); // Kill B1 via session close (posts a task to disconnect). EXPECT_CALL(*client_b_, DoEnded(client_b_route_1)).Times(1); controller_->StopSession(300); // Queue up another buffer. buffer = device_->ReserveOutputBuffer(media::VideoFrame::I420, capture_resolution); ASSERT_TRUE(buffer); memset(buffer->data(), buffer_no++, buffer->size()); device_->OnIncomingCapturedVideoFrame( buffer, media::VideoCaptureFormat(capture_resolution, device_format.frame_rate, media::PIXEL_FORMAT_I420), WrapI420Buffer(buffer, capture_resolution), base::TimeTicks()); buffer = NULL; buffer = device_->ReserveOutputBuffer(media::VideoFrame::I420, capture_resolution); { // Kill A2 via session close (posts a task to disconnect, but A2 must not // be sent either of these two buffers). EXPECT_CALL(*client_a_, DoEnded(client_a_route_2)).Times(1); controller_->StopSession(200); } ASSERT_TRUE(buffer); memset(buffer->data(), buffer_no++, buffer->size()); device_->OnIncomingCapturedVideoFrame( buffer, media::VideoCaptureFormat(capture_resolution, device_format.frame_rate, media::PIXEL_FORMAT_I420), WrapI420Buffer(buffer, capture_resolution), base::TimeTicks()); buffer = NULL; // B2 is the only client left, and is the only one that should // get the buffer. EXPECT_CALL(*client_b_, DoBufferReady(client_b_route_2)).Times(2); base::RunLoop().RunUntilIdle(); Mock::VerifyAndClearExpectations(client_a_.get()); Mock::VerifyAndClearExpectations(client_b_.get()); // Allocate all buffers from the buffer pool, half as SHM buffer and half as // mailbox buffers. Make sure of different counts though. int shm_buffers = kPoolSize / 2; int mailbox_buffers = kPoolSize - shm_buffers; if (shm_buffers == mailbox_buffers) { shm_buffers--; mailbox_buffers++; } for (int i = 0; i < shm_buffers; ++i) { buffer = device_->ReserveOutputBuffer(media::VideoFrame::I420, capture_resolution); ASSERT_TRUE(buffer); device_->OnIncomingCapturedVideoFrame( buffer, media::VideoCaptureFormat(capture_resolution, device_format.frame_rate, media::PIXEL_FORMAT_I420), WrapI420Buffer(buffer, capture_resolution), base::TimeTicks()); buffer = NULL; } std::vector<uint32> mailbox_syncpoints(mailbox_buffers); std::vector<uint32> release_syncpoints(mailbox_buffers); #if defined(OS_ANDROID) GLHelper* gl_helper = ImageTransportFactoryAndroid::GetInstance()->GetGLHelper(); #else GLHelper* gl_helper = ImageTransportFactory::GetInstance()->GetGLHelper(); #endif for (int i = 0; i < mailbox_buffers; ++i) { buffer = device_->ReserveOutputBuffer(media::VideoFrame::NATIVE_TEXTURE, gfx::Size(0, 0)); ASSERT_TRUE(buffer); mailbox_syncpoints[i] = gl_helper->InsertSyncPoint(); device_->OnIncomingCapturedVideoFrame( buffer, media::VideoCaptureFormat(capture_resolution, device_format.frame_rate, media::PIXEL_FORMAT_TEXTURE), WrapMailboxBuffer(buffer, make_scoped_ptr(new gpu::MailboxHolder( gpu::Mailbox(), 0, mailbox_syncpoints[i])), base::Bind(&CacheSyncPoint, &release_syncpoints[i]), capture_resolution), base::TimeTicks()); buffer = NULL; } // ReserveOutputBuffers ought to fail now regardless of buffer format, because // the pool is depleted. ASSERT_FALSE(device_->ReserveOutputBuffer(media::VideoFrame::I420, capture_resolution)); ASSERT_FALSE(device_->ReserveOutputBuffer(media::VideoFrame::NATIVE_TEXTURE, gfx::Size(0, 0))); EXPECT_CALL(*client_b_, DoBufferReady(client_b_route_2)).Times(shm_buffers); EXPECT_CALL(*client_b_, DoMailboxBufferReady(client_b_route_2)) .Times(mailbox_buffers); base::RunLoop().RunUntilIdle(); for (size_t i = 0; i < mailbox_syncpoints.size(); ++i) { // A new release sync point must be inserted when the video frame is // returned to the Browser process. // See: MockVideoCaptureControllerEventHandler::OnMailboxBufferReady() and // VideoCaptureController::ReturnBuffer() ASSERT_NE(mailbox_syncpoints[i], release_syncpoints[i]); } Mock::VerifyAndClearExpectations(client_b_.get()); #if defined(OS_ANDROID) ImageTransportFactoryAndroid::TerminateForUnitTests(); #else ImageTransportFactory::Terminate(); #endif } // Exercises the OnError() codepath of VideoCaptureController, and tests the // behavior of various operations after the error state has been signalled. TEST_F(VideoCaptureControllerTest, ErrorBeforeDeviceCreation) { media::VideoCaptureParams session_100; session_100.requested_format = media::VideoCaptureFormat( gfx::Size(320, 240), 30, media::PIXEL_FORMAT_I420); media::VideoCaptureParams session_200 = session_100; const gfx::Size capture_resolution(320, 240); const VideoCaptureControllerID route_id(0x99); // Start with one client. controller_->AddClient( route_id, client_a_.get(), base::kNullProcessHandle, 100, session_100); device_->OnError("Test Error"); EXPECT_CALL(*client_a_, DoError(route_id)).Times(1); base::RunLoop().RunUntilIdle(); Mock::VerifyAndClearExpectations(client_a_.get()); // Second client connects after the error state. It also should get told of // the error. EXPECT_CALL(*client_b_, DoError(route_id)).Times(1); controller_->AddClient( route_id, client_b_.get(), base::kNullProcessHandle, 200, session_200); base::RunLoop().RunUntilIdle(); Mock::VerifyAndClearExpectations(client_b_.get()); scoped_refptr<media::VideoCaptureDevice::Client::Buffer> buffer = device_->ReserveOutputBuffer(media::VideoFrame::I420, capture_resolution); ASSERT_TRUE(buffer); device_->OnIncomingCapturedVideoFrame( buffer, media::VideoCaptureFormat( capture_resolution, 30, media::PIXEL_FORMAT_I420), WrapI420Buffer(buffer, capture_resolution), base::TimeTicks()); buffer = NULL; base::RunLoop().RunUntilIdle(); } // Exercises the OnError() codepath of VideoCaptureController, and tests the // behavior of various operations after the error state has been signalled. TEST_F(VideoCaptureControllerTest, ErrorAfterDeviceCreation) { media::VideoCaptureParams session_100; session_100.requested_format = media::VideoCaptureFormat( gfx::Size(320, 240), 30, media::PIXEL_FORMAT_I420); media::VideoCaptureParams session_200 = session_100; const VideoCaptureControllerID route_id(0x99); // Start with one client. controller_->AddClient( route_id, client_a_.get(), base::kNullProcessHandle, 100, session_100); media::VideoCaptureFormat device_format( gfx::Size(10, 10), 25, media::PIXEL_FORMAT_ARGB); // Start the device. Then, before the first buffer, signal an error and // deliver the buffer. The error should be propagated to clients; the buffer // should not be. base::RunLoop().RunUntilIdle(); Mock::VerifyAndClearExpectations(client_a_.get()); const gfx::Size dims(320, 240); scoped_refptr<media::VideoCaptureDevice::Client::Buffer> buffer = device_->ReserveOutputBuffer(media::VideoFrame::I420, dims); ASSERT_TRUE(buffer); device_->OnError("Test error"); device_->OnIncomingCapturedVideoFrame( buffer, media::VideoCaptureFormat( dims, device_format.frame_rate, media::PIXEL_FORMAT_I420), WrapI420Buffer(buffer, dims), base::TimeTicks()); buffer = NULL; EXPECT_CALL(*client_a_, DoError(route_id)).Times(1); base::RunLoop().RunUntilIdle(); Mock::VerifyAndClearExpectations(client_a_.get()); // Second client connects after the error state. It also should get told of // the error. EXPECT_CALL(*client_b_, DoError(route_id)).Times(1); controller_->AddClient( route_id, client_b_.get(), base::kNullProcessHandle, 200, session_200); Mock::VerifyAndClearExpectations(client_b_.get()); } } // namespace content
[ "jhonnyjosearana@gmail.com" ]
jhonnyjosearana@gmail.com
75b834f49f40d5bdfe62a029982b2d58bb61b660
ad2d392f73f6e26b4f082fb0251b241a7ebf85a8
/abc/reiwa/188/d.cpp
c49f0e0681be9f26755372e32607a302e1f2c68c
[]
no_license
miyamotononno/atcoder
b293ac3b25397567aa93a179d1af34add492518b
cf29d48c7448464d33a9d7ad69affd771319fe3c
refs/heads/master
2022-01-09T23:03:07.022772
2022-01-08T14:12:13
2022-01-08T14:12:13
187,175,157
0
0
null
2019-06-12T16:03:24
2019-05-17T08:11:58
Python
UTF-8
C++
false
false
1,102
cpp
#include <algorithm> #include <iostream> #include <iomanip> #include <cassert> #include <cstring> #include <string> #include <vector> #include <random> #include <queue> #include <cmath> #include <unordered_map> #include <set> #include <map> #define INCANT cin.tie(0), cout.tie(0), ios::sync_with_stdio(0), cout << fixed << setprecision(20); #define rep(i,n) for (int i=0; i<n;++i) #define ALL(a) (a).begin(),(a).end() typedef long long ll; using namespace std; const ll MOD = 1e9+7LL; const int INF = 2e9; int N; ll C; typedef pair<int, ll> P; vector<P> D; int main() { INCANT; cin >> N >> C; int a,b,c; rep(i, N) { cin >> a >> b >> c; D.push_back(P(a-1, c)); D.push_back(P(b, -c)); // この次の日から支払い停止なので } sort(ALL(D)); int start = 0; ll price=0; ll ans = 0ll; for (int i=0; i<D.size(); i++) { if (i==0) { // この日までは払わなくていい price = D[i].second; continue; } ll day = D[i].first - D[i-1].first; ans+=day*min(C, price); price += D[i].second; } cout << ans << "\n"; return 0; }
[ "miyamoto-nozomu@g.ecc.u-tokyo.ac.jp" ]
miyamoto-nozomu@g.ecc.u-tokyo.ac.jp
3477b4babc87921244789b332564cb1f78cdbb8f
8889b483759190744615669d865698ccd0e05033
/src/rpcmining.cpp
00c50ba6bf82678735c94841f159f25af9e7fc6e
[ "MIT" ]
permissive
LatiumCoin/Latium
b22d576ece939101fc449265a1c2c9cf0f6bb863
9405d45fc954ec7d214b12a148b649fb8fb0ef35
refs/heads/master
2020-06-06T05:18:20.875447
2014-08-19T20:53:09
2014-08-19T20:53:09
19,510,310
6
7
null
2017-05-26T12:51:23
2014-05-06T20:52:10
C++
UTF-8
C++
false
false
19,537
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "db.h" #include "init.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; Value getgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getgenerate\n" "Returns true or false."); return GetBoolArg("-gen"); } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setgenerate <generate> [genproclimit]\n" "<generate> is true or false to turn generation on or off.\n" "Generation is limited to [genproclimit] processors, -1 is unlimited."); bool fGenerate = true; if (params.size() > 0) fGenerate = params[0].get_bool(); if (params.size() > 1) { int nGenProcLimit = params[1].get_int(); mapArgs["-genproclimit"] = itostr(nGenProcLimit); if (nGenProcLimit == 0) fGenerate = false; } mapArgs["-gen"] = (fGenerate ? "1" : "0"); GenerateBitcoins(fGenerate, pwalletMain); return Value::null; } Value gethashespersec(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gethashespersec\n" "Returns a recent hashes per second performance measurement while generating."); if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("generate", GetBoolArg("-gen"))); obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1))); obj.push_back(Pair("hashespersec", gethashespersec(params, false))); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } // Litecoin: Return average network hashes per second based on last number of blocks. Value GetNetworkHashPS(int lookup) { if (pindexBest == NULL) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pindexBest->nHeight % 2016 + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pindexBest->nHeight) lookup = pindexBest->nHeight; CBlockIndex* pindexPrev = pindexBest; for (int i = 0; i < lookup; i++) pindexPrev = pindexPrev->pprev; double timeDiff = pindexBest->GetBlockTime() - pindexPrev->GetBlockTime(); double timePerBlock = timeDiff / lookup; return (boost::int64_t)(((double)GetDifficulty() * pow(2.0, 32)) / timePerBlock); } Value getnetworkhashps(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnetworkhashps [blocks]\n" "Returns the estimated network hashes per second based on the last 120 blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change."); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120); } Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(-9, "Latium is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "Latium is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; static vector<CBlock*> vNewBlock; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } nTransactionsUpdatedLast = nTransactionsUpdated; pindexPrev = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(pwalletMain); if (!pblock) throw JSONRPCError(-7, "Out of memory"); vNewBlock.push_back(pblock); } // Update nTime pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Prebuild hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; BOOST_FOREACH(uint256 merkleh, merkle) { merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); vector<unsigned char> coinbase; if(params.size() == 2) coinbase = ParseHex(params[1].get_str()); if (vchData.size() != 128) throw JSONRPCError(-8, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; if(coinbase.size() == 0) pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; else CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK! pblock->hashMerkleRoot = pblock->BuildMerkleTree(); if (!pblock->SignBlock(*pwalletMain)) throw JSONRPCError(-100, "Unable to sign block, wallet locked?"); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Latium is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Latium is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlock*> vNewBlock; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(pwalletMain); if (!pblock) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlock.push_back(pblock); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); if (!pblock->SignBlock(*pwalletMain)) throw JSONRPCError(-100, "Unable to sign block, wallet locked?"); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Latium is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Latium is downloading blocks..."); static CReserveKey reservekey(pwalletMain); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblock) { delete pblock; pblock = NULL; } pblock = CreateNewBlock(pwalletMain); if (!pblock) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; CTxDB txdb("r"); BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase() || tx.IsCoinStake()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut()))); Array deps; BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs) { if (setTxIndex.count(inp.first)) deps.push_back(setTxIndex[inp.first]); } entry.push_back(Pair("depends", deps)); int64_t nSigOps = tx.GetLegacySigOpCount(); nSigOps += tx.GetP2SHSigOpCount(mapInputs); entry.push_back(Pair("sigops", nSigOps)); } transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock block; try { ssBlock >> block; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } if (!block.SignBlock(*pwalletMain)) throw JSONRPCError(-100, "Unable to sign block, wallet locked?"); bool fAccepted = ProcessBlock(NULL, &block); if (!fAccepted) return "rejected"; return Value::null; }
[ "buckygreen1@gmail.com" ]
buckygreen1@gmail.com